app_dongri.py 20 KB

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