app_dongri.py 20 KB

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