script_task.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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
  18. from module.logger import logger
  19. from tasks.base_task import BaseTask
  20. from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy
  21. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
  22. from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
  23. from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig, ActivityShikigami
  24. from tasks.Component.BaseActivity.base_activity import BaseActivity
  25. from tasks.Component.BaseActivity.config_activity import GeneralClimb
  26. from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
  27. from tasks.GameUi.game_ui import GameUi
  28. import tasks.Component.GeneralBattle.config_general_battle
  29. import tasks.ActivityShikigami.page as game
  30. def _prepare_image_for_ocr(image: np.ndarray, asset: RuleOcr) -> np.ndarray:
  31. image_copy = image.copy()
  32. x, y, w, h = asset.roi
  33. roi_to_process = image_copy[y:y + h, x:x + w]
  34. if len(roi_to_process.shape) == 3:
  35. gray_image = cv2.cvtColor(roi_to_process, cv2.COLOR_BGR2GRAY)
  36. else:
  37. gray_image = roi_to_process
  38. # 自适应二值化
  39. _, binary_norm = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  40. _, binary_inv = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
  41. if cv2.countNonZero(binary_norm) < cv2.countNonZero(binary_inv):
  42. binary_correct = binary_norm
  43. else:
  44. binary_correct = binary_inv
  45. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 1))
  46. dilated_image = cv2.dilate(binary_correct, kernel, iterations=1)
  47. # 找轮廓
  48. contours, _ = cv2.findContours(dilated_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  49. processed_roi_content = None
  50. if contours:
  51. all_points = np.concatenate(contours, axis=0)
  52. bx, by, bw, bh = cv2.boundingRect(all_points)
  53. processed_roi_content = binary_correct[by:by + bh, bx:bx + bw]
  54. centered_roi = np.full((h, w), 255, dtype=np.uint8) # 255代表白色
  55. if processed_roi_content is not None:
  56. content_h, content_w = processed_roi_content.shape
  57. if content_h <= h and content_w <= w:
  58. # 计算居中粘贴的位置,放到中间
  59. start_y = (h - content_h) // 2
  60. start_x = (w - content_w) // 2
  61. paste_area = centered_roi[start_y:start_y + content_h, start_x:start_x + content_w]
  62. paste_area[processed_roi_content == 255] = 0
  63. else:
  64. logger.warning(f"Content for asset '{asset.name}' is larger than ROI. Skipping centering.")
  65. # 内容过大,直接使用原始二值图的反转作为结果
  66. centered_roi = cv2.bitwise_not(binary_correct)
  67. else:
  68. logger.warning(f"No content found in ROI for asset: {asset.name}. ROI will be blank.")
  69. processed_roi_bgr = cv2.cvtColor(centered_roi, cv2.COLOR_GRAY2BGR)
  70. image_copy[y:y + h, x:x + w] = processed_roi_bgr
  71. return image_copy
  72. class LimitTimeOut(Exception):
  73. pass
  74. class LimitCountOut(Exception):
  75. pass
  76. class StateMachine(BaseTask):
  77. run_idx: int = 0 # 当前爬塔类型
  78. _count_map = None
  79. @cached_property
  80. def conf(self) -> GeneralClimb:
  81. return self.config.model.activity_shikigami
  82. @property
  83. def climb_type(self) -> str:
  84. if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
  85. return self.conf.general_climb.run_sequence_v[-1]
  86. return self.conf.general_climb.run_sequence_v[self.run_idx]
  87. @property
  88. def count_map(self) -> dict[str, int]:
  89. """
  90. :return: key: climb type, value: run count
  91. """
  92. if not getattr(self, "_count_map", None):
  93. self._count_map = {climb_type: 0 for climb_type in self.conf.general_climb.run_sequence_v}
  94. return self._count_map
  95. # ----------------------------------------------------
  96. def put_status(self):
  97. """
  98. 更新全局状态
  99. """
  100. def get_count(self) -> int:
  101. return self.count_map[self.climb_type]
  102. def get_limit(self) -> int:
  103. limit = getattr(self.conf.general_climb, f'{self.climb_type}_limit', 0)
  104. return 0 if not limit else limit
  105. # 超过运行时间
  106. if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
  107. logger.info(f"Climb type {self.climb_type} time out")
  108. raise LimitTimeOut
  109. # 次数达到限制
  110. if get_count(self) >= get_limit(self):
  111. logger.info(f"Climb type {self.climb_type} count limit reached")
  112. raise LimitCountOut
  113. def switch_next(self):
  114. """
  115. 切换下一种爬塔类型
  116. :return: True 切换成功 or False
  117. """
  118. self.run_idx += 1
  119. if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
  120. logger.info('All climbing activities have been completed')
  121. return False
  122. # 切换爬塔类型了, 恢复所有状态
  123. self.current_count = 0
  124. logger.hr(f'Climb switch to {self.climb_type}', 2)
  125. return True
  126. class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
  127. """
  128. 更新前请先看 ./README.md
  129. """
  130. def run(self) -> None:
  131. self.limit_time: timedelta = self.conf.general_climb.limit_time_v
  132. #
  133. for climb_type in self.conf.general_climb.run_sequence_v:
  134. # 进入到活动的主页面,不是具体的战斗页面
  135. self.ui_get_current_page()
  136. self.ui_goto(game.page_climb_act)
  137. try:
  138. method_func = getattr(self, f'_run_{climb_type}')
  139. method_func()
  140. except LimitCountOut as e:
  141. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=2.8)
  142. except LimitTimeOut as e:
  143. break
  144. finally:
  145. # 切换下一个爬塔类型
  146. self.switch_next()
  147. # 返回庭院
  148. logger.hr("Exit Shikigami", 2)
  149. self.ui_get_current_page(False)
  150. self.ui_goto(game.page_main)
  151. if self.conf.general_climb.active_souls_clean:
  152. self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
  153. self.set_next_run(task="ActivityShikigami", success=True)
  154. raise TaskEnd
  155. def _run_pass(self):
  156. """
  157. 更新前请先看 ./README.md
  158. """
  159. logger.hr(f'Start run climb type PASS', 1)
  160. self.ui_clicks([self.I_TO_BATTLE_MAIN, self.I_TO_BATTLE_MAIN_2],
  161. stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  162. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  163. self.switch_climb_mode_in_game('pass')
  164. ocr_limit_timer = Timer(1).start()
  165. click_limit_timer = Timer(4).start()
  166. while 1:
  167. self.screenshot()
  168. self.put_status()
  169. # --------------------------------------------------------------
  170. if (self.appear_then_click(self.I_UI_CONFIRM, interval=0.5)
  171. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5)):
  172. continue
  173. if self.ui_reward_appear_click():
  174. continue
  175. if not ocr_limit_timer.reached():
  176. continue
  177. ocr_limit_timer.reset()
  178. if not self.ocr_appear(self.O_FIRE):
  179. continue
  180. # --------------------------------------------------------------
  181. self.lock_team(self.conf.general_battle)
  182. if not self.check_tickets_enough():
  183. logger.warning(f'No tickets left, wait for next time')
  184. break
  185. if self.conf.general_climb.random_sleep:
  186. random_sleep(probability=0.2)
  187. if self.start_battle():
  188. continue
  189. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
  190. def _run_ap(self):
  191. """
  192. 更新前请先看 ./README.md
  193. """
  194. logger.hr(f'Start run climb type AP')
  195. self.ui_clicks([self.I_TO_BATTLE_MAIN, self.I_TO_BATTLE_MAIN_2],
  196. stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  197. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  198. self.switch_climb_mode_in_game('ap')
  199. ocr_limit_timer = Timer(1).start()
  200. while 1:
  201. self.screenshot()
  202. self.put_status()
  203. # --------------------------------------------------------------
  204. if not ocr_limit_timer.reached():
  205. continue
  206. ocr_limit_timer.reset()
  207. if not self.ocr_appear(self.O_FIRE):
  208. self.appear_then_click(self.I_CHECK_BATTLE_MAIN, interval=4)
  209. continue
  210. # --------------------------------------------------------------
  211. self.lock_team(self.conf.general_battle)
  212. if not self.check_tickets_enough():
  213. logger.warning(f'No tickets left, wait for next time')
  214. break
  215. if self.conf.general_climb.random_sleep:
  216. random_sleep(probability=0.2)
  217. if self.start_battle():
  218. continue
  219. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
  220. def _run_boss(self):
  221. """
  222. 更新前请先看 ./README.md
  223. """
  224. logger.hr(f'Start run climb type BOSS')
  225. self.ui_clicks([self.I_TO_BATTLE_BOSS],
  226. stop=self.I_CHECK_BATTLE_BOSS, interval=1)
  227. while 1:
  228. self.screenshot()
  229. self.put_status()
  230. # --------------------------------------------------------------
  231. if not self.ocr_appear(self.O_FIRE):
  232. self.appear_then_click(self.I_CHECK_BATTLE_BOSS, interval=4)
  233. continue
  234. if self.conf.general_climb.random_sleep:
  235. random_sleep(probability=0.2)
  236. if self.start_battle():
  237. continue
  238. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_BOSS, interval=1)
  239. def _run_ap100(self):
  240. """
  241. 更新前请先看 ./README.md
  242. """
  243. logger.hr(f'Start run climb type AP100')
  244. def start_battle(self):
  245. click_times, max_times = 0, random.randint(4, 8)
  246. while 1:
  247. self.screenshot()
  248. if self.is_in_battle(False):
  249. break
  250. if click_times >= max_times:
  251. logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
  252. return
  253. if (self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
  254. self.appear_then_click(self.I_UI_CONFIRM, interval=1) ):
  255. continue
  256. if (self.appear(self.I_CHECK_BATTLE_MAIN, interval=1) or self.appear(self.I_CHECK_BATTLE_BOSS, interval=1)) \
  257. and self.ocr_appear_click(self.O_FIRE, interval=2):
  258. click_times += 1
  259. logger.info(f'Try click fire, remain times[{max_times - click_times}]')
  260. continue
  261. # 运行战斗
  262. self.run_general_battle(config=self.get_general_battle_conf())
  263. # def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  264. # # 通用战斗结束判断
  265. # self.device.stuck_record_add("BATTLE_STATUS_S")
  266. # self.device.click_record_clear()
  267. # logger.info(f"Start {self.climb_type} battle process")
  268. # self.count_map[self.climb_type] = self.current_count
  269. # for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
  270. # btn.name = "BATTLE_RANDOM"
  271. # ok_cnt, max_retry = 0, 8
  272. # while 1:
  273. # sleep(random.uniform(0.5, 1.5))
  274. # self.screenshot()
  275. # # 达到最大重试次数则直接交给上层处理
  276. # if ok_cnt > max_retry:
  277. # break
  278. # # 识别到挑战说明已经退出战斗
  279. # if ok_cnt > 0 and self.ocr_appear(self.O_FIRE):
  280. # return True
  281. # # 战斗失败
  282. # if self.appear(self.I_FALSE):
  283. # logger.warning("Battle failed")
  284. # self.ui_click_until_smt_disappear(self.random_reward_click(click_now=False), self.I_FALSE, interval=1.5)
  285. # return False
  286. # # 战斗成功
  287. # if self.appear_then_click(self.I_WIN, interval=2):
  288. # continue
  289. # # 出现 “魂” 和 紫蛇皮
  290. # if self.appear(self.I_REWARD) or self.appear(self.I_REWARD_PURPLE_SNAKE_SKIN) or \
  291. # self.appear(self.I_REWARD_GOLD) or self.appear(self.I_REWARD_GOLD_SNAKE_SKIN):
  292. # self.random_reward_click(exclude_click=[self.C_RANDOM_TOP, self.C_RANDOM_LEFT])
  293. # ok_cnt += 1
  294. # continue
  295. # # 已经不在战斗中了, 且奖励也识别过了, 则随机点击
  296. # if ok_cnt > 3 and not self.is_in_battle(False):
  297. # self.random_reward_click(exclude_click=[self.C_RANDOM_TOP, self.C_RANDOM_LEFT])
  298. # self.device.stuck_record_clear()
  299. # ok_cnt += 1
  300. # continue
  301. # # 战斗中随机滑动
  302. # if ok_cnt == 0 and random_click_swipt_enable:
  303. # self.random_click_swipt()
  304. # return True
  305. @battle_wait_strategy('reserve_default', 'idle_default', failure='default', success='soul')
  306. def battle_wait(self, *args, **kwargs):
  307. return self.battle_wait_with_strategy(*args, **kwargs)
  308. def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
  309. conf = self.conf.switch_soul_config
  310. enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
  311. enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
  312. if not enable_switch and not enable_by_name:
  313. return
  314. logger.hr('Start switch soul', 2)
  315. conf.validate_switch_soul()
  316. self.ui_click(enter_button, stop=self.I_CHECK_RECORDS, interval=1)
  317. if enable_by_name:
  318. group, team = getattr(conf, f"{self.climb_type}_group_team_name").split(",")
  319. self.run_switch_soul_by_name(group, team)
  320. elif enable_switch:
  321. group_team = getattr(conf, f"{self.climb_type}_group_team")
  322. self.run_switch_soul(group_team)
  323. self.ui_click(self.I_UI_BACK_YELLOW, stop=cur_img, interval=1)
  324. def switch_climb_mode_in_game(self, mode: str = 'ap'):
  325. map_check = {
  326. 'ap': self.I_CLIMB_MODE_AP,
  327. 'pass': self.I_CLIMB_MODE_PASS,
  328. }
  329. logger.info(f'Switch climb mode to {mode}')
  330. self.ui_click(self.I_CLIMB_MODE_SWITCH, stop=map_check[mode], interval=1.9)
  331. def lock_team(self, battle_conf: GeneralBattleConfig):
  332. """
  333. 根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
  334. """
  335. enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
  336. if not enable_preset:
  337. logger.info(f'Lock {self.climb_type} team')
  338. self.ui_click(self.I_UNLOCK, stop=self.I_LOCK, interval=1.5)
  339. return
  340. logger.info(f'Unlock {self.climb_type} team')
  341. self.ui_click(self.I_LOCK, stop=self.I_UNLOCK, interval=1.5)
  342. def check_tickets_enough(self) -> bool:
  343. """
  344. 判断当前爬塔门票是否足够
  345. :return: True 可以运行 or False
  346. """
  347. logger.hr(f'Check {self.climb_type} tickets')
  348. if not self.wait_until_appear(self.O_FIRE, wait_time=3):
  349. logger.warning(f'Detect fire fail, try reidentify')
  350. return False
  351. self.screenshot()
  352. remain_times = 0
  353. if self.climb_type == 'pass':
  354. remain_times = self.O_REMAIN_PASS.ocr_digit(self.device.image)
  355. if self.climb_type == 'ap':
  356. remain_times = self.O_REMAIN_AP.ocr_digit(self.device.image)
  357. if self.climb_type == 'boss':
  358. _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
  359. if self.climb_type == 'ap100':
  360. remain_times = self.O_REMAIN_AP100.ocr_digit(self.device.image)
  361. return remain_times > 0
  362. def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
  363. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
  364. self.conf.validate_switch_preset()
  365. enable_preset = getattr(self.conf.general_battle, f'enable_{self.climb_type}_preset', False)
  366. group, team = getattr(self.conf.switch_soul_config, f'{self.climb_type}_group_team').split(',')
  367. return gbc(lock_team_enable=not enable_preset,
  368. preset_enable=enable_preset,
  369. preset_group=group if enable_preset else 1,
  370. preset_team=team if enable_preset else 1,
  371. green_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_green', False),
  372. green_mark=getattr(self.conf.general_battle, f'{self.climb_type}_green_mark'),
  373. random_click_swipt_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_anti_detect',
  374. False), )
  375. def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
  376. """
  377. 随机点击
  378. :param exclude_click: 排除的点击位置
  379. :param click_now: 是否立即点击
  380. :return: 随机的点击位置
  381. """
  382. options = [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM]
  383. if exclude_click:
  384. options = [option for option in options if option not in exclude_click]
  385. target = random.choice(options)
  386. if click_now:
  387. self.click(target, interval=1.8)
  388. return target
  389. if __name__ == '__main__':
  390. from module.config.config import Config
  391. from module.device.device import Device
  392. c = Config('oas1')
  393. d = Device(c)
  394. t = ScriptTask(c, d)
  395. t.run()