app_dongri.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. send_status(f'巨熊行动:在60min内,切换到无尽模式')
  252. g_times = 2
  253. task_queue.appendleft(task_checkActivities())
  254. elif is_within_n_minutes(get_todo_time("巨熊行动"), 10, 40):
  255. task_queue.appendleft(task_returnAllLine())
  256. if len(task_queue) < 5:
  257. task_queue.appendleft(task_paticipateInTeam())
  258. task_queue.appendleft(task_paticipateInTeam())
  259. task_queue.appendleft(task_paticipateInTeam())
  260. myTimeSleep_big()
  261. send_status(f'巨熊行动中')
  262. g_times = 2
  263. continue
  264. # special activity
  265. if activity == 'lianmeng':
  266. task_queue.appendleft(task_activity_lianmeng())
  267. elif activity == 'cure':
  268. task_queue.appendleft(task_cure(True, g_cureNum))
  269. elif activity == 'only_cure':
  270. task_queue.appendleft(task_cure(True, g_cureNum))
  271. task_queue.appendleft(task_cure(True, g_cureNum))
  272. task_queue.appendleft(task_cure(True, g_cureNum))
  273. return
  274. # first run
  275. if g_times % 3 == 1:
  276. task_queue.appendleft(check_safe_collect())
  277. if get_rungame_type() == 0:
  278. task_queue.appendleft(task_checkActivities())
  279. if isSimple == False:
  280. task_queue.appendleft(task_information())
  281. task_queue.appendleft(check_buildOrResearch())
  282. task_queue.appendleft(task_cure(True, g_cureNum))
  283. task_queue.appendleft(task_checkStoreRoom())
  284. if not isSimple:
  285. if isJina == 'jina':
  286. task_queue.appendleft(task_fight_jina(isAddStrengh))
  287. elif isJina == 'yongbing':
  288. task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  289. elif isJina == 'monster':
  290. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  291. elif isJina == 'big_monster':
  292. task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  293. elif isJina == 'jina_call':
  294. ### 全部聊天记录都是新吉娜
  295. task_queue.appendleft(task_call_jina())
  296. task_queue.appendleft(task_call_jina())
  297. task_queue.appendleft(task_call_jina())
  298. task_queue.appendleft(task_call_jina())
  299. elif isJina == 'jina_onlyFight':
  300. task_queue.appendleft(task_fight_jina_only())
  301. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  302. task_queue.appendleft(task_train(train_type))
  303. if isSimple == False:
  304. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  305. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  306. if isJina == 'monster' and isAddStrengh:
  307. task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  308. else:
  309. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  310. else:
  311. task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  312. if g_times % 3 == 0:
  313. task_queue.appendleft(task_checkDonata())
  314. task_queue.appendleft(task_checkMaster())
  315. task_queue.appendleft(task_checkAdventure())
  316. task_queue.appendleft(task_train(train_type))
  317. task_queue.appendleft(task_useAnnimalSkill())
  318. task_queue.appendleft(task_read_mails())
  319. if auto_participate:
  320. task_queue.appendleft(task_checkConfilits())
  321. task_queue.appendleft(task_checkDiamond())
  322. task_queue.appendleft(task_fight_campion())
  323. task_queue.appendleft(task_checkBenifitStatus())
  324. task_queue.appendleft(task_checkHelp())
  325. task_queue.appendleft(task_gotoTree())
  326. #task_queue.appendleft(task_get_redPackage())
  327. restart_times = 7
  328. global g_switch
  329. if g_switch:
  330. restart_times = 4
  331. if g_times == restart_times:
  332. handle_end_game()
  333. if always:
  334. myTimeSleep(random.randint(350, 400), send_status)
  335. else:
  336. myTimeSleep(random.randint(1000, 2000), send_status)
  337. handle_restart_game()
  338. else:
  339. if isAddStrengh:
  340. myTimeSleep(random.randint(350, 400), send_status)
  341. else:
  342. myTimeSleep(random.randint(350, 400), send_status)
  343. task_queue.clear()
  344. send_status(f'自动模式结束')
  345. event.clear()
  346. daily_config = {
  347. "login_task": False,
  348. "fight_bigMonster_times": 0
  349. }
  350. def check_daily_config(config):
  351. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  352. print(f"Today: {today}") # 打印当前日期
  353. print(f"Config: {config}") # 打印传入的配置
  354. if "daily" not in config:
  355. print("Daily key not found, creating it.") # 调试信息
  356. config["daily"] = {}
  357. return False
  358. if today not in config["daily"]:
  359. print(f"Today's config not found: {today}") # 调试信息
  360. return False
  361. else:
  362. print(f"Today's config found: {today}") # 调试信息
  363. return True
  364. def update_rungame_type(dstType=None):
  365. config = read_Dailycfg()
  366. runTypeStr = 'runType'
  367. if runTypeStr not in config:
  368. if dstType is not None:
  369. config[runTypeStr] = dstType
  370. else:
  371. config[runTypeStr] = 1
  372. write_Dailycfg(config)
  373. print(f"更新下次启动{config[runTypeStr]}")
  374. return 0
  375. else:
  376. value = config[runTypeStr]
  377. if dstType is not None:
  378. config[runTypeStr] = dstType
  379. else:
  380. config[runTypeStr] = (value + 1) % 2
  381. write_Dailycfg(config)
  382. print(f"更新下次启动{config[runTypeStr]}")
  383. return value
  384. def get_rungame_type():
  385. config = read_Dailycfg()
  386. runTypeStr = 'runType'
  387. if runTypeStr not in config:
  388. return 0
  389. else:
  390. return config[runTypeStr]
  391. # 修改或添加 "login_task" 的值
  392. def set_login_task(config, value):
  393. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  394. if today not in config["daily"]: # 如果当天的配置不存在
  395. config["daily"][today] = {} # 创建当天的配置
  396. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  397. return config
  398. # 修改或添加 "fight_bigMonster_times" 的值
  399. def set_fight_big_monster_times(config, value):
  400. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  401. if today not in config["daily"]: # 如果当天的配置不存在
  402. config["daily"][today] = {} # 创建当天的配置
  403. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  404. return config
  405. def add_today_daily_config(config, daily_config, overwrite=False):
  406. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  407. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  408. config["daily"][today] = daily_config # 添加或更新
  409. return config
  410. # 清理非当天的每日配置
  411. def clean_old_daily_configs(config):
  412. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  413. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  414. for key in keys_to_remove:
  415. del config["daily"][key] # 删除非当天的每日配置
  416. return config
  417. def write_cfg(config):
  418. with open('config.json', 'w') as config_file:
  419. json.dump(config, config_file, indent=4)
  420. def read_cfg():
  421. global g_cureNum
  422. try:
  423. with open('config.json', 'r') as config_file:
  424. config = json.load(config_file)
  425. g_cureNum = config['cureNumber']
  426. return config
  427. except FileNotFoundError:
  428. print("配置文件不存在,请检查文件路径。")
  429. return None
  430. except PermissionError:
  431. print("没有权限读取配置文件。")
  432. return None
  433. except json.JSONDecodeError:
  434. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  435. return None
  436. def write_Dailycfg(config):
  437. with open('daily.json', 'w') as config_file:
  438. json.dump(config, config_file, indent=4)
  439. def read_Dailycfg():
  440. try:
  441. with open('daily.json', 'r') as config_file:
  442. config = json.load(config_file)
  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. @socketio.on('begin_auto')
  454. def handle_auto(data):
  455. write_cfg(data)
  456. config = read_cfg()
  457. print("config", config)
  458. auto_task(config)
  459. def auto_task(data):
  460. global autoTask, g_cureNum
  461. if data == None:
  462. isMaxCollect = '4,3,2,1'
  463. isSimple = False
  464. isJina = 'jina'
  465. isAddStrengh = False
  466. activity = 'none'
  467. participateJijie = False
  468. auto_daily = False
  469. train_type = 'none'
  470. always = False
  471. cureNumber = 500
  472. lineCheck = False
  473. switch = False
  474. else:
  475. isMaxCollect = data['maxCollect']
  476. isSimple = data['simple']
  477. isJina = data['jina']
  478. isAddStrengh = data['add_strength']
  479. activity = data['activity']
  480. participateJijie = data['participate_jijie']
  481. auto_daily = data['auto_daily']
  482. train_type = data['train']
  483. always = data['always']
  484. cureNumber = data['cureNumber']
  485. lineCheck = data['lineCheck']
  486. switch = data['switch']
  487. g_cureNum = cureNumber
  488. g_switch = switch
  489. set_lineCheck(lineCheck)
  490. send_status(f'开始自动模式')
  491. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  492. @socketio.on('begin_auto_participate')
  493. def handle_auto_participate():
  494. global autoTask
  495. send_status(f'开始自动集结模式')
  496. executor.submit(auto_participate)
  497. @socketio.on('begin_auto_ranshuang')
  498. def handle_auto_ranshuang():
  499. global autoTask
  500. send_status(f'开始自动燃霜')
  501. executor.submit(auto_ranshuang)
  502. @socketio.on('auto_palace')
  503. def handle_auto_palace():
  504. global autoTask
  505. send_status(f'开始自动王城')
  506. executor.submit(auto_palace)
  507. if __name__ == '__main__':
  508. init()
  509. if '--reset' in sys.argv:
  510. isReset = True
  511. print("需要重启游戏")
  512. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  513. runTask.daemon = True
  514. runTask.start()
  515. socketio.run(app, host= '0.0.0.0', debug=True)