app_dongri.py 17 KB

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