app_dongri.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. # -*- coding: utf-8 -*-
  2. from flask import Flask, render_template,jsonify
  3. from flask_socketio import SocketIO, emit
  4. from scriptBase.comon import *
  5. import pyautogui
  6. import base64
  7. import threading
  8. from dongri_task import *
  9. from collections import deque
  10. import json
  11. from concurrent.futures import ThreadPoolExecutor
  12. from flask_caching import Cache
  13. from scriptBase.minio_manage import *
  14. # 全局线程池,限制最大线程数为1
  15. executor = ThreadPoolExecutor(max_workers=1)
  16. cache = Cache(config={'CACHE_TYPE': 'null'}) # 使用 null 缓存类型
  17. app = Flask(__name__)
  18. cache.init_app(app)
  19. app.config['TEMPLATES_AUTO_RELOAD'] = True
  20. socketio = SocketIO(app, cors_allowed_origins="*", max_http_buffer_size=1e8)
  21. class GlobalState:
  22. event = threading.Event()
  23. g_status_list = []
  24. last_time = 0.0
  25. task_queue = deque()
  26. last_process = ''
  27. isGameBegin = True
  28. isReset = False
  29. g_times = 0
  30. g_cureNum = 500
  31. g_switch = False
  32. g_isRestart = True
  33. last_change_time = time.time()
  34. g_firstRunBear = True
  35. @app.after_request
  36. def add_no_cache_header(response):
  37. # 添加禁用缓存的响应头
  38. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  39. response.headers["Pragma"] = "no-cache"
  40. response.headers["Expires"] = "0"
  41. return response
  42. def thread_runTask():
  43. while True:
  44. if GlobalState.event.is_set():
  45. GlobalState.task_queue.clear()
  46. if len(GlobalState.task_queue) != 0:
  47. # 初始时间
  48. current_time = time.time()
  49. task = GlobalState.task_queue[-1]
  50. GlobalState.task_queue.pop()
  51. print(f"-----------{task.name} 开始执行-----------")
  52. GlobalState.last_process = task.name
  53. try:
  54. task.run()
  55. except Exception as e:
  56. print(f"-----------{task.name} 执行失败,错误原因:{e}-----------")
  57. cost_time = int(time.time() - current_time)
  58. send_status(f"{task.name} 执行完成,耗时{cost_time}秒")
  59. print(f"-----------{task.name} 执行完成,耗时{cost_time}秒-----------")
  60. myTimeSleep_small()
  61. else:
  62. myTimeSleep_big()
  63. if GlobalState.isReset:
  64. GlobalState.isReset = False
  65. cfg = read_cfg()
  66. if cfg['switch']:
  67. type = update_rungame_type()
  68. print(f'启动游戏{type}')
  69. restart_game(type)
  70. else:
  71. restart_game(0)
  72. @app.route('/')
  73. def index():
  74. return render_template('index_dongri.html')
  75. @socketio.on('connect')
  76. def handle_connect():
  77. print('Client connected')
  78. @socketio.on('disconnect')
  79. def handle_disconnect():
  80. print('Client disconnected')
  81. def send_hint(msg):#数组信息
  82. emit('processing_hint', msg)
  83. def send_todo():
  84. emit('processing_todo', get_todo_msgList())
  85. def send_status(msg):#软件执行状态
  86. try:
  87. if not msg == "":
  88. # 添加新的状态消息和时间到列表
  89. timestamp = datetime.now().strftime('%H:%M:%S') # 获取当前时间
  90. status_entry = {'msg': msg, 'time': timestamp} # 存储消息和时间
  91. GlobalState.g_status_list.append(status_entry)
  92. # 如果列表超过 5 条,移除最早的一条
  93. if len(GlobalState.g_status_list) > 5:
  94. GlobalState.g_status_list.pop(0)
  95. else:
  96. sendStr = ''
  97. for item in GlobalState.g_status_list:
  98. sendStr = f"{GlobalState.g_times}次-{item['time']}-{item['msg']}<br>" + sendStr
  99. emit('processing_status', sendStr)
  100. # 如果消息是 "结束",发送所有状态并清空列表
  101. if msg == "结束":
  102. GlobalState.g_status_list = [] # 清空列表
  103. GlobalState.event.clear()
  104. except Exception as e:
  105. print(f"Error in send_status: {e}")
  106. return
  107. @socketio.on('monitor_begin')
  108. def monitor_begin():
  109. current_time = time.time()
  110. elapsed_time = current_time - GlobalState.last_time
  111. if elapsed_time < 0.5:
  112. return
  113. GlobalState.last_time = current_time
  114. regionRet, regionPos = game_region()
  115. screenshot = pyautogui.screenshot(region=regionPos)
  116. compressed_data = compress_image(screenshot)
  117. image_data_base64 = base64.b64encode(compressed_data).decode('utf-8')
  118. socketio.emit('image_data', image_data_base64)
  119. task_arr = []
  120. if not GlobalState.event.is_set():
  121. task_arr.append(GlobalState.last_process)
  122. for item in reversed(GlobalState.task_queue):
  123. task_arr.append(item.name)
  124. latest_tasks = task_arr[:5] # only show the last 5 tasks
  125. send_hint(json.dumps(latest_tasks, ensure_ascii=False))
  126. send_todo()
  127. send_status('')
  128. #print("send img")
  129. @socketio.on('end_script')
  130. def handle_end_script():
  131. GlobalState.event.set()
  132. @socketio.on('end_game')
  133. def handle_end_game():
  134. GlobalState.event.set()
  135. task_close_game()
  136. send_status("结束2")
  137. GlobalState.event.clear()
  138. @socketio.on('get_title')
  139. def handle_get_title():
  140. str = task_getComputerName()
  141. dst = str + ' machine'
  142. emit('processing_title', dst)
  143. @socketio.on('reset_script')
  144. def handle_reset_script():
  145. python = sys.executable
  146. script = os.path.abspath(sys.argv[0]) # 获取当前脚本的绝对路径
  147. # 构建新的参数列表,移除旧的 --reset 并添加新的
  148. new_args = [arg for arg in sys.argv[1:] if arg != '--reset'] # 排除脚本名和旧的 --reset
  149. print(f"当前 Python 解释器: {python}")
  150. print(f"当前脚本路径: {script}")
  151. print(f"重置参数: {[python, script, *new_args, '']}")
  152. try:
  153. os.execv(python, [python, script, *new_args, ''])
  154. except Exception as e:
  155. print(f"重置失败: {e}")
  156. subprocess.Popen([python, script, *new_args, ''])
  157. sys.exit(0) # 终止当前进程
  158. @socketio.on('restart_game')
  159. def handle_restart_game():
  160. python = sys.executable
  161. script = os.path.abspath(sys.argv[0]) # 获取当前脚本的绝对路径
  162. # 构建新的参数列表,移除旧的 --reset 并添加新的
  163. new_args = [arg for arg in sys.argv[1:] if arg != '--reset'] # 排除脚本名和旧的 --reset
  164. print(f"当前 Python 解释器: {python}")
  165. print(f"当前脚本路径: {script}")
  166. print(f"重启参数: {[python, script, *new_args, '--reset']}")
  167. try:
  168. os.execv(python, [python, script, *new_args, '--reset'])
  169. except Exception as e:
  170. print(f"重启失败: {e}")
  171. subprocess.Popen([python, script, *new_args, '--reset'])
  172. sys.exit(0) # 终止当前进程
  173. @app.route('/restart_game', methods=['POST'])
  174. def http_restart_game():
  175. print("HTTP 触发 restart_game")
  176. socketio.start_background_task(handle_restart_game)
  177. return jsonify({"status": "success", "message": "已重启"})
  178. @socketio.on('close_game')
  179. def handle_close_game():
  180. task_close_game()
  181. send_status("结束2")
  182. GlobalState.event.clear()
  183. @app.route('/close_game', methods=['POST'])
  184. def http_close_game():
  185. print("HTTP 触发 close_game")
  186. handle_close_game()
  187. socketio.start_background_task(handle_reset_script)
  188. return jsonify({"status": "success", "message": "已关闭"})
  189. @socketio.on('read_cfg')
  190. def handle_read_cfg():
  191. cfg = read_cfg()
  192. emit('processing_cfg', cfg)
  193. def restart_game(type=0):
  194. GlobalState.isGameBegin = False
  195. while True:
  196. task_close_game()
  197. if True == task_start_game(type):
  198. break
  199. else:
  200. send_status("启动失败")
  201. GlobalState.isGameBegin = True
  202. send_status("结束")
  203. config = read_cfg()
  204. print("config", config)
  205. auto_task(config)
  206. def auto_participate():
  207. GlobalState.task_queue.appendleft(task_returnAllLine())
  208. timeout = 40 * 60
  209. start_time = time.time() # 记录开始时间
  210. while not GlobalState.event.is_set():
  211. if len(GlobalState.task_queue) < 4:
  212. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  213. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  214. GlobalState.task_queue.appendleft(task_paticipateInTeam())
  215. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  216. GlobalState.task_queue.appendleft(task_paticipateInTeam())
  217. myTimeSleep_big()
  218. # 每次循环检查已用时间
  219. current_time = time.time()
  220. elapsed_time = current_time - start_time
  221. if elapsed_time >= timeout:
  222. handle_restart_game()
  223. break
  224. def auto_palace():
  225. timeout = 180 * 60
  226. start_time = time.time() # 记录开始时间
  227. read_cfg()
  228. while not GlobalState.event.is_set():
  229. GlobalState.g_times += 1
  230. if len(GlobalState.task_queue) < 4:
  231. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum * 5))
  232. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum * 3))
  233. GlobalState.task_queue.appendleft(task_fight_enemy())
  234. myTimeSleep_big()
  235. current_time = time.time()
  236. elapsed_time = current_time - start_time
  237. if elapsed_time >= timeout:
  238. handle_restart_game()
  239. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True, isDailyConfig = False, train_type = 'None', always = False):
  240. collectArr = [int(x) for x in isMaxCollect.split(",")]
  241. print("collectArr", collectArr)
  242. if len(collectArr) == 1:
  243. collectArr = collectArr[0]
  244. while not GlobalState.event.is_set():
  245. if isSimple == False and is_within_n_minutes(get_todo_time("巨熊行动"), 30, 35):
  246. print("in fight bear")
  247. if len(GlobalState.task_queue) < 5:
  248. if GlobalState.g_firstRunBear:
  249. GlobalState.g_firstRunBear = False
  250. start_recording()
  251. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  252. GlobalState.task_queue.appendleft(task_returnAllLine())
  253. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  254. GlobalState.task_queue.appendleft(task_returnAllLine())
  255. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  256. GlobalState.task_queue.appendleft(task_returnAllLine())
  257. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  258. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  259. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  260. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  261. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  262. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  263. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  264. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  265. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  266. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  267. myTimeSleep_big()
  268. send_status(f'巨熊行动中')
  269. continue
  270. elif isSimple == False and is_within_n_minutes(get_todo_time("巨熊行动"), 60, 0):
  271. # 设置无尽运行和启动的游戏为0
  272. always = True
  273. if GlobalState.g_switch:
  274. update_rungame_type(0)
  275. send_status(f'巨熊行动:在60min内,切换到无尽模式')
  276. stop_recording()
  277. print("add special activity")
  278. # special activity
  279. if activity == 'lianmeng':
  280. GlobalState.task_queue.appendleft(task_activity_lianmeng())
  281. elif activity == 'cure':
  282. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  283. elif activity == 'only_cure':
  284. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  285. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  286. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  287. return
  288. print("add normal activity")
  289. GlobalState.task_queue.appendleft(task_checkActivities())
  290. if GlobalState.g_switch == True:
  291. GlobalState.task_queue.appendleft(task_checkBenifitStatus())
  292. if isSimple == False:
  293. GlobalState.task_queue.appendleft(task_information())
  294. GlobalState.task_queue.appendleft(task_check_Research())
  295. GlobalState.task_queue.appendleft(task_checkStoreRoom())
  296. if not isSimple:
  297. if isJina == 'jina':
  298. GlobalState.task_queue.appendleft(task_fight_jina(isAddStrengh))
  299. elif isJina == 'yongbing':
  300. GlobalState.task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  301. elif isJina == 'monster':
  302. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  303. elif isJina == 'big_monster' or isJina == 'bigMonster_max':
  304. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  305. elif isJina == 'jina_call':
  306. ### 全部聊天记录都是新吉娜
  307. GlobalState.task_queue.appendleft(task_call_jina())
  308. GlobalState.task_queue.appendleft(task_call_jina())
  309. GlobalState.task_queue.appendleft(task_call_jina())
  310. GlobalState.task_queue.appendleft(task_call_jina())
  311. elif isJina == 'jina_onlyFight':
  312. GlobalState.task_queue.appendleft(task_fight_jina_only())
  313. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  314. GlobalState.task_queue.appendleft(task_train(train_type))
  315. if isSimple == False:
  316. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  317. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  318. if isJina == 'monster' and isAddStrengh:
  319. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  320. else:
  321. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  322. else:
  323. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  324. print("add rare activity")
  325. if GlobalState.g_times % 5 == 1:
  326. if get_rungame_type() == 0:
  327. GlobalState.task_queue.appendleft(check_buildOrResearch())
  328. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  329. GlobalState.task_queue.appendleft(task_information())
  330. GlobalState.task_queue.appendleft(task_checkDonata())
  331. GlobalState.task_queue.appendleft(task_checkMaster())
  332. GlobalState.task_queue.appendleft(task_checkAdventure())
  333. GlobalState.task_queue.appendleft(task_train(train_type))
  334. GlobalState.task_queue.appendleft(task_useAnnimalSkill())
  335. GlobalState.task_queue.appendleft(task_read_mails())
  336. GlobalState.task_queue.appendleft(task_getStrength())
  337. if auto_participate:
  338. GlobalState.task_queue.appendleft(task_checkConfilits())
  339. GlobalState.task_queue.appendleft(task_checkDiamond())
  340. GlobalState.task_queue.appendleft(task_fight_campion())
  341. GlobalState.task_queue.appendleft(task_get_fire_crystal())
  342. GlobalState.task_queue.appendleft(task_checkUnionTreasure())
  343. #GlobalState.task_queue.appendleft(task_checkBenifitStatus())
  344. GlobalState.task_queue.appendleft(task_gotoTree())
  345. GlobalState.task_queue.appendleft(task_checkHelp())
  346. if activity == 'redPackage':
  347. GlobalState.task_queue.appendleft(task_get_redPackage())
  348. if isJina == 'bigMonster_max':
  349. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  350. print("check restart")
  351. GlobalState.g_times += 1
  352. restart_times = 7
  353. if GlobalState.g_switch:
  354. restart_times = 4
  355. if GlobalState.g_times % restart_times == 0 and GlobalState.g_times != 0:
  356. if GlobalState.g_isRestart:
  357. handle_end_game()
  358. if GlobalState.g_switch == False:
  359. if always:
  360. nextTaskTime = random.randint(400, 450)
  361. set_nextTaskTime(nextTaskTime)
  362. myTimeSleep(nextTaskTime, send_status)
  363. else:
  364. nextTaskTime = random.randint(1000, 2000)
  365. set_nextTaskTime(nextTaskTime)
  366. myTimeSleep(nextTaskTime, send_status)
  367. else:
  368. nextTaskTime = random.randint(20, 50)
  369. set_nextTaskTime(nextTaskTime)
  370. myTimeSleep(nextTaskTime, send_status)
  371. if GlobalState.g_isRestart:
  372. handle_restart_game()
  373. else:
  374. nextTaskTime = random.randint(400, 450)
  375. set_nextTaskTime(nextTaskTime)
  376. myTimeSleep(nextTaskTime, send_status)
  377. GlobalState.task_queue.clear()
  378. send_status(f'自动模式结束')
  379. GlobalState.event.clear()
  380. daily_config = {
  381. "login_task": False,
  382. "fight_bigMonster_times": 0
  383. }
  384. def check_daily_config(config):
  385. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  386. print(f"Today: {today}") # 打印当前日期
  387. print(f"Config: {config}") # 打印传入的配置
  388. if "daily" not in config:
  389. print("Daily key not found, creating it.") # 调试信息
  390. config["daily"] = {}
  391. return False
  392. if today not in config["daily"]:
  393. print(f"Today's config not found: {today}") # 调试信息
  394. return False
  395. else:
  396. print(f"Today's config found: {today}") # 调试信息
  397. return True
  398. def update_rungame_type(dstType=None):
  399. config = read_Dailycfg()
  400. runTypeStr = 'runType'
  401. if runTypeStr not in config:
  402. if dstType is not None:
  403. config[runTypeStr] = dstType
  404. else:
  405. config[runTypeStr] = 1
  406. write_Dailycfg(config)
  407. print(f"更新下次启动{config[runTypeStr]}")
  408. return 0
  409. else:
  410. value = config[runTypeStr]
  411. if dstType is not None:
  412. config[runTypeStr] = dstType
  413. else:
  414. config[runTypeStr] = (value + 1) % 2
  415. write_Dailycfg(config)
  416. print(f"更新下次启动{config[runTypeStr]}")
  417. return value
  418. def get_rungame_type():
  419. config = read_Dailycfg()
  420. runTypeStr = 'runType'
  421. if runTypeStr not in config:
  422. return 0
  423. else:
  424. if config[runTypeStr] == 0:
  425. return 1
  426. else:
  427. return 0
  428. # 修改或添加 "login_task" 的值
  429. def set_login_task(config, value):
  430. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  431. if today not in config["daily"]: # 如果当天的配置不存在
  432. config["daily"][today] = {} # 创建当天的配置
  433. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  434. return config
  435. # 修改或添加 "fight_bigMonster_times" 的值
  436. def set_fight_big_monster_times(config, value):
  437. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  438. if today not in config["daily"]: # 如果当天的配置不存在
  439. config["daily"][today] = {} # 创建当天的配置
  440. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  441. return config
  442. def add_today_daily_config(config, daily_config, overwrite=False):
  443. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  444. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  445. config["daily"][today] = daily_config # 添加或更新
  446. return config
  447. # 清理非当天的每日配置
  448. def clean_old_daily_configs(config):
  449. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  450. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  451. for key in keys_to_remove:
  452. del config["daily"][key] # 删除非当天的每日配置
  453. return config
  454. def write_cfg(config):
  455. try:
  456. config_manager = MinIOConfigManager()
  457. localCfg_name = task_getComputerName() + '_config'
  458. config_manager.set_config(localCfg_name, config)
  459. except Exception as e:
  460. print("写入minIO错误, 尝试写入本地")
  461. with open('config.json', 'w') as config_file:
  462. json.dump(config, config_file, indent=4)
  463. def read_cfg():
  464. try:
  465. config_manager = MinIOConfigManager()
  466. localCfg_name = task_getComputerName() + '_config'
  467. localCfg = config_manager.get_config(localCfg_name)
  468. config = json.loads(localCfg)
  469. GlobalState.g_cureNum = int(config['cureNumber'])
  470. return config
  471. except Exception as e:
  472. print("读取minIO错误, 尝试读取本地")
  473. try:
  474. with open('config.json', 'r') as config_file:
  475. config = json.load(config_file)
  476. GlobalState.g_cureNum = int(config['cureNumber'])
  477. return config
  478. except FileNotFoundError:
  479. print("配置文件不存在,请检查文件路径。")
  480. return None
  481. except PermissionError:
  482. print("没有权限读取配置文件。")
  483. return None
  484. except json.JSONDecodeError:
  485. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  486. return None
  487. def write_Dailycfg(config):
  488. try:
  489. config_manager = MinIOConfigManager()
  490. localCfg_name = task_getComputerName() + '_daily'
  491. config_manager.set_config(localCfg_name, config)
  492. except Exception as e:
  493. print("写入minIO错误, 尝试写入本地")
  494. with open('daily.json', 'w') as config_file:
  495. json.dump(config, config_file, indent=4)
  496. def read_Dailycfg():
  497. try:
  498. config_manager = MinIOConfigManager()
  499. localCfg_name = task_getComputerName() + '_daily'
  500. localCfg = config_manager.get_config(localCfg_name)
  501. config = json.loads(localCfg)
  502. return config
  503. except Exception as e:
  504. print("读取minIO错误, 尝试读取本地")
  505. try:
  506. with open('daily.json', 'r') as config_file:
  507. config = json.load(config_file)
  508. return config
  509. except FileNotFoundError:
  510. print("配置文件不存在,请检查文件路径。")
  511. return None
  512. except PermissionError:
  513. print("没有权限读取配置文件。")
  514. return None
  515. except json.JSONDecodeError:
  516. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  517. return None
  518. @socketio.on('begin_auto')
  519. def handle_auto(data):
  520. write_cfg(data)
  521. config = read_cfg()
  522. print("config", config)
  523. auto_task(config)
  524. def auto_task(data):
  525. if data == None:
  526. isMaxCollect = '4,3,2,1'
  527. isSimple = False
  528. isJina = 'jina'
  529. isAddStrengh = False
  530. activity = 'none'
  531. participateJijie = False
  532. auto_daily = False
  533. train_type = 'none'
  534. always = False
  535. cureNumber = 500
  536. lineCheck = False
  537. switch = False
  538. GlobalState.g_isRestart = True
  539. else:
  540. isMaxCollect = data['maxCollect']
  541. isSimple = data['simple']
  542. isJina = data['jina']
  543. isAddStrengh = data['add_strength']
  544. activity = data['activity']
  545. participateJijie = data['participate_jijie']
  546. auto_daily = False
  547. train_type = data['train']
  548. always = data['always']
  549. cureNumber = int(data['cureNumber'])
  550. lineCheck = data['lineCheck']
  551. switch = data['switch']
  552. GlobalState.g_isRestart = data['is_restart']
  553. GlobalState.g_cureNum = cureNumber
  554. GlobalState.g_switch = switch
  555. set_lineCheck(lineCheck)
  556. send_status(f'开始自动模式')
  557. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  558. @socketio.on('begin_auto_participate')
  559. def handle_auto_participate():
  560. send_status(f'开始自动集结模式')
  561. executor.submit(auto_participate)
  562. @socketio.on('begin_testNewFun')
  563. def handle_auto_testNewFun():
  564. send_status(f'开始自动测试新功能')
  565. task_testFun().run()
  566. @socketio.on('auto_palace')
  567. def handle_auto_palace():
  568. send_status(f'开始自动王城')
  569. executor.submit(auto_palace)
  570. def monitor_game_runtime():
  571. last_value = GlobalState.g_times
  572. while True:
  573. current_value = GlobalState.g_times
  574. if current_value != last_value:
  575. last_value = current_value
  576. GlobalState.last_change_time = time.time()
  577. print(f"g_times changed to {current_value}")
  578. # 检查是否超过60分钟没有变化
  579. if time.time() - GlobalState.last_change_time > 3600: # 3600秒=60分钟
  580. print("g_times hasn't changed for 60 minutes!")
  581. handle_restart_game()
  582. time.sleep(60)
  583. if __name__ == '__main__':
  584. init()
  585. if '--reset' in sys.argv:
  586. time.sleep(2)
  587. GlobalState.isReset = True
  588. print("需要重启游戏")
  589. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  590. runTask.daemon = True
  591. runTask.start()
  592. monitor_thread = threading.Thread(target=monitor_game_runtime, daemon=True)
  593. monitor_thread.start()
  594. socketio.run(app, host= '0.0.0.0', debug=True, use_reloader=False)#关闭自动重载