app_dongri.py 21 KB

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