app_dongri.py 14 KB

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