app_dongri.py 17 KB

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