app_dongri.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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, isDailyConfig = False):
  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_Dailycfg()
  179. print("config", config)
  180. if check_daily_config(config):
  181. today = datetime.now().strftime('%Y-%m-%d')
  182. print("today", today)
  183. isLoginTask = bool(config['daily'][today]["login_task"])
  184. fight_big_monster_times = int(config['daily'][today]["fight_bigMonster_times"])
  185. else:
  186. set_login_task(config, False)
  187. set_fight_big_monster_times(config, 0)
  188. clean_old_daily_configs(config)
  189. isLoginTask = False
  190. fight_big_monster_times = 0
  191. write_Dailycfg(config)
  192. print("111")
  193. send_status(f"isLoginTask:{isLoginTask}, fight_big_monster_times:{fight_big_monster_times}")
  194. print("222")
  195. if not isLoginTask:
  196. task_queue.appendleft(task_checkMaster())
  197. set_login_task(config, True)
  198. write_Dailycfg(config)
  199. print("333")
  200. if isDailyConfig and fight_big_monster_times < 10:
  201. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  202. set_fight_big_monster_times(config, fight_big_monster_times + 1)
  203. write_Dailycfg(config)
  204. task_queue.appendleft(task_information())
  205. if activity == 'lianmeng':
  206. task_queue.appendleft(task_activity_lianmeng())
  207. task_queue.appendleft(check_buildOrResearch())
  208. if not isSimple:
  209. if isJina == 'jina':
  210. task_queue.appendleft(task_fight_jina(isAddStrengh))
  211. elif isJina == 'yongbing':
  212. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  213. elif isJina == 'monster':
  214. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  215. elif isJina == 'big_monster':
  216. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  217. task_queue.appendleft(task_cure())
  218. task_queue.appendleft(task_checkStoreRoom())
  219. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  220. task_queue.appendleft(task_train(False))
  221. task_queue.appendleft(task_checkDonata())
  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':
  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_checkAdventure())
  236. task_queue.appendleft(task_train(False))
  237. task_queue.appendleft(task_useAnnimalSkill())
  238. task_queue.appendleft(task_checkHelp(False))
  239. if auto_participate:
  240. task_queue.appendleft(task_checkConfilits())
  241. if times == 10:
  242. handle_end_game()
  243. if isAddStrengh:
  244. myTimeSleep(random.randint(400, 500), send_status)
  245. else:
  246. myTimeSleep(random.randint(1000, 2000), send_status)
  247. handle_restart_game()
  248. else:
  249. if isAddStrengh:
  250. myTimeSleep(random.randint(400, 500), send_status)
  251. else:
  252. myTimeSleep(random.randint(600, 1000), send_status)
  253. task_queue.clear()
  254. send_status(f'自动模式结束')
  255. event.clear()
  256. daily_config = {
  257. "login_task": False,
  258. "fight_bigMonster_times": 0
  259. }
  260. def check_daily_config(config):
  261. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  262. print(f"Today: {today}") # 打印当前日期
  263. print(f"Config: {config}") # 打印传入的配置
  264. if "daily" not in config:
  265. print("Daily key not found, creating it.") # 调试信息
  266. config["daily"] = {}
  267. return False
  268. if today not in config["daily"]:
  269. print(f"Today's config not found: {today}") # 调试信息
  270. return False
  271. else:
  272. print(f"Today's config found: {today}") # 调试信息
  273. return True
  274. # 修改或添加 "login_task" 的值
  275. def set_login_task(config, value):
  276. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  277. if today not in config["daily"]: # 如果当天的配置不存在
  278. config["daily"][today] = {} # 创建当天的配置
  279. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  280. return config
  281. # 修改或添加 "fight_bigMonster_times" 的值
  282. def set_fight_big_monster_times(config, value):
  283. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  284. if today not in config["daily"]: # 如果当天的配置不存在
  285. config["daily"][today] = {} # 创建当天的配置
  286. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  287. return config
  288. def add_today_daily_config(config, daily_config, overwrite=False):
  289. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  290. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  291. config["daily"][today] = daily_config # 添加或更新
  292. return config
  293. # 清理非当天的每日配置
  294. def clean_old_daily_configs(config):
  295. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  296. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  297. for key in keys_to_remove:
  298. del config["daily"][key] # 删除非当天的每日配置
  299. return config
  300. def write_cfg(config):
  301. with open('config.json', 'w') as config_file:
  302. json.dump(config, config_file, indent=4)
  303. def read_cfg():
  304. try:
  305. with open('config.json', 'r') as config_file:
  306. config = json.load(config_file)
  307. return config
  308. except FileNotFoundError:
  309. print("配置文件不存在,请检查文件路径。")
  310. return None
  311. except PermissionError:
  312. print("没有权限读取配置文件。")
  313. return None
  314. except json.JSONDecodeError:
  315. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  316. return None
  317. def write_Dailycfg(config):
  318. with open('daily.json', 'w') as config_file:
  319. json.dump(config, config_file, indent=4)
  320. def read_Dailycfg():
  321. try:
  322. with open('daily.json', 'r') as config_file:
  323. config = json.load(config_file)
  324. return config
  325. except FileNotFoundError:
  326. print("配置文件不存在,请检查文件路径。")
  327. return None
  328. except PermissionError:
  329. print("没有权限读取配置文件。")
  330. return None
  331. except json.JSONDecodeError:
  332. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  333. return None
  334. @socketio.on('begin_auto')
  335. def handle_auto(data):
  336. write_cfg(data)
  337. config = read_cfg()
  338. print("config", config)
  339. auto_task(config)
  340. def auto_task(data):
  341. global autoTask
  342. if data == None:
  343. isMaxCollect = '4,3,2,1'
  344. isSimple = False
  345. isJina = 'jina'
  346. isAddStrengh = False
  347. activity = 'none'
  348. participateJijie = False
  349. auto_daily = False
  350. else:
  351. isMaxCollect = data['maxCollect']
  352. isSimple = data['simple']
  353. isJina = data['jina']
  354. isAddStrengh = data['add_strength']
  355. activity = data['activity']
  356. participateJijie = data['participate_jijie']
  357. auto_daily = data['auto_daily']
  358. send_status(f'开始自动模式')
  359. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily)
  360. @socketio.on('begin_auto_participate')
  361. def handle_auto_participate():
  362. global autoTask
  363. send_status(f'开始自动集结模式')
  364. executor.submit(auto_participate)
  365. if __name__ == '__main__':
  366. init()
  367. if '--reset' in sys.argv:
  368. isReset = True
  369. print("需要重启游戏")
  370. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  371. runTask.daemon = True
  372. runTask.start()
  373. socketio.run(app, host= '0.0.0.0', debug=True)