script_task.py 18 KB

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