script_task.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from enum import Enum, auto
  5. from time import sleep
  6. from datetime import datetime, timedelta
  7. import cv2
  8. import numpy as np
  9. import random
  10. from typing import Any
  11. from cached_property import cached_property
  12. from module.atom.image import RuleImage
  13. from module.atom.click import RuleClick
  14. from module.atom.ocr import RuleOcr
  15. from module.base.protect import random_sleep
  16. from module.base.timer import Timer
  17. from module.exception import TaskEnd, GameStuckError
  18. from module.logger import logger
  19. from tasks.base_task import BaseTask
  20. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
  21. from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
  22. from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig, ActivityShikigami
  23. from tasks.Component.BaseActivity.base_activity import BaseActivity
  24. from tasks.Component.BaseActivity.config_activity import GeneralClimb
  25. from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
  26. from tasks.GameUi.game_ui import GameUi
  27. import tasks.Component.GeneralBattle.config_general_battle
  28. import tasks.ActivityShikigami.page as game
  29. from tasks.BudokaiTournament.config import BudokaiTournament
  30. from tasks.BudokaiTournament.assets import BudokaiTournamentAssets
  31. class LimitTimeOut(Exception):
  32. pass
  33. class LimitCountOut(Exception):
  34. pass
  35. class StateMachine(BaseTask):
  36. run_idx: int = 0 # 当前爬塔类型
  37. _count_map = None
  38. @cached_property
  39. def conf(self) -> BudokaiTournament:
  40. return self.config.model.budokai_tournament
  41. @property
  42. def climb_type(self) -> str:
  43. if self.run_idx >= len(self.conf.run_sequence()):
  44. return self.conf.run_sequence()[-1]
  45. return self.conf.run_sequence()[self.run_idx]
  46. @property
  47. def count_map(self) -> dict[str, int]:
  48. """
  49. :return: key: climb type, value: run count
  50. """
  51. if not getattr(self, "_count_map", None):
  52. self._count_map = {climb_type: 0 for climb_type in self.conf.run_sequence()}
  53. return self._count_map
  54. # ----------------------------------------------------
  55. def put_status(self):
  56. """
  57. 更新全局状态
  58. """
  59. def get_count(self) -> int:
  60. return self.count_map[self.climb_type]
  61. def get_limit(self) -> int:
  62. limit = getattr(self.conf.daily_training, f'limit_{self.climb_type}', 0)
  63. return 0 if not limit else limit
  64. # # 超过运行时间
  65. # if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
  66. # logger.info(f"Climb type {self.climb_type} time out")
  67. # raise LimitTimeOut
  68. # 次数达到限制
  69. if get_count(self) >= get_limit(self):
  70. logger.info(f"Climb type {self.climb_type} count limit reached")
  71. raise LimitCountOut
  72. def switch_next(self):
  73. """
  74. 切换下一种爬塔类型
  75. :return: True 切换成功 or False
  76. """
  77. self.run_idx += 1
  78. if self.run_idx >= len(self.conf.run_sequence()):
  79. logger.info('All climbing activities have been completed')
  80. return False
  81. # 切换爬塔类型了, 恢复所有状态
  82. self.current_count = 0
  83. logger.hr(f'Climb switch to {self.climb_type}', 2)
  84. return True
  85. class Foot(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets, BudokaiTournamentAssets):
  86. def lock_team(self, battle_conf: GeneralBattleConfig):
  87. """
  88. 根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
  89. """
  90. enable_preset = getattr(battle_conf, f"enable_preset_{self.climb_type}", False)
  91. if not enable_preset:
  92. logger.info(f'Lock {self.climb_type} team')
  93. self.ui_click(self.I_UNLOCK, stop=self.I_LOCK, interval=1.5)
  94. return
  95. logger.info(f'Unlock {self.climb_type} team')
  96. self.ui_click(self.I_LOCK, stop=self.I_UNLOCK, interval=1.5)
  97. def start_battle(self):
  98. click_times, max_times = 0, random.randint(4, 8)
  99. while 1:
  100. self.screenshot()
  101. if self.is_in_battle(False):
  102. break
  103. if click_times >= max_times:
  104. logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
  105. return False
  106. if (self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
  107. self.appear_then_click(self.I_UI_CONFIRM, interval=1) ):
  108. continue
  109. if self.ocr_appear_click(self.O_FIRE, interval=2) or self.appear_then_click(self.I_IMG3, interval=2)or self.appear_then_click(self.I_IMG4, interval=2):
  110. click_times += 1
  111. logger.info(f'Try click fire, remain times[{max_times - click_times}]')
  112. continue
  113. # 运行战斗
  114. return self.run_general_battle(config=self.get_general_battle_conf())
  115. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  116. func = getattr(self, f'battle_wait_daily_training', self.battle_wait_daily_training)
  117. return func(random_click_swipt_enable)
  118. def battle_wait_daily_training(self, random_click_swipt_enable: bool):
  119. self.C_REWARD_1.name, self.C_REWARD_2.name, self.C_REWARD_3.name = 'C_REWARD', 'C_REWARD', 'C_REWARD'
  120. self.device.stuck_record_add('BATTLE_STATUS_S')
  121. self.device.click_record_clear()
  122. logger.info(f"Start {self.climb_type} battle process")
  123. if self.climb_type == 'daily_training':
  124. self.count_map[self.climb_type] = self.current_count
  125. super_long_timer = None
  126. else:
  127. super_long_timer = Timer(270).start()
  128. super_long_cnt = 0
  129. while 1:
  130. self.screenshot()
  131. # 出现赢的鼓,点击直到消失
  132. if self.appear_then_click(self.I_WIN, interval=1.8):
  133. self.ui_click_until_disappear(self.I_DE_WIN, interval=1.5)
  134. return True
  135. if self.appear(self.I_FALSE, threshold=0.8):
  136. logger.warning('False battle')
  137. self.ui_click_until_disappear(self.I_FALSE)
  138. return False
  139. if self.ui_reward_appear_click():
  140. continue
  141. if super_long_timer and super_long_timer.reached_and_reset():
  142. if super_long_cnt >= 3:
  143. raise GameStuckError
  144. self.click(self.C_RANDOM_CLICK, interval=10)
  145. self.device.stuck_record_add('BATTLE_STATUS_S')
  146. logger.info(f"Start click in battle process for 270s")
  147. super_long_cnt += 1
  148. # 随机滑动
  149. if random_click_swipt_enable:
  150. self.random_click_swipt()
  151. return False
  152. def battle_wait_cultivation_drills(self, random_click_swipt_enable: bool):
  153. self.C_REWARD_1.name, self.C_REWARD_2.name, self.C_REWARD_3.name = 'C_REWARD', 'C_REWARD', 'C_REWARD'
  154. self.device.stuck_record_add('BATTLE_STATUS_S')
  155. self.device.click_record_clear()
  156. logger.info(f"Start {self.climb_type} battle process")
  157. while 1:
  158. self.screenshot()
  159. def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
  160. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
  161. # self.conf.validate_switch_preset()
  162. enable_preset = getattr(self.conf.general_battle, f'enable_preset_{self.climb_type}', False)
  163. group, team = getattr(self.conf.switch_soul_config, f'group_team_{self.climb_type}').split(',')
  164. return gbc(lock_team_enable=not enable_preset,
  165. preset_enable=enable_preset,
  166. preset_group=group if enable_preset else 1,
  167. preset_team=team if enable_preset else 1,
  168. green_enable=getattr(self.conf.general_battle, f'enable_green_{self.climb_type}', False),
  169. green_mark=getattr(self.conf.general_battle, f'green_mark_{self.climb_type}'),
  170. random_click_swipt_enable=getattr(self.conf.general_battle,
  171. f'enable_anti_detect_{self.climb_type}',
  172. False), )
  173. def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
  174. """
  175. 随机点击
  176. :param exclude_click: 排除的点击位置
  177. :param click_now: 是否立即点击
  178. :return: 随机的点击位置
  179. """
  180. options = [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM]
  181. if exclude_click:
  182. options = [option for option in options if option not in exclude_click]
  183. target = random.choice(options)
  184. if click_now:
  185. self.click(target, interval=1.8)
  186. return target
  187. def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
  188. conf = self.conf.switch_soul_config
  189. enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
  190. enable_by_name = getattr(conf, f"enable_switch_by_name_{self.climb_type}", False)
  191. if not enable_switch and not enable_by_name:
  192. return
  193. logger.hr('Start switch soul', 2)
  194. # conf.validate_switch_soul()
  195. self.ui_click(enter_button, stop=self.I_CHECK_RECORDS, interval=1)
  196. if enable_by_name:
  197. group, team = getattr(conf, f"group_team_name_{self.climb_type}").split(",")
  198. self.run_switch_soul_by_name(group, team)
  199. elif enable_switch:
  200. group_team = getattr(conf, f"group_team_{self.climb_type}")
  201. self.run_switch_soul(group_team)
  202. self.ui_click(self.I_UI_BACK_YELLOW, stop=cur_img, interval=1)
  203. class ScriptTask(Foot):
  204. def run(self) -> None:
  205. # self.limit_time: timedelta = self.conf.general_climb.limit_time_v
  206. #
  207. for climb_type in self.conf.run_sequence():
  208. # 进入到活动的主页面,不是具体的战斗页面
  209. self.goto_page(game.page_climb_act)
  210. try:
  211. if getattr(self.conf.daily_training, f'limit_{self.climb_type}') > 0:
  212. method_func = getattr(self, f'_run_{climb_type}')
  213. method_func()
  214. except LimitCountOut as e:
  215. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
  216. except LimitTimeOut as e:
  217. break
  218. finally:
  219. # 切换下一个爬塔类型
  220. self.switch_next()
  221. # 返回庭院
  222. logger.hr("Exit BudokaiTournament", 2)
  223. self.goto_page(game.page_main)
  224. if self.conf.daily_training.active_souls_clean:
  225. self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
  226. self.set_next_run(task="BudokaiTournament", success=True)
  227. raise TaskEnd
  228. def _run_daily_training(self):
  229. """
  230. 更新前请先看 ./README.md
  231. """
  232. logger.hr(f'Start run climb type PASS', 1)
  233. self.ui_clicks([self.I_TO_BATTLE_MAIN, self.I_TO_BATTLE_MAIN_2],
  234. stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  235. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  236. ocr_limit_timer = Timer(1).start()
  237. click_limit_timer = Timer(4).start()
  238. while 1:
  239. self.screenshot()
  240. self.put_status()
  241. # --------------------------------------------------------------
  242. if (self.appear_then_click(self.I_UI_CONFIRM, interval=0.5)
  243. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5)):
  244. continue
  245. if self.ui_reward_appear_click():
  246. continue
  247. if not ocr_limit_timer.reached():
  248. continue
  249. ocr_limit_timer.reset()
  250. if not self.ocr_appear(self.O_FIRE):
  251. continue
  252. # --------------------------------------------------------------
  253. self.lock_team(self.conf.general_battle)
  254. if not self.check_tickets_enough():
  255. logger.warning(f'No tickets left, wait for next time')
  256. break
  257. if self.conf.daily_training.random_sleep:
  258. random_sleep(probability=0.2)
  259. if self.start_battle():
  260. continue
  261. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
  262. def _run_cultivation_drills(self):
  263. """
  264. 更新前请先看 ./README.md
  265. """
  266. logger.hr(f'Start run climb type BOSS')
  267. self.ui_clicks([self.I_TO_BATTLE_BOSS],
  268. stop=self.I_CHECK_BATTLE_BOSS, interval=1)
  269. cnt_scout = 0 # 保留
  270. switch_soul_done = False
  271. while 1:
  272. self.screenshot()
  273. # --------------------------------------------------------------
  274. if (self.appear_then_click(self.I_UI_CONFIRM, interval=0.5)
  275. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5)):
  276. continue
  277. if self.ui_reward_appear_click():
  278. continue
  279. if self.appear_then_click(self.I_IMG2, interval=0.8):
  280. continue
  281. # 搜寻
  282. if self.appear(self.I_IMG1):
  283. if not self.check_tickets_enough():
  284. logger.warning(f'No tickets left, wait for next time')
  285. break
  286. # self.put_status()
  287. if cnt_scout >= self.conf.daily_training.limit_cultivation_drills:
  288. raise LimitCountOut
  289. # Click search once, then wait for the boss-detail page without
  290. # sending another input during the page transition.
  291. if self.appear_then_click(self.I_IMG1, interval=1.5):
  292. transition_timer = Timer(10).start()
  293. while 1:
  294. self.screenshot()
  295. if self.appear(self.I_IMG3) or self.appear(self.I_IMG4):
  296. logger.info(f'Cultivation drill done, for next time {cnt_scout}')
  297. cnt_scout += 1
  298. break
  299. if transition_timer.reached():
  300. logger.warning('Wait cultivation drill boss detail timeout, retry search')
  301. break
  302. continue
  303. if not (self.appear(self.I_IMG3) or self.appear(self.I_IMG4)):
  304. continue
  305. if not switch_soul_done:
  306. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_BATTLE_MAIN_TO_RECORDS)
  307. switch_soul_done = True
  308. continue
  309. self.lock_team(self.conf.general_battle)
  310. if not self.check_tickets_enough():
  311. logger.warning(f'No tickets left, wait for next time')
  312. if not self.ui_click(self.C_BOSS_DETAIL_CLOSE, stop=self.I_CHECK_BATTLE_BOSS,
  313. interval=1, timeout=10):
  314. raise GameStuckError('Unable to close cultivation drills boss detail')
  315. break
  316. if self.conf.daily_training.random_sleep:
  317. random_sleep(probability=0.2)
  318. if self.start_battle():
  319. continue
  320. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_BOSS, interval=1)
  321. def check_tickets_enough(self) -> bool:
  322. """
  323. 判断当前爬塔门票是否足够
  324. :return: True 可以运行 or False
  325. """
  326. logger.hr(f'Check {self.climb_type} tickets')
  327. # apper_button = self.O_FIRE if self.climb_type == 'daily_training' else self.I_IMG3
  328. if self.climb_type == 'daily_training' and not self.wait_until_appear(self.O_FIRE, wait_time=3):
  329. logger.warning(f'Detect fire fail, try reidentify')
  330. return False
  331. self.screenshot()
  332. remain_times = 0
  333. if self.climb_type == 'daily_training':
  334. remain_times = self.O_REMAIN_AP.ocr_digit(self.device.image)
  335. if self.climb_type == 'cultivation_drills':
  336. remain_times= self.O_REMAIN_BOSS.ocr_digit(self.device.image)
  337. return remain_times > 0
  338. if __name__ == '__main__':
  339. from module.config.config import Config
  340. from module.device.device import Device
  341. c = Config('oas1')
  342. d = Device(c)
  343. t = ScriptTask(c, d)
  344. t.run()