app_dongri.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. @app.after_request
  26. def add_no_cache_header(response):
  27. # 添加禁用缓存的响应头
  28. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  29. response.headers["Pragma"] = "no-cache"
  30. response.headers["Expires"] = "0"
  31. return response
  32. def thread_runTask():
  33. global last_process
  34. global task_queue,isReset
  35. while True:
  36. if event.is_set():
  37. task_queue.clear()
  38. if len(task_queue) != 0:
  39. task = task_queue[-1]
  40. task_queue.pop()
  41. last_process = task.name
  42. task.run()
  43. myTimeSleep_small()
  44. else:
  45. myTimeSleep_big()
  46. if isReset:
  47. isReset = False
  48. restart_game()
  49. @app.route('/')
  50. def index():
  51. return render_template('index_dongri.html')
  52. @socketio.on('connect')
  53. def handle_connect():
  54. print('Client connected')
  55. @socketio.on('disconnect')
  56. def handle_disconnect():
  57. print('Client disconnected')
  58. def send_hint(msg):#数组信息
  59. emit('processing_hint', msg)
  60. def send_status(msg):#软件执行状态
  61. global g_status_list
  62. try:
  63. if not msg == "":
  64. # 添加新的状态消息和时间到列表
  65. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 获取当前时间
  66. status_entry = {'msg': msg, 'time': timestamp} # 存储消息和时间
  67. g_status_list.append(status_entry)
  68. # 如果列表超过 5 条,移除最早的一条
  69. if len(g_status_list) > 5:
  70. g_status_list.pop(0)
  71. else:
  72. sendStr = ''
  73. for item in g_status_list:
  74. sendStr = sendStr + f"{item['time']}-{item['msg']}<br>"
  75. #print(sendStr)
  76. emit('processing_status', sendStr)
  77. # 如果消息是 "结束",发送所有状态并清空列表
  78. if msg == "结束":
  79. g_status_list = [] # 清空列表
  80. event.clear()
  81. except Exception as e:
  82. print(f"Error in send_status: {e}")
  83. return
  84. @socketio.on('monitor_begin')
  85. def monitor_begin():
  86. global last_time, last_process
  87. current_time = time.time()
  88. elapsed_time = current_time - last_time
  89. if elapsed_time < 0.5:
  90. return
  91. last_time = current_time
  92. regionRet, regionPos = game_region()
  93. screenshot = pyautogui.screenshot(region=regionPos)
  94. #binary_img = binarize_image(screenshot)
  95. compressed_data = compress_image(screenshot)
  96. image_data_base64 = base64.b64encode(compressed_data).decode('utf-8')
  97. socketio.emit('image_data', image_data_base64)
  98. task_arr = []
  99. if not event.is_set():
  100. task_arr.append(last_process)
  101. for item in reversed(task_queue):
  102. task_arr.append(item.name)
  103. send_hint(json.dumps(task_arr, ensure_ascii=False))
  104. send_status('')
  105. #print("send img")
  106. @socketio.on('end_script')
  107. def handle_end_script():
  108. event.set()
  109. @socketio.on('end_game')
  110. def handle_end_game():
  111. event.set()
  112. task_close_game()
  113. send_status("结束2")
  114. event.clear()
  115. @socketio.on('get_title')
  116. def handle_get_title():
  117. str = task_getComputerName()
  118. dst = str + ' machine'
  119. emit('processing_title', dst)
  120. @socketio.on('reset_script')
  121. def handle_reset_script():
  122. python = sys.executable
  123. while '--reset' in sys.argv:
  124. # 从 sys.argv 列表中删除 --reset 参数
  125. sys.argv.remove('--reset')
  126. os.execl(python, python, *sys.argv)
  127. @socketio.on('restart_game')
  128. def handle_restart_game():
  129. python = sys.executable
  130. os.execl(python, python, *sys.argv, '--reset')
  131. @socketio.on('read_cfg')
  132. def handle_read_cfg():
  133. cfg = read_cfg()
  134. emit('processing_cfg', cfg)
  135. def restart_game():
  136. global isGameBegin
  137. isGameBegin = False
  138. while True:
  139. task_close_game()
  140. if True == task_start_game():
  141. break
  142. else:
  143. send_status("启动失败")
  144. isGameBegin = True
  145. send_status("结束")
  146. config = read_cfg()
  147. print("config", config)
  148. auto_task(config)
  149. def auto_participate():
  150. task_queue.appendleft(task_returnAllLine())
  151. timeout = 40 * 60
  152. start_time = time.time() # 记录开始时间
  153. while not event.is_set():
  154. if len(task_queue) < 4:
  155. task_queue.appendleft(task_paticipateInTeam())
  156. task_queue.appendleft(task_paticipateInTeam())
  157. task_queue.appendleft(task_paticipateInTeam())
  158. task_queue.appendleft(task_checkHelp(True))
  159. myTimeSleep_big()
  160. # 每次循环检查已用时间
  161. current_time = time.time()
  162. elapsed_time = current_time - start_time
  163. if elapsed_time >= timeout:
  164. handle_restart_game()
  165. break
  166. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True):
  167. collectArr = [int(x) for x in isMaxCollect.split(",")]
  168. print("collectArr", collectArr)
  169. times = 0
  170. while not event.is_set():
  171. task_queue.appendleft(task_information())
  172. if activity == 'lianmeng':
  173. task_queue.appendleft(task_activity_lianmeng())
  174. #if not isSimple:
  175. # task_queue.appendleft(task_paticipateInTeam())
  176. task_queue.appendleft(check_buildOrResearch())
  177. if not isSimple:
  178. if isJina == 'jina':
  179. task_queue.appendleft(task_fight_jina(isAddStrengh))
  180. elif isJina == 'yongbing':
  181. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  182. elif isJina == 'monster':
  183. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  184. elif isJina == 'big_monster':
  185. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  186. task_queue.appendleft(task_cure())
  187. task_queue.appendleft(task_checkStoreRoom())
  188. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  189. task_queue.appendleft(task_train(False))
  190. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  191. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  192. task_queue.appendleft(task_cure())
  193. if isSimple:
  194. task_queue.appendleft(check_buildOrResearch())
  195. else:
  196. if isJina == 'monster':
  197. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  198. else:
  199. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  200. #task_queue.appendleft(task_waitTime())
  201. times += 1
  202. if times % 3 == 0:
  203. task_queue.appendleft(task_checkAdventure())
  204. task_queue.appendleft(task_train(False))
  205. task_queue.appendleft(task_checkDonata())
  206. task_queue.appendleft(task_useAnnimalSkill())
  207. task_queue.appendleft(task_checkHelp(False))
  208. if auto_participate:
  209. task_queue.appendleft(task_checkConfilits())
  210. if times == 10:
  211. handle_end_game()
  212. if isAddStrengh:
  213. myTimeSleep(random.randint(400, 500), send_status)
  214. else:
  215. myTimeSleep(random.randint(1000, 2000), send_status)
  216. handle_restart_game()
  217. else:
  218. if isAddStrengh:
  219. myTimeSleep(random.randint(400, 500), send_status)
  220. else:
  221. myTimeSleep(random.randint(600, 1000), send_status)
  222. task_queue.clear()
  223. send_status(f'自动模式结束')
  224. event.clear()
  225. def write_cfg(config):
  226. with open('config.json', 'w') as config_file:
  227. json.dump(config, config_file, indent=4)
  228. def read_cfg():
  229. try:
  230. with open('config.json', 'r') as config_file:
  231. config = json.load(config_file)
  232. return config
  233. except FileNotFoundError:
  234. print("配置文件不存在,请检查文件路径。")
  235. return None
  236. except PermissionError:
  237. print("没有权限读取配置文件。")
  238. return None
  239. except json.JSONDecodeError:
  240. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  241. return None
  242. @socketio.on('begin_auto')
  243. def handle_auto(data):
  244. write_cfg(data)
  245. config = read_cfg()
  246. print("config", config)
  247. auto_task(config)
  248. def auto_task(data):
  249. global autoTask
  250. if data == None:
  251. isMaxCollect = '4,3,2,1'
  252. isSimple = False
  253. isJina = 'jina'
  254. isAddStrengh = False
  255. activity = 'none'
  256. participateJijie = False
  257. else:
  258. isMaxCollect = data['maxCollect']
  259. isSimple = data['simple']
  260. isJina = data['jina']
  261. isAddStrengh = data['add_strength']
  262. activity = data['activity']
  263. participateJijie = data['participate_jijie']
  264. send_status(f'开始自动模式')
  265. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie)
  266. @socketio.on('begin_auto_participate')
  267. def handle_auto_participate():
  268. global autoTask
  269. send_status(f'开始自动集结模式')
  270. executor.submit(auto_participate)
  271. if __name__ == '__main__':
  272. init()
  273. if '--reset' in sys.argv:
  274. isReset = True
  275. print("需要重启游戏")
  276. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  277. runTask.daemon = True
  278. runTask.start()
  279. socketio.run(app, host= '0.0.0.0', debug=True)