app_dongri.py 21 KB

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