app_dongri.py 14 KB

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