app_dongri.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. from flask import Flask, render_template
  4. from flask_socketio import SocketIO, emit
  5. from scriptBase.comon import *
  6. import pyautogui
  7. import base64
  8. import threading
  9. from dongri_task import *
  10. from collections import deque
  11. import json
  12. from concurrent.futures import ThreadPoolExecutor
  13. from flask_caching import Cache
  14. # 全局线程池,限制最大线程数为1
  15. executor = ThreadPoolExecutor(max_workers=1)
  16. cache = Cache(config={'CACHE_TYPE': 'null'}) # 使用 null 缓存类型
  17. app = Flask(__name__)
  18. cache.init_app(app)
  19. app.config['TEMPLATES_AUTO_RELOAD'] = True
  20. socketio = SocketIO(app, cors_allowed_origins="*")
  21. event = threading.Event()
  22. g_status_list = []
  23. last_time = 0.0
  24. task_queue = deque()
  25. last_process = ''
  26. isGameBegin = True
  27. autoTask = None
  28. isReset = False
  29. g_times = 0
  30. g_cureNum = 500
  31. g_switch = False
  32. @app.after_request
  33. def add_no_cache_header(response):
  34. # 添加禁用缓存的响应头
  35. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  36. response.headers["Pragma"] = "no-cache"
  37. response.headers["Expires"] = "0"
  38. return response
  39. def thread_runTask():
  40. global last_process
  41. global task_queue,isReset
  42. while True:
  43. if event.is_set():
  44. task_queue.clear()
  45. if len(task_queue) != 0:
  46. # 初始时间
  47. current_time = time.time()
  48. task = task_queue[-1]
  49. task_queue.pop()
  50. last_process = task.name
  51. task.run()
  52. cost_time = int(time.time() - current_time)
  53. send_status(f"{task.name} 执行完成,耗时{cost_time}秒")
  54. myTimeSleep_small()
  55. else:
  56. myTimeSleep_big()
  57. if isReset:
  58. isReset = False
  59. cfg = read_cfg()
  60. if cfg['switch']:
  61. config = read_Dailycfg()
  62. type = update_rungame_type(config)
  63. print(f'启动游戏{type}')
  64. restart_game(type)
  65. else:
  66. restart_game(0)
  67. @app.route('/')
  68. def index():
  69. return render_template('index_dongri.html')
  70. @socketio.on('connect')
  71. def handle_connect():
  72. print('Client connected')
  73. @socketio.on('disconnect')
  74. def handle_disconnect():
  75. print('Client disconnected')
  76. def send_hint(msg):#数组信息
  77. emit('processing_hint', msg)
  78. def send_todo():
  79. emit('processing_todo', get_todo_msgList())
  80. def send_status(msg):#软件执行状态
  81. global g_status_list, g_times
  82. try:
  83. if not msg == "":
  84. # 添加新的状态消息和时间到列表
  85. timestamp = datetime.now().strftime('%H:%M:%S') # 获取当前时间
  86. status_entry = {'msg': msg, 'time': timestamp} # 存储消息和时间
  87. g_status_list.append(status_entry)
  88. # 如果列表超过 5 条,移除最早的一条
  89. if len(g_status_list) > 5:
  90. g_status_list.pop(0)
  91. else:
  92. sendStr = ''
  93. for item in g_status_list:
  94. sendStr = f"{g_times}次-{item['time']}-{item['msg']}<br>" + sendStr
  95. #print(sendStr)
  96. emit('processing_status', sendStr)
  97. # 如果消息是 "结束",发送所有状态并清空列表
  98. if msg == "结束":
  99. g_status_list = [] # 清空列表
  100. event.clear()
  101. except Exception as e:
  102. print(f"Error in send_status: {e}")
  103. return
  104. @socketio.on('monitor_begin')
  105. def monitor_begin():
  106. global last_time, last_process
  107. current_time = time.time()
  108. elapsed_time = current_time - last_time
  109. if elapsed_time < 0.5:
  110. return
  111. last_time = current_time
  112. regionRet, regionPos = game_region()
  113. screenshot = pyautogui.screenshot(region=regionPos)
  114. #binary_img = binarize_image(screenshot)
  115. compressed_data = compress_image(screenshot)
  116. image_data_base64 = base64.b64encode(compressed_data).decode('utf-8')
  117. socketio.emit('image_data', image_data_base64)
  118. task_arr = []
  119. if not event.is_set():
  120. task_arr.append(last_process)
  121. for item in reversed(task_queue):
  122. task_arr.append(item.name)
  123. send_hint(json.dumps(task_arr, ensure_ascii=False))
  124. send_todo()
  125. send_status('')
  126. #print("send img")
  127. @socketio.on('end_script')
  128. def handle_end_script():
  129. event.set()
  130. @socketio.on('end_game')
  131. def handle_end_game():
  132. event.set()
  133. task_close_game()
  134. send_status("结束2")
  135. event.clear()
  136. @socketio.on('get_title')
  137. def handle_get_title():
  138. str = task_getComputerName()
  139. dst = str + ' machine'
  140. emit('processing_title', dst)
  141. @socketio.on('reset_script')
  142. def handle_reset_script():
  143. python = sys.executable
  144. while '--reset' in sys.argv:
  145. # 从 sys.argv 列表中删除 --reset 参数
  146. sys.argv.remove('--reset')
  147. os.execl(python, python, *sys.argv)
  148. @socketio.on('restart_game')
  149. def handle_restart_game():
  150. python = sys.executable
  151. os.execl(python, python, *sys.argv, '--reset')
  152. @socketio.on('close_game')
  153. def handle_close_game():
  154. task_close_game()
  155. send_status("结束2")
  156. event.clear()
  157. @socketio.on('read_cfg')
  158. def handle_read_cfg():
  159. cfg = read_cfg()
  160. emit('processing_cfg', cfg)
  161. def restart_game(type=0):
  162. global isGameBegin
  163. isGameBegin = False
  164. while True:
  165. task_close_game()
  166. if True == task_start_game(type):
  167. break
  168. else:
  169. send_status("启动失败")
  170. isGameBegin = True
  171. send_status("结束")
  172. config = read_cfg()
  173. print("config", config)
  174. auto_task(config)
  175. def auto_participate():
  176. task_queue.appendleft(task_returnAllLine())
  177. timeout = 40 * 60
  178. start_time = time.time() # 记录开始时间
  179. while not event.is_set():
  180. if len(task_queue) < 4:
  181. task_queue.appendleft(task_paticipateInTeam())
  182. task_queue.appendleft(task_paticipateInTeam())
  183. task_queue.appendleft(task_paticipateInTeam())
  184. task_queue.appendleft(task_checkHelp(True))
  185. myTimeSleep_big()
  186. # 每次循环检查已用时间
  187. current_time = time.time()
  188. elapsed_time = current_time - start_time
  189. if elapsed_time >= timeout:
  190. handle_restart_game()
  191. break
  192. def auto_ranshuang():
  193. timeout = 40 * 60
  194. start_time = time.time() # 记录开始时间
  195. while not event.is_set():
  196. if len(task_queue) < 4:
  197. task_queue.appendleft(task_fight_ranshuang())
  198. myTimeSleep_big()
  199. current_time = time.time()
  200. elapsed_time = current_time - start_time
  201. if elapsed_time >= timeout:
  202. handle_restart_game()
  203. break
  204. def auto_palace():
  205. global g_times, g_cureNum
  206. timeout = 180 * 60
  207. start_time = time.time() # 记录开始时间
  208. read_cfg()
  209. while not event.is_set():
  210. if len(task_queue) < 4:
  211. task_queue.appendleft(task_cure(True, g_cureNum))
  212. task_queue.appendleft(task_cure(True, g_cureNum))
  213. task_queue.appendleft(task_checkHelp())
  214. task_queue.appendleft(task_fight_enemy())
  215. task_queue.appendleft(task_checkHelp())
  216. myTimeSleep_big()
  217. current_time = time.time()
  218. elapsed_time = current_time - start_time
  219. if elapsed_time >= timeout:
  220. handle_restart_game()
  221. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True, isDailyConfig = False, train_type = 'None', always = False):
  222. global g_times, g_cureNum
  223. collectArr = [int(x) for x in isMaxCollect.split(",")]
  224. print("collectArr", collectArr)
  225. while not event.is_set():
  226. isLoginTask = True
  227. fight_big_monster_times = 0
  228. config = read_Dailycfg()
  229. print("config", config)
  230. g_times += 1
  231. if check_daily_config(config):
  232. today = datetime.now().strftime('%Y-%m-%d')
  233. isLoginTask = bool(config['daily'][today]["login_task"])
  234. fight_big_monster_times = int(config['daily'][today]["fight_bigMonster_times"])
  235. else:
  236. set_login_task(config, False)
  237. set_fight_big_monster_times(config, 0)
  238. clean_old_daily_configs(config)
  239. isLoginTask = False
  240. fight_big_monster_times = 0
  241. write_Dailycfg(config)
  242. send_status(f"isLoginTask:{isLoginTask}, fight_big_monster_times:{fight_big_monster_times}")
  243. if not isLoginTask:
  244. task_queue.appendleft(task_checkMaster())
  245. set_login_task(config, True)
  246. write_Dailycfg(config)
  247. if isDailyConfig and fight_big_monster_times < 10:
  248. isSuccess = task_fightMonster(isAddStrengh, True, isSimple)
  249. if isSuccess:
  250. set_fight_big_monster_times(config, fight_big_monster_times + 1)
  251. write_Dailycfg(config)
  252. if activity == 'lianmeng':
  253. task_queue.appendleft(task_activity_lianmeng())
  254. elif activity == 'cure':
  255. task_queue.appendleft(task_cure(True, g_cureNum))
  256. elif activity == 'only_cure':
  257. task_queue.appendleft(task_cure(True, g_cureNum))
  258. task_queue.appendleft(task_cure(True, g_cureNum))
  259. task_queue.appendleft(task_cure(True, g_cureNum))
  260. return
  261. if g_times % 3 == 1:
  262. task_queue.appendleft(check_safe_collect())
  263. if isSimple == False:
  264. task_queue.appendleft(task_information())
  265. task_queue.appendleft(check_buildOrResearch())
  266. task_queue.appendleft(task_cure(True, g_cureNum))
  267. task_queue.appendleft(task_checkStoreRoom())
  268. if not isSimple:
  269. if isJina == 'jina':
  270. task_queue.appendleft(task_fight_jina(isAddStrengh))
  271. elif isJina == 'yongbing':
  272. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  273. elif isJina == 'monster':
  274. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  275. elif isJina == 'big_monster':
  276. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  277. elif isJina == 'jina_call':
  278. ### 全部聊天记录都是新吉娜
  279. task_queue.appendleft(task_call_jina())
  280. task_queue.appendleft(task_call_jina())
  281. task_queue.appendleft(task_call_jina())
  282. task_queue.appendleft(task_call_jina())
  283. elif isJina == 'jina_onlyFight':
  284. task_queue.appendleft(task_fight_jina_only())
  285. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  286. task_queue.appendleft(task_train(train_type))
  287. if isSimple == False:
  288. task_queue.appendleft(task_checkActivities())
  289. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  290. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  291. if isJina == 'monster' and isAddStrengh:
  292. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  293. else:
  294. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  295. task_queue.appendleft(task_information())
  296. else:
  297. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  298. if g_times % 3 == 0:
  299. task_queue.appendleft(task_checkDonata())
  300. task_queue.appendleft(task_checkMaster())
  301. task_queue.appendleft(task_checkAdventure())
  302. task_queue.appendleft(task_train(train_type))
  303. task_queue.appendleft(task_useAnnimalSkill())
  304. #task_queue.appendleft(task_checkHelp(False))
  305. task_queue.appendleft(task_read_mails())
  306. if auto_participate:
  307. task_queue.appendleft(task_checkConfilits())
  308. task_queue.appendleft(task_checkDiamond())
  309. task_queue.appendleft(task_fight_campion())
  310. task_queue.appendleft(task_checkBenifitStatus())
  311. task_queue.appendleft(task_gotoTree())
  312. #task_queue.appendleft(task_get_redPackage())
  313. restart_times = 7
  314. if g_switch:
  315. restart_times = 4
  316. if g_times == restart_times:
  317. handle_end_game()
  318. if always:
  319. myTimeSleep(random.randint(350, 400), send_status)
  320. else:
  321. myTimeSleep(random.randint(1000, 2000), send_status)
  322. handle_restart_game()
  323. else:
  324. if isAddStrengh:
  325. myTimeSleep(random.randint(350, 400), send_status)
  326. else:
  327. myTimeSleep(random.randint(350, 400), send_status)
  328. task_queue.clear()
  329. send_status(f'自动模式结束')
  330. event.clear()
  331. daily_config = {
  332. "login_task": False,
  333. "fight_bigMonster_times": 0
  334. }
  335. def check_daily_config(config):
  336. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  337. print(f"Today: {today}") # 打印当前日期
  338. print(f"Config: {config}") # 打印传入的配置
  339. if "daily" not in config:
  340. print("Daily key not found, creating it.") # 调试信息
  341. config["daily"] = {}
  342. return False
  343. if today not in config["daily"]:
  344. print(f"Today's config not found: {today}") # 调试信息
  345. return False
  346. else:
  347. print(f"Today's config found: {today}") # 调试信息
  348. return True
  349. def update_rungame_type(config):
  350. runTypeStr = 'runType'
  351. if runTypeStr not in config:
  352. config[runTypeStr] = 1
  353. write_Dailycfg(config)
  354. print(f"更新下次启动{config[runTypeStr]}")
  355. return 0
  356. else:
  357. value = config[runTypeStr]
  358. config[runTypeStr] = (value + 1) % 2
  359. write_Dailycfg(config)
  360. print(f"更新下次启动{config[runTypeStr]}")
  361. return value
  362. # 修改或添加 "login_task" 的值
  363. def set_login_task(config, value):
  364. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  365. if today not in config["daily"]: # 如果当天的配置不存在
  366. config["daily"][today] = {} # 创建当天的配置
  367. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  368. return config
  369. # 修改或添加 "fight_bigMonster_times" 的值
  370. def set_fight_big_monster_times(config, value):
  371. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  372. if today not in config["daily"]: # 如果当天的配置不存在
  373. config["daily"][today] = {} # 创建当天的配置
  374. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  375. return config
  376. def add_today_daily_config(config, daily_config, overwrite=False):
  377. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  378. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  379. config["daily"][today] = daily_config # 添加或更新
  380. return config
  381. # 清理非当天的每日配置
  382. def clean_old_daily_configs(config):
  383. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  384. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  385. for key in keys_to_remove:
  386. del config["daily"][key] # 删除非当天的每日配置
  387. return config
  388. def write_cfg(config):
  389. with open('config.json', 'w') as config_file:
  390. json.dump(config, config_file, indent=4)
  391. def read_cfg():
  392. global g_cureNum
  393. try:
  394. with open('config.json', 'r') as config_file:
  395. config = json.load(config_file)
  396. g_cureNum = config['cureNumber']
  397. return config
  398. except FileNotFoundError:
  399. print("配置文件不存在,请检查文件路径。")
  400. return None
  401. except PermissionError:
  402. print("没有权限读取配置文件。")
  403. return None
  404. except json.JSONDecodeError:
  405. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  406. return None
  407. def write_Dailycfg(config):
  408. with open('daily.json', 'w') as config_file:
  409. json.dump(config, config_file, indent=4)
  410. def read_Dailycfg():
  411. try:
  412. with open('daily.json', 'r') as config_file:
  413. config = json.load(config_file)
  414. return config
  415. except FileNotFoundError:
  416. print("配置文件不存在,请检查文件路径。")
  417. return None
  418. except PermissionError:
  419. print("没有权限读取配置文件。")
  420. return None
  421. except json.JSONDecodeError:
  422. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  423. return None
  424. @socketio.on('begin_auto')
  425. def handle_auto(data):
  426. write_cfg(data)
  427. config = read_cfg()
  428. print("config", config)
  429. auto_task(config)
  430. def auto_task(data):
  431. global autoTask, g_cureNum
  432. if data == None:
  433. isMaxCollect = '4,3,2,1'
  434. isSimple = False
  435. isJina = 'jina'
  436. isAddStrengh = False
  437. activity = 'none'
  438. participateJijie = False
  439. auto_daily = False
  440. train_type = 'none'
  441. always = False
  442. cureNumber = 500
  443. lineCheck = False
  444. switch = False
  445. else:
  446. isMaxCollect = data['maxCollect']
  447. isSimple = data['simple']
  448. isJina = data['jina']
  449. isAddStrengh = data['add_strength']
  450. activity = data['activity']
  451. participateJijie = data['participate_jijie']
  452. auto_daily = data['auto_daily']
  453. train_type = data['train']
  454. always = data['always']
  455. cureNumber = data['cureNumber']
  456. lineCheck = data['lineCheck']
  457. switch = data['switch']
  458. g_cureNum = cureNumber
  459. g_switch = switch
  460. set_lineCheck(lineCheck)
  461. send_status(f'开始自动模式')
  462. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  463. @socketio.on('begin_auto_participate')
  464. def handle_auto_participate():
  465. global autoTask
  466. send_status(f'开始自动集结模式')
  467. executor.submit(auto_participate)
  468. @socketio.on('begin_auto_ranshuang')
  469. def handle_auto_ranshuang():
  470. global autoTask
  471. send_status(f'开始自动燃霜')
  472. executor.submit(auto_ranshuang)
  473. @socketio.on('auto_palace')
  474. def handle_auto_palace():
  475. global autoTask
  476. send_status(f'开始自动王城')
  477. executor.submit(auto_palace)
  478. if __name__ == '__main__':
  479. init()
  480. if '--reset' in sys.argv:
  481. isReset = True
  482. print("需要重启游戏")
  483. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  484. runTask.daemon = True
  485. runTask.start()
  486. socketio.run(app, host= '0.0.0.0', debug=True)