app_dongri.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. @app.after_request
  27. def add_no_cache_header(response):
  28. # 添加禁用缓存的响应头
  29. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  30. response.headers["Pragma"] = "no-cache"
  31. response.headers["Expires"] = "0"
  32. return response
  33. def thread_runTask():
  34. global last_process
  35. global task_queue,isReset
  36. while True:
  37. if event.is_set():
  38. task_queue.clear()
  39. if len(task_queue) != 0:
  40. task = task_queue[-1]
  41. task_queue.pop()
  42. last_process = task.name
  43. task.run()
  44. myTimeSleep_small()
  45. else:
  46. myTimeSleep_big()
  47. if isReset:
  48. isReset = False
  49. restart_game()
  50. @app.route('/')
  51. def index():
  52. return render_template('index_dongri.html')
  53. @socketio.on('connect')
  54. def handle_connect():
  55. print('Client connected')
  56. @socketio.on('disconnect')
  57. def handle_disconnect():
  58. print('Client disconnected')
  59. def send_hint(msg):#数组信息
  60. emit('processing_hint', msg)
  61. def send_todo():
  62. emit('processing_todo', get_todo_msg())
  63. def send_status(msg):#软件执行状态
  64. global g_status_list, g_times
  65. try:
  66. if not msg == "":
  67. # 添加新的状态消息和时间到列表
  68. timestamp = datetime.now().strftime('%H:%M:%S') # 获取当前时间
  69. status_entry = {'msg': msg, 'time': timestamp} # 存储消息和时间
  70. g_status_list.append(status_entry)
  71. # 如果列表超过 5 条,移除最早的一条
  72. if len(g_status_list) > 5:
  73. g_status_list.pop(0)
  74. else:
  75. sendStr = ''
  76. for item in g_status_list:
  77. sendStr = sendStr + f"{g_times}次-{item['time']}-{item['msg']}<br>"
  78. #print(sendStr)
  79. emit('processing_status', sendStr)
  80. # 如果消息是 "结束",发送所有状态并清空列表
  81. if msg == "结束":
  82. g_status_list = [] # 清空列表
  83. event.clear()
  84. except Exception as e:
  85. print(f"Error in send_status: {e}")
  86. return
  87. @socketio.on('monitor_begin')
  88. def monitor_begin():
  89. global last_time, last_process
  90. current_time = time.time()
  91. elapsed_time = current_time - last_time
  92. if elapsed_time < 0.5:
  93. return
  94. last_time = current_time
  95. regionRet, regionPos = game_region()
  96. screenshot = pyautogui.screenshot(region=regionPos)
  97. #binary_img = binarize_image(screenshot)
  98. compressed_data = compress_image(screenshot)
  99. image_data_base64 = base64.b64encode(compressed_data).decode('utf-8')
  100. socketio.emit('image_data', image_data_base64)
  101. task_arr = []
  102. if not event.is_set():
  103. task_arr.append(last_process)
  104. for item in reversed(task_queue):
  105. task_arr.append(item.name)
  106. send_hint(json.dumps(task_arr, ensure_ascii=False))
  107. send_todo()
  108. send_status('')
  109. #print("send img")
  110. @socketio.on('end_script')
  111. def handle_end_script():
  112. event.set()
  113. @socketio.on('end_game')
  114. def handle_end_game():
  115. event.set()
  116. task_close_game()
  117. send_status("结束2")
  118. event.clear()
  119. @socketio.on('get_title')
  120. def handle_get_title():
  121. str = task_getComputerName()
  122. dst = str + ' machine'
  123. emit('processing_title', dst)
  124. @socketio.on('reset_script')
  125. def handle_reset_script():
  126. python = sys.executable
  127. while '--reset' in sys.argv:
  128. # 从 sys.argv 列表中删除 --reset 参数
  129. sys.argv.remove('--reset')
  130. os.execl(python, python, *sys.argv)
  131. @socketio.on('restart_game')
  132. def handle_restart_game():
  133. python = sys.executable
  134. os.execl(python, python, *sys.argv, '--reset')
  135. @socketio.on('close_game')
  136. def handle_close_game():
  137. task_close_game()
  138. send_status("结束2")
  139. event.clear()
  140. @socketio.on('read_cfg')
  141. def handle_read_cfg():
  142. cfg = read_cfg()
  143. emit('processing_cfg', cfg)
  144. def restart_game():
  145. global isGameBegin
  146. isGameBegin = False
  147. while True:
  148. task_close_game()
  149. if True == task_start_game():
  150. break
  151. else:
  152. send_status("启动失败")
  153. isGameBegin = True
  154. send_status("结束")
  155. config = read_cfg()
  156. print("config", config)
  157. auto_task(config)
  158. def auto_participate():
  159. task_queue.appendleft(task_returnAllLine())
  160. timeout = 40 * 60
  161. start_time = time.time() # 记录开始时间
  162. while not event.is_set():
  163. if len(task_queue) < 4:
  164. task_queue.appendleft(task_paticipateInTeam())
  165. task_queue.appendleft(task_paticipateInTeam())
  166. task_queue.appendleft(task_paticipateInTeam())
  167. task_queue.appendleft(task_checkHelp(True))
  168. myTimeSleep_big()
  169. # 每次循环检查已用时间
  170. current_time = time.time()
  171. elapsed_time = current_time - start_time
  172. if elapsed_time >= timeout:
  173. handle_restart_game()
  174. break
  175. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True, isDailyConfig = False, train_type = 'None', always = False):
  176. global g_times
  177. collectArr = [int(x) for x in isMaxCollect.split(",")]
  178. print("collectArr", collectArr)
  179. while not event.is_set():
  180. isLoginTask = True
  181. fight_big_monster_times = 0
  182. config = read_Dailycfg()
  183. print("config", config)
  184. if check_daily_config(config):
  185. today = datetime.now().strftime('%Y-%m-%d')
  186. isLoginTask = bool(config['daily'][today]["login_task"])
  187. fight_big_monster_times = int(config['daily'][today]["fight_bigMonster_times"])
  188. else:
  189. set_login_task(config, False)
  190. set_fight_big_monster_times(config, 0)
  191. clean_old_daily_configs(config)
  192. isLoginTask = False
  193. fight_big_monster_times = 0
  194. write_Dailycfg(config)
  195. send_status(f"isLoginTask:{isLoginTask}, fight_big_monster_times:{fight_big_monster_times}")
  196. if not isLoginTask:
  197. task_queue.appendleft(task_checkMaster())
  198. set_login_task(config, True)
  199. write_Dailycfg(config)
  200. if isDailyConfig and fight_big_monster_times < 10:
  201. isSuccess = task_fightMonster(isAddStrengh, True, isSimple)
  202. if isSuccess:
  203. set_fight_big_monster_times(config, fight_big_monster_times + 1)
  204. write_Dailycfg(config)
  205. task_queue.appendleft(task_information())
  206. if activity == 'lianmeng':
  207. task_queue.appendleft(task_activity_lianmeng())
  208. if activity == 'cure':
  209. task_queue.appendleft(task_cure(True))
  210. task_queue.appendleft(check_buildOrResearch())
  211. if not isSimple:
  212. if isJina == 'jina':
  213. task_queue.appendleft(task_fight_jina(isAddStrengh))
  214. elif isJina == 'yongbing':
  215. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  216. elif isJina == 'monster':
  217. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  218. elif isJina == 'big_monster':
  219. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  220. task_queue.appendleft(task_cure(False))
  221. task_queue.appendleft(task_checkStoreRoom())
  222. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  223. task_queue.appendleft(task_train(train_type))
  224. task_queue.appendleft(task_checkActivities())
  225. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  226. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  227. task_queue.appendleft(task_cure(False))
  228. if isSimple:
  229. task_queue.appendleft(check_buildOrResearch())
  230. else:
  231. if isJina == 'monster' and isAddStrengh:
  232. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  233. else:
  234. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  235. #task_queue.appendleft(task_waitTime())
  236. g_times += 1
  237. if g_times % 3 == 0:
  238. task_queue.appendleft(task_checkDonata())
  239. task_queue.appendleft(task_checkAdventure())
  240. task_queue.appendleft(task_train(train_type))
  241. task_queue.appendleft(task_useAnnimalSkill())
  242. task_queue.appendleft(task_checkHelp(False))
  243. if auto_participate:
  244. task_queue.appendleft(task_checkConfilits())
  245. if always == False and g_times == 7:
  246. handle_end_game()
  247. if isAddStrengh:
  248. myTimeSleep(random.randint(350, 400), send_status)
  249. else:
  250. myTimeSleep(random.randint(1000, 2000), send_status)
  251. handle_restart_game()
  252. else:
  253. if isAddStrengh:
  254. myTimeSleep(random.randint(300, 350), send_status)
  255. else:
  256. myTimeSleep(random.randint(400, 500), send_status)
  257. task_queue.clear()
  258. send_status(f'自动模式结束')
  259. event.clear()
  260. daily_config = {
  261. "login_task": False,
  262. "fight_bigMonster_times": 0
  263. }
  264. def check_daily_config(config):
  265. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  266. print(f"Today: {today}") # 打印当前日期
  267. print(f"Config: {config}") # 打印传入的配置
  268. if "daily" not in config:
  269. print("Daily key not found, creating it.") # 调试信息
  270. config["daily"] = {}
  271. return False
  272. if today not in config["daily"]:
  273. print(f"Today's config not found: {today}") # 调试信息
  274. return False
  275. else:
  276. print(f"Today's config found: {today}") # 调试信息
  277. return True
  278. # 修改或添加 "login_task" 的值
  279. def set_login_task(config, value):
  280. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  281. if today not in config["daily"]: # 如果当天的配置不存在
  282. config["daily"][today] = {} # 创建当天的配置
  283. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  284. return config
  285. # 修改或添加 "fight_bigMonster_times" 的值
  286. def set_fight_big_monster_times(config, value):
  287. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  288. if today not in config["daily"]: # 如果当天的配置不存在
  289. config["daily"][today] = {} # 创建当天的配置
  290. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  291. return config
  292. def add_today_daily_config(config, daily_config, overwrite=False):
  293. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  294. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  295. config["daily"][today] = daily_config # 添加或更新
  296. return config
  297. # 清理非当天的每日配置
  298. def clean_old_daily_configs(config):
  299. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  300. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  301. for key in keys_to_remove:
  302. del config["daily"][key] # 删除非当天的每日配置
  303. return config
  304. def write_cfg(config):
  305. with open('config.json', 'w') as config_file:
  306. json.dump(config, config_file, indent=4)
  307. def read_cfg():
  308. try:
  309. with open('config.json', 'r') as config_file:
  310. config = json.load(config_file)
  311. return config
  312. except FileNotFoundError:
  313. print("配置文件不存在,请检查文件路径。")
  314. return None
  315. except PermissionError:
  316. print("没有权限读取配置文件。")
  317. return None
  318. except json.JSONDecodeError:
  319. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  320. return None
  321. def write_Dailycfg(config):
  322. with open('daily.json', 'w') as config_file:
  323. json.dump(config, config_file, indent=4)
  324. def read_Dailycfg():
  325. try:
  326. with open('daily.json', 'r') as config_file:
  327. config = json.load(config_file)
  328. return config
  329. except FileNotFoundError:
  330. print("配置文件不存在,请检查文件路径。")
  331. return None
  332. except PermissionError:
  333. print("没有权限读取配置文件。")
  334. return None
  335. except json.JSONDecodeError:
  336. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  337. return None
  338. @socketio.on('begin_auto')
  339. def handle_auto(data):
  340. write_cfg(data)
  341. config = read_cfg()
  342. print("config", config)
  343. auto_task(config)
  344. def auto_task(data):
  345. global autoTask
  346. if data == None:
  347. isMaxCollect = '4,3,2,1'
  348. isSimple = False
  349. isJina = 'jina'
  350. isAddStrengh = False
  351. activity = 'none'
  352. participateJijie = False
  353. auto_daily = False
  354. train_type = 'none'
  355. always = False
  356. else:
  357. isMaxCollect = data['maxCollect']
  358. isSimple = data['simple']
  359. isJina = data['jina']
  360. isAddStrengh = data['add_strength']
  361. activity = data['activity']
  362. participateJijie = data['participate_jijie']
  363. auto_daily = data['auto_daily']
  364. train_type = data['train']
  365. always = data['always']
  366. send_status(f'开始自动模式')
  367. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  368. @socketio.on('begin_auto_participate')
  369. def handle_auto_participate():
  370. global autoTask
  371. send_status(f'开始自动集结模式')
  372. executor.submit(auto_participate)
  373. if __name__ == '__main__':
  374. init()
  375. if '--reset' in sys.argv:
  376. isReset = True
  377. print("需要重启游戏")
  378. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  379. runTask.daemon = True
  380. runTask.start()
  381. socketio.run(app, host= '0.0.0.0', debug=True)