app_dongri.py 16 KB

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