script_task.py 17 KB

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