app_dongri.py 17 KB

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