app_dongri.py 19 KB

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