app_dongri.py 18 KB

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