script_task.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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, battle_wait_options
  21. from tasks.Component.GeneralBattle.battle import Battle
  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. # 切换爬塔类型, count_map 按类型独立统计无需重置;但战斗框架状态需要清掉上一类型的残留
  123. self.battle_state_reset()
  124. logger.hr(f'Climb switch to {self.climb_type}', 2)
  125. return True
  126. class ScriptTask(StateMachine, GameUi, Battle, 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.goto_page(game.page_climb_act)
  136. try:
  137. method_func = getattr(self, f'_run_{climb_type}')
  138. method_func()
  139. except LimitCountOut as e:
  140. while 1:
  141. self.screenshot()
  142. if self.appear(self.I_TO_BATTLE_MAIN):
  143. break
  144. if self.appear_then_click(self.I_UI_BACK_CIRCLE, interval=1.5):
  145. continue
  146. if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=2.5):
  147. continue
  148. if self.appear_then_click(self.I_UI_BACK_RED, interval=1.5):
  149. continue
  150. except LimitTimeOut as e:
  151. break
  152. finally:
  153. # 切换下一个爬塔类型
  154. self.switch_next()
  155. # 返回庭院
  156. logger.hr("Exit Shikigami", 2)
  157. self.goto_page(game.page_main)
  158. if self.conf.general_climb.active_souls_clean:
  159. self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
  160. self.set_next_run(task="ActivityShikigami", success=True)
  161. raise TaskEnd
  162. def _run_pass(self):
  163. """
  164. 更新前请先看 ./README.md
  165. """
  166. logger.hr(f'Start run climb type PASS', 1)
  167. # self.ui_clicks([self.I_TO_BATTLE_MAIN_2],
  168. # stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  169. #
  170. while 1:
  171. self.screenshot()
  172. if self.appear(self.I_UI_BACK_RED) and self.appear(self.I_PASS_4):
  173. break
  174. if self.appear_then_click(self.I_UI_CONFIRM, interval=0.5):
  175. continue
  176. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5):
  177. continue
  178. if self.appear_then_click(self.I_TO_BATTLE_MAIN_2, interval=1.5):
  179. continue
  180. if not self.appear(self.I_PASS_3):
  181. continue
  182. if self.appear_then_click(self.I_PASS_1, interval=1.5):
  183. continue
  184. if self.appear_then_click(self.I_PASS_2, interval=1.5):
  185. continue
  186. logger.info('Enter occupation reward screen') # 进入到占领奖励
  187. index = 0
  188. clicks = [self.I_PASS_5, self.I_PASS_6, self.I_PASS_7, self.I_PASS_8, self.I_PASS_9]
  189. while 1:
  190. self.screenshot()
  191. if self.appear(self.I_CHECK_BATTLE_MAIN):
  192. break
  193. if self.click(clicks[index], interval=1.5):
  194. sleep(1)
  195. index = (index + 1) % len(clicks)
  196. logger.info('Enter challenge screen') # 正式进入挑战界面
  197. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  198. # self.switch_climb_mode_in_game('pass')
  199. ocr_limit_timer = Timer(1).start()
  200. click_limit_timer = Timer(4).start()
  201. while 1:
  202. self.screenshot()
  203. self.put_status()
  204. # --------------------------------------------------------------
  205. if (self.appear_then_click(self.I_UI_CONFIRM, interval=0.5)
  206. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5)):
  207. continue
  208. if self.ui_reward_appear_click():
  209. continue
  210. if not ocr_limit_timer.reached():
  211. continue
  212. ocr_limit_timer.reset()
  213. if not self.ocr_appear(self.O_FIRE):
  214. continue
  215. # --------------------------------------------------------------
  216. self.lock_team(self.conf.general_battle)
  217. if not self.check_tickets_enough():
  218. logger.warning(f'No tickets left, wait for next time')
  219. break
  220. if self.conf.general_climb.random_sleep:
  221. random_sleep(probability=0.2)
  222. if self.start_battle():
  223. continue
  224. # self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=4.5)
  225. while 1:
  226. self.screenshot()
  227. if self.appear(self.I_TO_BATTLE_MAIN):
  228. break
  229. if self.appear(self.I_CHECK_BATTLE_MAIN) and self.appear_then_click(self.I_UI_BACK_YELLOW, interval=2.5):
  230. continue
  231. def _run_ap(self):
  232. """
  233. 更新前请先看 ./README.md
  234. """
  235. logger.hr(f'Start run climb type AP')
  236. self.ui_clicks([self.I_TO_BATTLE_MAIN],
  237. stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  238. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  239. # self.switch_climb_mode_in_game('ap')
  240. ocr_limit_timer = Timer(1).start()
  241. while 1:
  242. self.screenshot()
  243. self.put_status()
  244. # --------------------------------------------------------------
  245. if not ocr_limit_timer.reached():
  246. continue
  247. ocr_limit_timer.reset()
  248. if not self.ocr_appear(self.O_FIRE):
  249. self.appear_then_click(self.I_CHECK_BATTLE_MAIN, interval=4)
  250. continue
  251. # --------------------------------------------------------------
  252. self.lock_team(self.conf.general_battle)
  253. if not self.check_tickets_enough():
  254. logger.warning(f'No tickets left, wait for next time')
  255. break
  256. if self.conf.general_climb.random_sleep:
  257. random_sleep(probability=0.2)
  258. if self.start_battle():
  259. continue
  260. # self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=3.5, timeout=10)
  261. while 1:
  262. self.screenshot()
  263. if self.appear(self.I_TO_BATTLE_MAIN):
  264. break
  265. if self.appear_then_click(self.I_UI_BACK_CIRCLE, interval=1.5):
  266. continue
  267. if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=2.5):
  268. continue
  269. if self.appear_then_click(self.I_UI_BACK_RED, interval=1.5):
  270. continue
  271. def _run_boss(self):
  272. """
  273. 更新前请先看 ./README.md
  274. """
  275. logger.hr(f'Start run climb type BOSS')
  276. self.ui_clicks([self.I_TO_BATTLE_BOSS],
  277. stop=self.I_CHECK_BATTLE_BOSS, interval=1)
  278. while 1:
  279. self.screenshot()
  280. self.put_status()
  281. # --------------------------------------------------------------
  282. if not self.ocr_appear(self.O_FIRE):
  283. self.appear_then_click(self.I_CHECK_BATTLE_BOSS, interval=4)
  284. continue
  285. if self.conf.general_climb.random_sleep:
  286. random_sleep(probability=0.2)
  287. if self.start_battle():
  288. continue
  289. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_BOSS, interval=4.5)
  290. def _run_ap100(self):
  291. """
  292. 更新前请先看 ./README.md
  293. """
  294. logger.hr(f'Start run climb type AP100')
  295. def start_battle(self):
  296. click_times, max_times = 0, random.randint(4, 8)
  297. while 1:
  298. self.screenshot()
  299. if self.is_in_battle(False):
  300. break
  301. if click_times >= max_times:
  302. logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
  303. return
  304. if (self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
  305. self.appear_then_click(self.I_UI_CONFIRM, interval=1) ):
  306. continue
  307. if (self.appear(self.I_CHECK_BATTLE_MAIN, interval=1) or self.appear(self.I_CHECK_BATTLE_BOSS, interval=1)) \
  308. and self.ocr_appear_click(self.O_FIRE, interval=2):
  309. click_times += 1
  310. logger.info(f'Try click fire, remain times[{max_times - click_times}]')
  311. continue
  312. # 运行战斗
  313. strategies, options = self.loadout_from_config(self.get_general_battle_conf())
  314. # strategies['success'] = 'activity'
  315. self.loadout_show((strategies, options))
  316. self.state_show()
  317. with battle_wait_strategy(**strategies), battle_wait_options(**options):
  318. win = self.battle_wait()
  319. # 对齐历史语义: 战斗成功结束后记为一次
  320. if win:
  321. self.count_map[self.climb_type] += 1
  322. logger.info(f'Count {self.climb_type}: {self.count_map[self.climb_type]}')
  323. return win
  324. def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
  325. conf = self.conf.switch_soul_config
  326. enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
  327. enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
  328. if not enable_switch and not enable_by_name:
  329. return
  330. logger.hr('Start switch soul', 2)
  331. conf.validate_switch_soul()
  332. self.ui_click(enter_button, stop=self.I_CHECK_RECORDS, interval=1)
  333. if enable_by_name:
  334. group, team = getattr(conf, f"{self.climb_type}_group_team_name").split(",")
  335. self.run_switch_soul_by_name(group, team)
  336. elif enable_switch:
  337. group_team = getattr(conf, f"{self.climb_type}_group_team")
  338. self.run_switch_soul(group_team)
  339. self.ui_click(self.I_UI_BACK_YELLOW, stop=cur_img, interval=1)
  340. def switch_climb_mode_in_game(self, mode: str = 'ap'):
  341. map_check = {
  342. 'ap': self.I_CLIMB_MODE_AP,
  343. 'pass': self.I_CLIMB_MODE_PASS,
  344. }
  345. logger.info(f'Switch climb mode to {mode}')
  346. self.ui_click(self.I_CLIMB_MODE_SWITCH, stop=map_check[mode], interval=1.9)
  347. def lock_team(self, battle_conf: GeneralBattleConfig):
  348. """
  349. 根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
  350. """
  351. enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
  352. if not enable_preset:
  353. logger.info(f'Lock {self.climb_type} team')
  354. self.ui_click(self.I_UNLOCK, stop=self.I_LOCK, interval=1.5)
  355. return
  356. logger.info(f'Unlock {self.climb_type} team')
  357. self.ui_click(self.I_LOCK, stop=self.I_UNLOCK, interval=1.5)
  358. def check_tickets_enough(self) -> bool:
  359. """
  360. 判断当前爬塔门票是否足够
  361. :return: True 可以运行 or False
  362. """
  363. logger.hr(f'Check {self.climb_type} tickets')
  364. if not self.wait_until_appear(self.O_FIRE, wait_time=3):
  365. logger.warning(f'Detect fire fail, try reidentify')
  366. return False
  367. self.screenshot()
  368. remain_times = 0
  369. if self.climb_type == 'pass':
  370. remain_times = self.O_REMAIN_PASS.ocr_digit(self.device.image)
  371. if self.climb_type == 'ap':
  372. remain_times = self.O_REMAIN_AP.ocr_digit(self.device.image)
  373. if self.climb_type == 'boss':
  374. _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
  375. if self.climb_type == 'ap100':
  376. remain_times = self.O_REMAIN_AP100.ocr_digit(self.device.image)
  377. return remain_times > 0
  378. def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
  379. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
  380. self.conf.validate_switch_preset()
  381. enable_preset = getattr(self.conf.general_battle, f'enable_{self.climb_type}_preset', False)
  382. group, team = getattr(self.conf.switch_soul_config, f'{self.climb_type}_group_team').split(',')
  383. return gbc(lock_team_enable=not enable_preset,
  384. preset_enable=enable_preset,
  385. preset_group=group if enable_preset else 1,
  386. preset_team=team if enable_preset else 1,
  387. green_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_green', False),
  388. green_mark=getattr(self.conf.general_battle, f'{self.climb_type}_green_mark'),
  389. random_click_swipt_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_anti_detect',
  390. False), )
  391. def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
  392. """
  393. 随机点击
  394. :param exclude_click: 排除的点击位置
  395. :param click_now: 是否立即点击
  396. :return: 随机的点击位置
  397. """
  398. options = [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM]
  399. if exclude_click:
  400. options = [option for option in options if option not in exclude_click]
  401. target = random.choice(options)
  402. if click_now:
  403. self.click(target, interval=1.8)
  404. return target
  405. if __name__ == '__main__':
  406. from module.config.config import Config
  407. from module.device.device import Device
  408. c = Config('oas1')
  409. d = Device(c)
  410. t = ScriptTask(c, d)
  411. t.run()