app_dongri.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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('close_game')
  132. def handle_close_game():
  133. task_close_game()
  134. send_status("结束2")
  135. event.clear()
  136. @socketio.on('read_cfg')
  137. def handle_read_cfg():
  138. cfg = read_cfg()
  139. emit('processing_cfg', cfg)
  140. def restart_game():
  141. global isGameBegin
  142. isGameBegin = False
  143. while True:
  144. task_close_game()
  145. if True == task_start_game():
  146. break
  147. else:
  148. send_status("启动失败")
  149. isGameBegin = True
  150. send_status("结束")
  151. config = read_cfg()
  152. print("config", config)
  153. auto_task(config)
  154. def auto_participate():
  155. task_queue.appendleft(task_returnAllLine())
  156. timeout = 40 * 60
  157. start_time = time.time() # 记录开始时间
  158. while not event.is_set():
  159. if len(task_queue) < 4:
  160. task_queue.appendleft(task_paticipateInTeam())
  161. task_queue.appendleft(task_paticipateInTeam())
  162. task_queue.appendleft(task_paticipateInTeam())
  163. task_queue.appendleft(task_checkHelp(True))
  164. myTimeSleep_big()
  165. # 每次循环检查已用时间
  166. current_time = time.time()
  167. elapsed_time = current_time - start_time
  168. if elapsed_time >= timeout:
  169. handle_restart_game()
  170. break
  171. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True):
  172. collectArr = [int(x) for x in isMaxCollect.split(",")]
  173. print("collectArr", collectArr)
  174. times = 0
  175. while not event.is_set():
  176. isLoginTask = True
  177. fight_big_monster_times = 0
  178. config = read_cfg()
  179. if check_daily_config(config):
  180. today = datetime.now().strftime('%Y-%m-%d')
  181. isLoginTask = config['daily'][today]["login_task"]
  182. fight_big_monster_times = int(config['daily'][today]["fight_big_monster_times"])
  183. else:
  184. set_login_task(config, False)
  185. set_fight_big_monster_times(config, 0)
  186. clean_old_daily_configs(config)
  187. isLoginTask = False
  188. fight_big_monster_times = 0
  189. write_cfg(config)
  190. print("isLoginTask", isLoginTask, "fight_big_monster_times", fight_big_monster_times)
  191. if not isLoginTask:
  192. task_queue.appendleft(task_checkMaster())
  193. set_login_task(config, True)
  194. write_cfg(config)
  195. task_queue.appendleft(task_information())
  196. if activity == 'lianmeng':
  197. task_queue.appendleft(task_activity_lianmeng())
  198. #if not isSimple:
  199. # task_queue.appendleft(task_paticipateInTeam())
  200. task_queue.appendleft(check_buildOrResearch())
  201. if not isSimple:
  202. if isJina == 'jina':
  203. task_queue.appendleft(task_fight_jina(isAddStrengh))
  204. elif isJina == 'yongbing':
  205. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  206. elif isJina == 'monster':
  207. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  208. elif isJina == 'big_monster':
  209. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  210. task_queue.appendleft(task_cure())
  211. task_queue.appendleft(task_checkStoreRoom())
  212. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  213. task_queue.appendleft(task_train(False))
  214. task_queue.appendleft(task_checkDonata())
  215. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  216. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  217. task_queue.appendleft(task_cure())
  218. if isSimple:
  219. task_queue.appendleft(check_buildOrResearch())
  220. else:
  221. if isJina == 'monster':
  222. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  223. else:
  224. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  225. #task_queue.appendleft(task_waitTime())
  226. times += 1
  227. if times % 3 == 0:
  228. task_queue.appendleft(task_checkAdventure())
  229. task_queue.appendleft(task_train(False))
  230. task_queue.appendleft(task_useAnnimalSkill())
  231. task_queue.appendleft(task_checkHelp(False))
  232. if auto_participate:
  233. task_queue.appendleft(task_checkConfilits())
  234. if times == 10:
  235. handle_end_game()
  236. if isAddStrengh:
  237. myTimeSleep(random.randint(400, 500), send_status)
  238. else:
  239. myTimeSleep(random.randint(1000, 2000), send_status)
  240. handle_restart_game()
  241. else:
  242. if isAddStrengh:
  243. myTimeSleep(random.randint(400, 500), send_status)
  244. else:
  245. myTimeSleep(random.randint(600, 1000), send_status)
  246. task_queue.clear()
  247. send_status(f'自动模式结束')
  248. event.clear()
  249. daily_config = {
  250. "login_task": False,
  251. "fight_bigMonster_times": 0
  252. }
  253. def check_daily_config(config):
  254. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  255. if "daily" not in config:
  256. config["daily"] = {}
  257. return False
  258. if today not in config["daily"]:
  259. return False
  260. else:
  261. return True
  262. # 修改或添加 "login_task" 的值
  263. def set_login_task(config, value):
  264. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  265. if today not in config["daily"]: # 如果当天的配置不存在
  266. config["daily"][today] = {} # 创建当天的配置
  267. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  268. return config
  269. # 修改或添加 "fight_bigMonster_times" 的值
  270. def set_fight_big_monster_times(config, value):
  271. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  272. if today not in config["daily"]: # 如果当天的配置不存在
  273. config["daily"][today] = {} # 创建当天的配置
  274. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  275. return config
  276. def add_today_daily_config(config, daily_config, overwrite=False):
  277. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  278. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  279. config["daily"][today] = daily_config # 添加或更新
  280. return config
  281. # 清理非当天的每日配置
  282. def clean_old_daily_configs(config):
  283. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  284. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  285. for key in keys_to_remove:
  286. del config["daily"][key] # 删除非当天的每日配置
  287. return config
  288. def write_cfg(config):
  289. with open('config.json', 'w') as config_file:
  290. json.dump(config, config_file, indent=4)
  291. def read_cfg():
  292. try:
  293. with open('config.json', 'r') as config_file:
  294. config = json.load(config_file)
  295. return config
  296. except FileNotFoundError:
  297. print("配置文件不存在,请检查文件路径。")
  298. return None
  299. except PermissionError:
  300. print("没有权限读取配置文件。")
  301. return None
  302. except json.JSONDecodeError:
  303. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  304. return None
  305. @socketio.on('begin_auto')
  306. def handle_auto(data):
  307. write_cfg(data)
  308. config = read_cfg()
  309. print("config", config)
  310. auto_task(config)
  311. def auto_task(data):
  312. global autoTask
  313. if data == None:
  314. isMaxCollect = '4,3,2,1'
  315. isSimple = False
  316. isJina = 'jina'
  317. isAddStrengh = False
  318. activity = 'none'
  319. participateJijie = False
  320. else:
  321. isMaxCollect = data['maxCollect']
  322. isSimple = data['simple']
  323. isJina = data['jina']
  324. isAddStrengh = data['add_strength']
  325. activity = data['activity']
  326. participateJijie = data['participate_jijie']
  327. send_status(f'开始自动模式')
  328. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie)
  329. @socketio.on('begin_auto_participate')
  330. def handle_auto_participate():
  331. global autoTask
  332. send_status(f'开始自动集结模式')
  333. executor.submit(auto_participate)
  334. if __name__ == '__main__':
  335. init()
  336. if '--reset' in sys.argv:
  337. isReset = True
  338. print("需要重启游戏")
  339. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  340. runTask.daemon = True
  341. runTask.start()
  342. socketio.run(app, host= '0.0.0.0', debug=True)