app_dongri.py 20 KB

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