script_task.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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=1)
  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_click(self.I_TO_BATTLE_MAIN, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  160. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  161. self.switch_climb_mode_in_game('pass')
  162. ocr_limit_timer = Timer(1).start()
  163. click_limit_timer = Timer(4).start()
  164. while 1:
  165. self.screenshot()
  166. self.put_status()
  167. # --------------------------------------------------------------
  168. if (self.appear_then_click(self.I_UI_CONFIRM, interval=0.5)
  169. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=0.5)):
  170. continue
  171. if self.ui_reward_appear_click():
  172. continue
  173. # 击败魇兽将直接前往下一层
  174. # if self.appear(self.I_PASS12):
  175. # logger.info('Found魇兽将')
  176. # from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as GBC1
  177. # _battle_config = GBC1(lock_team_enable=True)
  178. # _battle_config.lock_team_enable = True
  179. # self.ui_click(self.I_PASS12, stop=self.I_PASS_13)
  180. # self.ui_click_until_disappear(self.I_PASS_13, interval=1)
  181. # self.run_general_battle(config=_battle_config)
  182. # continue
  183. # 领箱子
  184. # if self.appear_then_click(self.I_PASS_5):
  185. # logger.info('Found箱子')
  186. # continue
  187. # 印记
  188. # if self.appear(self.I_PASS_6):
  189. # logger.info('Found印记')
  190. # click_index = 0
  191. # clicks = [self.I_PASS_8, self.I_PASS_10, self.I_PASS_11]
  192. # self.ui_click(self.I_PASS_6, stop=self.I_UI_BACK_RED, interval=1)
  193. # self.screenshot()
  194. # if not self.appear(self.I_UI_BACK_RED):
  195. # continue
  196. # while 1:
  197. # self.screenshot()
  198. # if self.ui_reward_appear_click():
  199. # break
  200. # if not self.appear(self.I_UI_BACK_RED):
  201. # break
  202. # # 按照顺序 间隔点击
  203. # if self.click(clicks[click_index], interval=1):
  204. # sleep(1.6)
  205. # click_index += 1
  206. # click_index = click_index % len(clicks)
  207. # if self.appear_then_click(self.I_PASS_9, interval=1.1):
  208. # logger.info('Select one done')
  209. # continue
  210. # 下一层
  211. # if self.appear_then_click(self.I_PASS_7, interval=1, threshold=0.65):
  212. # logger.info('Next layer')
  213. # continue
  214. if click_limit_timer.reached():
  215. click_limit_timer.reset()
  216. if (self.appear_then_click(self.I_PASS_1)
  217. or self.appear_then_click(self.I_PASS_2)
  218. or self.appear_then_click(self.I_PASS_3)
  219. or self.appear_then_click(self.I_PASS_4)):
  220. continue
  221. if not ocr_limit_timer.reached():
  222. continue
  223. ocr_limit_timer.reset()
  224. if not self.ocr_appear(self.O_FIRE):
  225. continue
  226. # --------------------------------------------------------------
  227. self.lock_team(self.conf.general_battle)
  228. if not self.check_tickets_enough():
  229. logger.warning(f'No tickets left, wait for next time')
  230. break
  231. if self.conf.general_climb.random_sleep:
  232. random_sleep(probability=0.2)
  233. if self.start_battle():
  234. continue
  235. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
  236. def _run_ap(self):
  237. """
  238. 更新前请先看 ./README.md
  239. """
  240. logger.hr(f'Start run climb type AP')
  241. self.ui_click(self.I_TO_BATTLE_MAIN, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
  242. self.switch_soul(self.I_BATTLE_MAIN_TO_RECORDS, self.I_CHECK_BATTLE_MAIN)
  243. self.switch_climb_mode_in_game('ap')
  244. ocr_limit_timer = Timer(1).start()
  245. while 1:
  246. self.screenshot()
  247. self.put_status()
  248. # --------------------------------------------------------------
  249. if not ocr_limit_timer.reached():
  250. continue
  251. ocr_limit_timer.reset()
  252. if not self.ocr_appear(self.O_FIRE):
  253. self.appear_then_click(self.I_CHECK_BATTLE_MAIN, interval=4)
  254. continue
  255. # --------------------------------------------------------------
  256. self.lock_team(self.conf.general_battle)
  257. if not self.check_tickets_enough():
  258. logger.warning(f'No tickets left, wait for next time')
  259. break
  260. if self.conf.general_climb.random_sleep:
  261. random_sleep(probability=0.2)
  262. if self.start_battle():
  263. continue
  264. self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
  265. def _run_boss(self):
  266. """
  267. 更新前请先看 ./README.md
  268. """
  269. logger.hr(f'Start run climb type BOSS')
  270. def start_battle(self):
  271. click_times, max_times = 0, random.randint(2, 4)
  272. while 1:
  273. self.screenshot()
  274. if self.is_in_battle(False):
  275. break
  276. if click_times >= max_times:
  277. logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
  278. return
  279. if (self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
  280. self.appear_then_click(self.I_UI_CONFIRM, interval=1) ):
  281. continue
  282. if self.ocr_appear_click(self.O_FIRE, interval=2):
  283. click_times += 1
  284. logger.info(f'Try click fire, remain times[{max_times - click_times}]')
  285. continue
  286. # 运行战斗
  287. self.run_general_battle(config=self.get_general_battle_conf())
  288. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  289. # 通用战斗结束判断
  290. self.device.stuck_record_add("BATTLE_STATUS_S")
  291. self.device.click_record_clear()
  292. logger.info(f"Start {self.climb_type} battle process")
  293. self.count_map[self.climb_type] = self.current_count
  294. for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
  295. btn.name = "BATTLE_RANDOM"
  296. ok_cnt, max_retry = 0, 5
  297. single_start_time = datetime.now()
  298. while 1:
  299. sleep(random.uniform(0.5, 1.5))
  300. self.screenshot()
  301. # 达到最大重试次数则直接交给上层处理
  302. if ok_cnt > max_retry:
  303. break
  304. # 识别到挑战说明已经退出战斗
  305. if ok_cnt > 0 and self.ocr_appear(self.O_FIRE):
  306. return True
  307. # 战斗失败
  308. if self.appear(self.I_FALSE):
  309. logger.warning("Battle failed")
  310. self.ui_click_until_smt_disappear(self.random_reward_click(click_now=False), self.I_FALSE, interval=1.5)
  311. return False
  312. # 战斗成功
  313. if self.appear_then_click(self.I_WIN, interval=2):
  314. continue
  315. # 出现 “魂” 和 紫蛇皮
  316. if self.appear(self.I_REWARD):
  317. logger.info('Win battle')
  318. while 1:
  319. self.screenshot()
  320. appear_reward = self.appear_then_click(self.I_REWARD)
  321. appear_reward_purple_snake_skin = self.appear(self.I_REWARD_PURPLE_SNAKE_SKIN)
  322. if not appear_reward and not appear_reward_purple_snake_skin:
  323. break
  324. if appear_reward or appear_reward_purple_snake_skin:
  325. reward_click = random.choice(
  326. [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP])
  327. self.click(reward_click, interval=1.8)
  328. continue
  329. return True
  330. # 已经不在战斗中了, 且奖励也识别过了, 则随机点击
  331. # if ok_cnt > 0 and not self.is_in_battle(False):
  332. # self.random_reward_click(exclude_click=[self.C_RANDOM_BOTTOM])
  333. # ok_cnt += 1
  334. # continue
  335. # # 单局到时间自动退出战斗
  336. # if ok_cnt == 0 and datetime.now() - single_start_time > self.conf.general_climb.get_single_limit_time(
  337. # self.climb_type, timedelta(days=1)):
  338. # logger.attr(self.climb_type, 'Time limit arrived, close current battle')
  339. # self.exit_battle(skip_first=True)
  340. # ok_cnt += 1
  341. # continue
  342. # 战斗中随机滑动
  343. if ok_cnt == 0 and random_click_swipt_enable:
  344. self.random_click_swipt()
  345. return True
  346. def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
  347. conf = self.conf.switch_soul_config
  348. conf.validate_switch_soul()
  349. enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
  350. enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
  351. if not enable_switch and not enable_by_name:
  352. return
  353. self.ui_click(enter_button, stop=self.I_CHECK_RECORDS, interval=1)
  354. if enable_by_name:
  355. group, team = getattr(conf, f"{self.climb_type}_group_team_name").split(",")
  356. self.run_switch_soul_by_name(group, team)
  357. elif enable_switch:
  358. group_team = getattr(conf, f"{self.climb_type}_group_team")
  359. self.run_switch_soul(group_team)
  360. self.ui_click(self.I_UI_BACK_YELLOW, stop=cur_img, interval=1)
  361. def switch_climb_mode_in_game(self, mode: str = 'ap'):
  362. map_check = {
  363. 'ap': self.I_CLIMB_MODE_AP,
  364. 'pass': self.I_CLIMB_MODE_PASS,
  365. }
  366. logger.info(f'Switch climb mode to {mode}')
  367. self.ui_click(self.I_CLIMB_MODE_SWITCH, stop=map_check[mode], interval=1)
  368. def lock_team(self, battle_conf: GeneralBattleConfig):
  369. """
  370. 根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
  371. """
  372. enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
  373. if not enable_preset:
  374. logger.info(f'Lock {self.climb_type} team')
  375. self.ui_click(self.I_UNLOCK, stop=self.I_LOCK, interval=1)
  376. return
  377. logger.info(f'Unlock {self.climb_type} team')
  378. self.ui_click(self.I_LOCK, stop=self.I_UNLOCK, interval=1)
  379. def check_tickets_enough(self) -> bool:
  380. """
  381. 判断当前爬塔门票是否足够
  382. :return: True 可以运行 or False
  383. """
  384. logger.hr(f'Check {self.climb_type} tickets')
  385. if not self.wait_until_appear(self.O_FIRE, wait_time=3):
  386. logger.warning(f'Detect fire fail, try reidentify')
  387. return False
  388. self.screenshot()
  389. remain_times = 0
  390. if self.climb_type == 'pass':
  391. remain_times = self.O_REMAIN_PASS.ocr_digit(
  392. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_PASS))
  393. if self.climb_type == 'ap':
  394. remain_times = self.O_REMAIN_AP.ocr_digit(
  395. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP))
  396. if self.climb_type == 'boss':
  397. _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
  398. if self.climb_type == 'ap100':
  399. remain_times = self.O_REMAIN_AP100.ocr_digit(
  400. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP100))
  401. return remain_times > 0
  402. def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
  403. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
  404. self.conf.validate_switch_preset()
  405. enable_preset = getattr(self.conf.general_battle, f'enable_{self.climb_type}_preset', False)
  406. group, team = getattr(self.conf.switch_soul_config, f'{self.climb_type}_group_team').split(',')
  407. return gbc(lock_team_enable=not enable_preset,
  408. preset_enable=enable_preset,
  409. preset_group=group if enable_preset else 1,
  410. preset_team=team if enable_preset else 1,
  411. green_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_green', False),
  412. green_mark=getattr(self.conf.general_battle, f'{self.climb_type}_green_mark'),
  413. random_click_swipt_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_anti_detect',
  414. False), )
  415. def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
  416. """
  417. 随机点击
  418. :param exclude_click: 排除的点击位置
  419. :param click_now: 是否立即点击
  420. :return: 随机的点击位置
  421. """
  422. options = [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM]
  423. if exclude_click:
  424. options = [option for option in options if option not in exclude_click]
  425. target = random.choice(options)
  426. if click_now:
  427. self.click(target, interval=1.8)
  428. return target
  429. if __name__ == '__main__':
  430. from module.config.config import Config
  431. from module.device.device import Device
  432. c = Config('oas1')
  433. d = Device(c)
  434. t = ScriptTask(c, d)
  435. t.run()