app_dongri.py 14 KB

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