app_dongri.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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_fight_enemy())
  202. myTimeSleep_big()
  203. current_time = time.time()
  204. elapsed_time = current_time - start_time
  205. if elapsed_time >= timeout:
  206. handle_restart_game()
  207. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True, isDailyConfig = False, train_type = 'None', always = False):
  208. global g_times, g_cureNum
  209. collectArr = [int(x) for x in isMaxCollect.split(",")]
  210. print("collectArr", collectArr)
  211. while not event.is_set():
  212. isLoginTask = True
  213. fight_big_monster_times = 0
  214. config = read_Dailycfg()
  215. print("config", config)
  216. if check_daily_config(config):
  217. today = datetime.now().strftime('%Y-%m-%d')
  218. isLoginTask = bool(config['daily'][today]["login_task"])
  219. fight_big_monster_times = int(config['daily'][today]["fight_bigMonster_times"])
  220. else:
  221. set_login_task(config, False)
  222. set_fight_big_monster_times(config, 0)
  223. clean_old_daily_configs(config)
  224. isLoginTask = False
  225. fight_big_monster_times = 0
  226. write_Dailycfg(config)
  227. send_status(f"isLoginTask:{isLoginTask}, fight_big_monster_times:{fight_big_monster_times}")
  228. if not isLoginTask:
  229. task_queue.appendleft(task_checkMaster())
  230. set_login_task(config, True)
  231. write_Dailycfg(config)
  232. if isDailyConfig and fight_big_monster_times < 10:
  233. isSuccess = task_fightMonster(isAddStrengh, True, isSimple)
  234. if isSuccess:
  235. set_fight_big_monster_times(config, fight_big_monster_times + 1)
  236. write_Dailycfg(config)
  237. if activity == 'lianmeng':
  238. task_queue.appendleft(task_activity_lianmeng())
  239. elif activity == 'cure':
  240. task_queue.appendleft(task_cure(True, g_cureNum))
  241. elif activity == 'only_cure':
  242. task_queue.appendleft(task_cure(True, g_cureNum))
  243. task_queue.appendleft(task_cure(True, g_cureNum))
  244. task_queue.appendleft(task_cure(True, g_cureNum))
  245. return
  246. task_queue.appendleft(task_information())
  247. task_queue.appendleft(check_buildOrResearch())
  248. task_queue.appendleft(task_cure(False, g_cureNum))
  249. task_queue.appendleft(task_checkStoreRoom())
  250. if not isSimple:
  251. if isJina == 'jina':
  252. task_queue.appendleft(task_fight_jina(isAddStrengh))
  253. elif isJina == 'yongbing':
  254. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  255. elif isJina == 'monster':
  256. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  257. elif isJina == 'big_monster':
  258. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  259. elif isJina == 'jina_call':
  260. ### 全部聊天记录都是新吉娜
  261. task_queue.appendleft(task_call_jina())
  262. task_queue.appendleft(task_call_jina())
  263. task_queue.appendleft(task_call_jina())
  264. task_queue.appendleft(task_call_jina())
  265. elif isJina == 'jina_onlyFight':
  266. task_queue.appendleft(task_fight_jina_only())
  267. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  268. task_queue.appendleft(task_train(train_type))
  269. task_queue.appendleft(task_checkActivities())
  270. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  271. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  272. task_queue.appendleft(task_cure(False, g_cureNum))
  273. if isSimple:
  274. task_queue.appendleft(check_buildOrResearch())
  275. else:
  276. if isJina == 'monster' and isAddStrengh:
  277. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  278. else:
  279. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  280. g_times += 1
  281. if g_times % 3 == 0:
  282. task_queue.appendleft(task_checkDonata())
  283. task_queue.appendleft(task_checkAdventure())
  284. task_queue.appendleft(task_train(train_type))
  285. task_queue.appendleft(task_useAnnimalSkill())
  286. task_queue.appendleft(task_checkHelp(False))
  287. if auto_participate:
  288. task_queue.appendleft(task_checkConfilits())
  289. task_queue.appendleft(task_gotoTree())
  290. if always == False and g_times == 7:
  291. handle_end_game()
  292. if isAddStrengh:
  293. myTimeSleep(random.randint(350, 400), send_status)
  294. else:
  295. myTimeSleep(random.randint(1000, 2000), send_status)
  296. handle_restart_game()
  297. else:
  298. if isAddStrengh:
  299. myTimeSleep(random.randint(300, 350), send_status)
  300. else:
  301. myTimeSleep(random.randint(400, 500), send_status)
  302. task_queue.clear()
  303. send_status(f'自动模式结束')
  304. event.clear()
  305. daily_config = {
  306. "login_task": False,
  307. "fight_bigMonster_times": 0
  308. }
  309. def check_daily_config(config):
  310. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  311. print(f"Today: {today}") # 打印当前日期
  312. print(f"Config: {config}") # 打印传入的配置
  313. if "daily" not in config:
  314. print("Daily key not found, creating it.") # 调试信息
  315. config["daily"] = {}
  316. return False
  317. if today not in config["daily"]:
  318. print(f"Today's config not found: {today}") # 调试信息
  319. return False
  320. else:
  321. print(f"Today's config found: {today}") # 调试信息
  322. return True
  323. # 修改或添加 "login_task" 的值
  324. def set_login_task(config, value):
  325. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  326. if today not in config["daily"]: # 如果当天的配置不存在
  327. config["daily"][today] = {} # 创建当天的配置
  328. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  329. return config
  330. # 修改或添加 "fight_bigMonster_times" 的值
  331. def set_fight_big_monster_times(config, value):
  332. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  333. if today not in config["daily"]: # 如果当天的配置不存在
  334. config["daily"][today] = {} # 创建当天的配置
  335. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  336. return config
  337. def add_today_daily_config(config, daily_config, overwrite=False):
  338. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  339. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  340. config["daily"][today] = daily_config # 添加或更新
  341. return config
  342. # 清理非当天的每日配置
  343. def clean_old_daily_configs(config):
  344. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  345. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  346. for key in keys_to_remove:
  347. del config["daily"][key] # 删除非当天的每日配置
  348. return config
  349. def write_cfg(config):
  350. with open('config.json', 'w') as config_file:
  351. json.dump(config, config_file, indent=4)
  352. def read_cfg():
  353. global g_cureNum
  354. try:
  355. with open('config.json', 'r') as config_file:
  356. config = json.load(config_file)
  357. g_cureNum = config['cureNumber']
  358. return config
  359. except FileNotFoundError:
  360. print("配置文件不存在,请检查文件路径。")
  361. return None
  362. except PermissionError:
  363. print("没有权限读取配置文件。")
  364. return None
  365. except json.JSONDecodeError:
  366. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  367. return None
  368. def write_Dailycfg(config):
  369. with open('daily.json', 'w') as config_file:
  370. json.dump(config, config_file, indent=4)
  371. def read_Dailycfg():
  372. try:
  373. with open('daily.json', 'r') as config_file:
  374. config = json.load(config_file)
  375. return config
  376. except FileNotFoundError:
  377. print("配置文件不存在,请检查文件路径。")
  378. return None
  379. except PermissionError:
  380. print("没有权限读取配置文件。")
  381. return None
  382. except json.JSONDecodeError:
  383. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  384. return None
  385. @socketio.on('begin_auto')
  386. def handle_auto(data):
  387. write_cfg(data)
  388. config = read_cfg()
  389. print("config", config)
  390. auto_task(config)
  391. def auto_task(data):
  392. global autoTask, g_cureNum
  393. if data == None:
  394. isMaxCollect = '4,3,2,1'
  395. isSimple = False
  396. isJina = 'jina'
  397. isAddStrengh = False
  398. activity = 'none'
  399. participateJijie = False
  400. auto_daily = False
  401. train_type = 'none'
  402. always = False
  403. cureNumber = 500
  404. lineCheck = False
  405. else:
  406. isMaxCollect = data['maxCollect']
  407. isSimple = data['simple']
  408. isJina = data['jina']
  409. isAddStrengh = data['add_strength']
  410. activity = data['activity']
  411. participateJijie = data['participate_jijie']
  412. auto_daily = data['auto_daily']
  413. train_type = data['train']
  414. always = data['always']
  415. cureNumber = data['cureNumber']
  416. lineCheck = data['lineCheck']
  417. g_cureNum = cureNumber
  418. set_lineCheck(lineCheck)
  419. send_status(f'开始自动模式')
  420. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  421. @socketio.on('begin_auto_participate')
  422. def handle_auto_participate():
  423. global autoTask
  424. send_status(f'开始自动集结模式')
  425. executor.submit(auto_participate)
  426. @socketio.on('begin_auto_ranshuang')
  427. def handle_auto_ranshuang():
  428. global autoTask
  429. send_status(f'开始自动燃霜')
  430. executor.submit(auto_ranshuang)
  431. @socketio.on('auto_palace')
  432. def handle_auto_palace():
  433. global autoTask
  434. send_status(f'开始自动王城')
  435. executor.submit(auto_palace)
  436. if __name__ == '__main__':
  437. init()
  438. if '--reset' in sys.argv:
  439. isReset = True
  440. print("需要重启游戏")
  441. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  442. runTask.daemon = True
  443. runTask.start()
  444. socketio.run(app, host= '0.0.0.0', debug=True)