script_task.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from time import sleep
  5. import cv2
  6. import numpy as np
  7. import random
  8. import tasks.Component.GeneralBattle.config_general_battle
  9. from datetime import datetime, timedelta, time
  10. from module.atom.ocr import RuleOcr
  11. from module.base.protect import random_sleep
  12. from module.exception import TaskEnd
  13. from module.logger import logger
  14. from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
  15. from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig
  16. from tasks.Component.BaseActivity.base_activity import BaseActivity
  17. from tasks.Component.BaseActivity.config_activity import GeneralClimb
  18. from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
  19. from tasks.GameUi.game_ui import GameUi
  20. from tasks.GameUi.page import page_main, page_shikigami_records, page_climb_act, page_climb_act_pass, \
  21. page_climb_act_boss, page_climb_act_ap, Page, page_climb_act_buff
  22. def get_run_order_list(climb_conf: GeneralClimb) -> list[str]:
  23. if climb_conf.run_sequence is None or climb_conf.run_sequence == '':
  24. raise ValueError('Run sequence now is empty, must set it')
  25. run_order_list = [climb_type.strip() for climb_type in climb_conf.run_sequence.split(',')]
  26. return [climb_type for climb_type in run_order_list if getattr(climb_conf, f'enable_{climb_type}')]
  27. def _prepare_image_for_ocr(image: np.ndarray, asset: RuleOcr) -> np.ndarray:
  28. image_copy = image.copy()
  29. x, y, w, h = asset.roi
  30. roi_to_process = image_copy[y:y + h, x:x + w]
  31. if len(roi_to_process.shape) == 3:
  32. gray_image = cv2.cvtColor(roi_to_process, cv2.COLOR_BGR2GRAY)
  33. else:
  34. gray_image = roi_to_process
  35. # 自适应二值化
  36. _, binary_norm = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  37. _, binary_inv = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
  38. if cv2.countNonZero(binary_norm) < cv2.countNonZero(binary_inv):
  39. binary_correct = binary_norm
  40. else:
  41. binary_correct = binary_inv
  42. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 1))
  43. dilated_image = cv2.dilate(binary_correct, kernel, iterations=1)
  44. # 找轮廓
  45. contours, _ = cv2.findContours(dilated_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  46. processed_roi_content = None
  47. if contours:
  48. all_points = np.concatenate(contours, axis=0)
  49. bx, by, bw, bh = cv2.boundingRect(all_points)
  50. processed_roi_content = binary_correct[by:by + bh, bx:bx + bw]
  51. centered_roi = np.full((h, w), 255, dtype=np.uint8) # 255代表白色
  52. if processed_roi_content is not None:
  53. content_h, content_w = processed_roi_content.shape
  54. if content_h <= h and content_w <= w:
  55. # 计算居中粘贴的位置,放到中间
  56. start_y = (h - content_h) // 2
  57. start_x = (w - content_w) // 2
  58. paste_area = centered_roi[start_y:start_y + content_h, start_x:start_x + content_w]
  59. paste_area[processed_roi_content == 255] = 0
  60. else:
  61. logger.warning(f"Content for asset '{asset.name}' is larger than ROI. Skipping centering.")
  62. # 内容过大,直接使用原始二值图的反转作为结果
  63. centered_roi = cv2.bitwise_not(binary_correct)
  64. else:
  65. logger.warning(f"No content found in ROI for asset: {asset.name}. ROI will be blank.")
  66. processed_roi_bgr = cv2.cvtColor(centered_roi, cv2.COLOR_GRAY2BGR)
  67. image_copy[y:y + h, x:x + w] = processed_roi_bgr
  68. return image_copy
  69. class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
  70. # key: climb type value: run count
  71. count_map: dict[str, int] = {
  72. 'pass': 0,
  73. 'ap': 0,
  74. 'boss': 0
  75. }
  76. page_map: dict[str, Page] = {
  77. 'pass': page_climb_act_pass,
  78. 'ap': page_climb_act_ap,
  79. 'boss': page_climb_act_boss,
  80. }
  81. climb_type: str = 'pass'
  82. run_idx: int = 0
  83. def run(self) -> None:
  84. config = self.config.activity_shikigami
  85. self.limit_time: timedelta = config.general_climb.limit_time
  86. if isinstance(self.limit_time, time):
  87. self.limit_time = timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
  88. seconds=self.limit_time.second)
  89. # 初始化爬塔类型
  90. self.climb_type = get_run_order_list(config.general_climb)[0]
  91. while 1:
  92. # 切换御魂
  93. self.switch_soul(config.switch_soul_config)
  94. # 进入爬塔活动主界面
  95. self.home_main()
  96. # 切换buff
  97. self.switch_buff(config.general_climb)
  98. # 锁定阵容
  99. self.lock_team(config.general_battle)
  100. while 1:
  101. switch = False
  102. # 超时退出
  103. if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
  104. logger.info(f"{self.climb_type} time out")
  105. break
  106. # 次数达到限制切换下一种爬塔
  107. if self.get_count() >= self.get_limit(config.general_climb):
  108. logger.warn(f"{self.climb_type} count out, switch to next")
  109. switch = self.switch_next()
  110. break
  111. # 判断是否可以运行
  112. can_run = self.check_can_run()
  113. if not can_run:
  114. logger.warn(f'{self.climb_type} tickets not enough, switch to next')
  115. switch = self.switch_next()
  116. break
  117. # 开始战斗
  118. self.start_battle()
  119. if not switch:
  120. break
  121. # 返回庭院
  122. self.main_home()
  123. if config.general_climb.active_souls_clean:
  124. self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
  125. self.set_next_run(task="ActivityShikigami", success=True)
  126. raise TaskEnd
  127. def switch_soul(self, conf: SwitchSoulConfig):
  128. """
  129. 根据当前爬塔类型自动切换御魂
  130. :param conf: 切换御魂配置
  131. :return:
  132. """
  133. enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
  134. enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
  135. if enable_switch or enable_by_name:
  136. self.ui_get_current_page()
  137. self.ui_goto(page_shikigami_records)
  138. if enable_by_name:
  139. group, team = getattr(conf, f"{self.climb_type}_group_team_name", '-1,-1').split(",")
  140. self.run_switch_soul_by_name(group, team)
  141. elif enable_switch:
  142. group_team = getattr(conf, f"{self.climb_type}_group_team", '-1,-1')
  143. self.run_switch_soul(group_team)
  144. def lock_team(self, battle_conf: GeneralBattleConfig):
  145. """
  146. 根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
  147. :param battle_conf: 战斗配置
  148. :return:
  149. """
  150. self.ui_get_current_page()
  151. self.ui_goto(self.page_map[self.climb_type])
  152. enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
  153. if not enable_preset:
  154. logger.info(f'Lock {self.climb_type} team')
  155. while 1:
  156. self.screenshot()
  157. if self.appear_then_click(self.I_UNLOCK, interval=1):
  158. continue
  159. if self.appear(self.I_LOCK):
  160. return
  161. logger.info(f'Unlock {self.climb_type} team')
  162. while 1:
  163. self.screenshot()
  164. if self.appear_then_click(self.I_LOCK, interval=1):
  165. continue
  166. if self.appear(self.I_UNLOCK):
  167. break
  168. def switch_buff(self, climb_conf: GeneralClimb):
  169. buffs = getattr(climb_conf, f'{self.climb_type}_buff', None)
  170. if not buffs:
  171. logger.info('Not set buff, skip')
  172. return
  173. buff_list = [buff.strip() for buff in buffs.split(',')]
  174. if not buff_list:
  175. logger.info('Buff incorrect formatting, skip')
  176. return
  177. self.ui_get_current_page()
  178. self.ui_goto(page_climb_act_buff)
  179. buff_box_list = [self.C_BUFF_1_BOX, self.C_BUFF_2_BOX]
  180. buff_box_empty_list = [self.I_BUFF_BOX_1_EMPTY, self.I_BUFF_BOX_2_EMPTY]
  181. buff_up_map = {
  182. 'buff_1': self.C_BUFF_1_UP,
  183. 'buff_2': self.C_BUFF_2_UP,
  184. 'buff_3': self.C_BUFF_3_UP,
  185. 'buff_4': self.C_BUFF_4_UP,
  186. 'buff_5': self.C_BUFF_5_UP
  187. }
  188. logger.info(f'start switch {self.climb_type} {buff_list}')
  189. for i, buff_box in enumerate(buff_box_list):
  190. logger.info(f'Start down {buff_list[i]}')
  191. ok = 0
  192. while ok <= 3:
  193. self.screenshot()
  194. # 打开buff面板
  195. self.click(buff_box, interval=1.5)
  196. ok = (ok + 1) if self.appear(buff_box_empty_list[i]) else 0
  197. # 卸下buff
  198. self.appear_then_click(self.I_BUFF_DOWN, interval=0.5)
  199. logger.info(f'Down {buff_list[i]} ok')
  200. for i, buff_box in enumerate(buff_box_list):
  201. logger.info(f'Start up {buff_list[i]}')
  202. ok = 0
  203. while ok <= 3:
  204. self.screenshot()
  205. # 打开buff面板
  206. self.click(buff_box, interval=1.5)
  207. ok = (ok + 1) if not self.appear(buff_box_empty_list[i]) else 0
  208. # 装上buff
  209. self.appear_then_click(self.I_BUFF_UP, buff_up_map[buff_list[i]], interval=0.5)
  210. logger.info(f'Up {buff_list[i]} ok')
  211. def get_count(self) -> int:
  212. """
  213. 获取当前爬塔类型运行次数
  214. :return: 运行次数
  215. """
  216. return self.count_map[self.climb_type]
  217. def check_can_run(self) -> bool:
  218. """
  219. 判断当前爬塔类型能否运行
  220. pass: 剩余门票爬塔票数>0
  221. ap: 剩余体力爬塔票数>0
  222. boss: 剩余挑战次数>0
  223. :return: True 可以运行 or False
  224. """
  225. self.ui_get_current_page()
  226. self.ui_goto(self.page_map[self.climb_type])
  227. logger.info(f'Check the {self.climb_type} can work')
  228. self.wait_until_appear(self.I_FIRE)
  229. self.screenshot()
  230. remain_times = 0
  231. if self.climb_type == 'pass':
  232. remain_times = self.O_REMAIN_AP_ACTIVITY2.ocr_digit(
  233. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP_ACTIVITY2))
  234. if self.climb_type == 'ap':
  235. remain_times = self.O_REMAIN_AP.ocr_digit(
  236. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP))
  237. if self.climb_type == 'boss':
  238. _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
  239. return remain_times > 0
  240. def get_limit(self, climb_conf: GeneralClimb) -> int:
  241. """
  242. 获取配置中当前爬塔类型次数限制
  243. :param climb_conf: 爬塔配置
  244. :return: 限制次数
  245. """
  246. return getattr(climb_conf, f'{self.climb_type}_limit', 0)
  247. def switch_next(self) -> bool:
  248. """
  249. 切换下一种爬塔类型
  250. :return: True 切换成功 or False
  251. """
  252. self.run_idx += 1
  253. climb_type_list = get_run_order_list(self.config.activity_shikigami.general_climb)
  254. if self.run_idx >= len(climb_type_list):
  255. logger.info('All tower climbing activities have been completed')
  256. return False
  257. self.climb_type = climb_type_list[self.run_idx]
  258. self.current_count = 0
  259. return True
  260. def start_battle(self):
  261. # 点击战斗前随机休息
  262. if self.config.activity_shikigami.general_climb.random_sleep:
  263. random_sleep(probability=0.2)
  264. logger.info("Click battle")
  265. while 1:
  266. self.screenshot()
  267. # 点击挑战
  268. if self.appear_then_click(self.I_FIRE, interval=2):
  269. continue
  270. if not self.appear(self.I_FIRE):
  271. break
  272. if self.appear_then_click(self.I_C_CONFIRM1, interval=0.6):
  273. continue
  274. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  275. continue
  276. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  277. continue
  278. if self.appear_then_click(self.I_N_CONFIRM, interval=1):
  279. continue
  280. # 运行战斗
  281. if self.run_general_battle(config=self.get_general_battle_conf()):
  282. self.count_map[self.climb_type] += 1
  283. logger.info("General battle success")
  284. def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
  285. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
  286. conf = self.config.activity_shikigami
  287. enable_preset = getattr(conf.general_battle, f'enable_{self.climb_type}_preset', False)
  288. group, team = getattr(conf.switch_soul_config, f'{self.climb_type}_group_team', '1,1').split(',')
  289. return gbc(lock_team_enable=not enable_preset,
  290. preset_enable=enable_preset,
  291. preset_group=group if enable_preset else 1,
  292. preset_team=team if enable_preset else 1,
  293. green_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_green', False),
  294. green_mark=getattr(conf.general_battle, f'{self.climb_type}_green_mark'),
  295. random_click_swipt_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_anti_detect', False), )
  296. def home_main(self) -> bool:
  297. """
  298. 从庭院到活动的爬塔界面,(只到爬塔活动主界面)
  299. :return:
  300. """
  301. logger.hr("Enter Shikigami", 2)
  302. self.ui_get_current_page()
  303. self.main_goto_act_by_list(page_climb_act)
  304. def main_home(self) -> bool:
  305. """
  306. 从活动的爬塔界面到庭院
  307. :return:
  308. """
  309. logger.hr("Exit Shikigami", 2)
  310. self.ui_get_current_page()
  311. self.ui_goto(page_main)
  312. def random_reward_click(self, exclude_bottom=False):
  313. options = [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP]
  314. if not exclude_bottom:
  315. options.append(self.C_RANDOM_BOTTOM)
  316. target = random.choice(options)
  317. self.click(target, interval=1.8)
  318. return 1
  319. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  320. # 通用战斗结束判断
  321. self.device.stuck_record_add("BATTLE_STATUS_S")
  322. self.device.click_record_clear()
  323. logger.info("Start battle process")
  324. for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
  325. btn.name = "BATTLE_RANDOM"
  326. ok_cnt, max_retry = 0, 5
  327. while 1:
  328. self.screenshot()
  329. sleep(0.5)
  330. # 已经回到对应挑战界面
  331. if self.ui_page_appear(self.page_map[self.climb_type]):
  332. break
  333. # 达到最大重试次数且没有回到活动界面
  334. if ok_cnt > max_retry:
  335. self.click(self.random_reward_click(exclude_bottom=True), interval=1)
  336. break
  337. # 已经胜利但是后续识别失败则重新识别并点击
  338. if 0 < ok_cnt <= max_retry:
  339. # 紫蛇皮消失
  340. self.ui_click_until_smt_disappear(self.random_reward_click(exclude_bottom=True),
  341. self.I_REWARD_PURPLE_SNAKE_SKIN, interval=1.6)
  342. self.ui_get_current_page()
  343. self.ui_goto(self.page_map[self.climb_type])
  344. ok_cnt += 1
  345. continue
  346. # 胜利(鼓 | 魂 | 获得奖励)
  347. if self.appear(self.I_WIN) or self.appear(self.I_REWARD) or self.appear(self.I_UI_REWARD):
  348. if ok_cnt == 0:
  349. logger.info("Win battle")
  350. # 鼓消失
  351. self.ui_click_until_smt_disappear(self.random_reward_click(), self.I_WIN, interval=1.1)
  352. # 魂消失
  353. self.ui_click_until_smt_disappear(self.random_reward_click(exclude_bottom=True), self.I_REWARD,
  354. interval=1.3)
  355. # 紫蛇皮消失
  356. self.ui_click_until_smt_disappear(self.random_reward_click(exclude_bottom=True),
  357. self.I_REWARD_PURPLE_SNAKE_SKIN, interval=1.6)
  358. # 获得奖励消失
  359. self.ui_click_until_smt_disappear(self.random_reward_click(),
  360. self.I_UI_REWARD, interval=1.6)
  361. ok_cnt += 1
  362. continue
  363. # 失败
  364. if self.appear(self.I_FALSE):
  365. logger.warning("False battle")
  366. self.ui_click_until_smt_disappear(self.random_reward_click(), self.I_FALSE, interval=1.5)
  367. return False
  368. # 战斗中随机滑动
  369. if random_click_swipt_enable:
  370. self.random_click_swipt()
  371. return True
  372. if __name__ == '__main__':
  373. from module.config.config import Config
  374. from module.device.device import Device
  375. c = Config('oas3')
  376. d = Device(c)
  377. t = ScriptTask(c, d)
  378. t.switch_buff(c.activity_shikigami.general_climb)