script_task.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 not climb_conf.run_sequence or len(climb_conf.run_sequence.split(',')) == 1:
  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_name = getattr(conf, f"{self.climb_type}_group_team_name", '-1,-1')
  140. if not group_name or len(group_name.split(',')) != 2:
  141. raise ValueError('switch soul by name must be 2 length')
  142. group, team = group_name.split(",")
  143. self.run_switch_soul_by_name(group, team)
  144. elif enable_switch:
  145. group_team = getattr(conf, f"{self.climb_type}_group_team", '-1,-1')
  146. self.run_switch_soul(group_team)
  147. def lock_team(self, battle_conf: GeneralBattleConfig):
  148. """
  149. 根据配置判断当前爬塔类型是否锁定阵容, 并执行锁定或解锁
  150. :param battle_conf: 战斗配置
  151. :return:
  152. """
  153. self.ui_get_current_page()
  154. self.ui_goto(self.page_map[self.climb_type])
  155. enable_preset = getattr(battle_conf, f"enable_{self.climb_type}_preset", False)
  156. if not enable_preset:
  157. logger.info(f'Lock {self.climb_type} team')
  158. while 1:
  159. self.screenshot()
  160. if self.appear_then_click(self.I_UNLOCK, interval=1):
  161. continue
  162. if self.appear(self.I_LOCK):
  163. return
  164. logger.info(f'Unlock {self.climb_type} team')
  165. while 1:
  166. self.screenshot()
  167. if self.appear_then_click(self.I_LOCK, interval=1):
  168. continue
  169. if self.appear(self.I_UNLOCK):
  170. break
  171. def switch_buff(self, climb_conf: GeneralClimb):
  172. buffs = getattr(climb_conf, f'{self.climb_type}_buff', None)
  173. if not buffs or len(buffs.split(',')) == 1:
  174. logger.info('Not set buff, skip')
  175. return
  176. buff_list = [buff.strip() for buff in buffs.split(',')]
  177. if not buff_list:
  178. logger.info('Buff incorrect formatting, skip')
  179. return
  180. self.ui_get_current_page()
  181. self.ui_goto(page_climb_act_buff)
  182. buff_box_list = [self.C_BUFF_1_BOX, self.C_BUFF_2_BOX]
  183. buff_box_empty_list = [self.I_BUFF_BOX_1_EMPTY, self.I_BUFF_BOX_2_EMPTY]
  184. buff_up_map = {
  185. 'buff_1': self.C_BUFF_1_UP,
  186. 'buff_2': self.C_BUFF_2_UP,
  187. 'buff_3': self.C_BUFF_3_UP,
  188. 'buff_4': self.C_BUFF_4_UP,
  189. 'buff_5': self.C_BUFF_5_UP
  190. }
  191. logger.info(f'start switch {self.climb_type} {buff_list}')
  192. for i, buff_box in enumerate(buff_box_list):
  193. logger.info(f'Start down {buff_list[i]}')
  194. ok = 0
  195. while ok <= 3:
  196. self.screenshot()
  197. # 打开buff面板
  198. self.click(buff_box, interval=1.5)
  199. ok = (ok + 1) if self.appear(buff_box_empty_list[i]) else 0
  200. # 卸下buff
  201. self.appear_then_click(self.I_BUFF_DOWN, interval=0.5)
  202. logger.info(f'Down {buff_list[i]} ok')
  203. for i, buff_box in enumerate(buff_box_list):
  204. logger.info(f'Start up {buff_list[i]}')
  205. ok = 0
  206. while ok <= 3:
  207. self.screenshot()
  208. # 打开buff面板
  209. self.click(buff_box, interval=1.5)
  210. ok = (ok + 1) if not self.appear(buff_box_empty_list[i]) else 0
  211. # 装上buff
  212. self.appear_then_click(self.I_BUFF_UP, buff_up_map[buff_list[i]], interval=0.5)
  213. logger.info(f'Up {buff_list[i]} ok')
  214. def get_count(self) -> int:
  215. """
  216. 获取当前爬塔类型运行次数
  217. :return: 运行次数
  218. """
  219. return self.count_map[self.climb_type]
  220. def check_can_run(self) -> bool:
  221. """
  222. 判断当前爬塔类型能否运行
  223. pass: 剩余门票爬塔票数>0
  224. ap: 剩余体力爬塔票数>0
  225. boss: 剩余挑战次数>0
  226. :return: True 可以运行 or False
  227. """
  228. self.ui_get_current_page()
  229. self.ui_goto(self.page_map[self.climb_type])
  230. logger.info(f'Check the {self.climb_type} can work')
  231. self.wait_until_appear(self.I_FIRE)
  232. self.screenshot()
  233. remain_times = 0
  234. if self.climb_type == 'pass':
  235. remain_times = self.O_REMAIN_AP_ACTIVITY2.ocr_digit(
  236. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP_ACTIVITY2))
  237. if self.climb_type == 'ap':
  238. remain_times = self.O_REMAIN_AP.ocr_digit(
  239. _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP))
  240. if self.climb_type == 'boss':
  241. _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
  242. return remain_times > 0
  243. def get_limit(self, climb_conf: GeneralClimb) -> int:
  244. """
  245. 获取配置中当前爬塔类型次数限制
  246. :param climb_conf: 爬塔配置
  247. :return: 限制次数
  248. """
  249. limit = getattr(climb_conf, f'{self.climb_type}_limit', 0)
  250. return 0 if not limit else limit
  251. def switch_next(self) -> bool:
  252. """
  253. 切换下一种爬塔类型
  254. :return: True 切换成功 or False
  255. """
  256. self.run_idx += 1
  257. climb_type_list = get_run_order_list(self.config.activity_shikigami.general_climb)
  258. if self.run_idx >= len(climb_type_list):
  259. logger.info('All tower climbing activities have been completed')
  260. return False
  261. self.climb_type = climb_type_list[self.run_idx]
  262. self.current_count = 0
  263. return True
  264. def start_battle(self):
  265. # 点击战斗前随机休息
  266. if self.config.activity_shikigami.general_climb.random_sleep:
  267. random_sleep(probability=0.2)
  268. logger.info("Click battle")
  269. while 1:
  270. self.screenshot()
  271. # 点击挑战
  272. if self.appear_then_click(self.I_FIRE, interval=2):
  273. continue
  274. if not self.appear(self.I_FIRE):
  275. break
  276. if self.appear_then_click(self.I_C_CONFIRM1, interval=0.6):
  277. continue
  278. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  279. continue
  280. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  281. continue
  282. if self.appear_then_click(self.I_N_CONFIRM, interval=1):
  283. continue
  284. # 运行战斗
  285. if self.run_general_battle(config=self.get_general_battle_conf()):
  286. self.count_map[self.climb_type] += 1
  287. logger.info("General battle success")
  288. def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
  289. from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
  290. conf = self.config.activity_shikigami
  291. enable_preset = getattr(conf.general_battle, f'enable_{self.climb_type}_preset', False)
  292. group_team = getattr(conf.switch_soul_config, f'{self.climb_type}_group_team')
  293. if enable_preset and (not group_team or len(group_team.split(',')) != 2):
  294. raise ValueError('Enable preset but group team not set correct!')
  295. group, team = group_team.split(',')
  296. return gbc(lock_team_enable=not enable_preset,
  297. preset_enable=enable_preset,
  298. preset_group=group if enable_preset else 1,
  299. preset_team=team if enable_preset else 1,
  300. green_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_green', False),
  301. green_mark=getattr(conf.general_battle, f'{self.climb_type}_green_mark'),
  302. random_click_swipt_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_anti_detect', False), )
  303. def home_main(self) -> bool:
  304. """
  305. 从庭院到活动的爬塔界面,(只到爬塔活动主界面)
  306. :return:
  307. """
  308. logger.hr("Enter Shikigami", 2)
  309. self.ui_get_current_page()
  310. self.main_goto_act_by_list(page_climb_act)
  311. def main_home(self) -> bool:
  312. """
  313. 从活动的爬塔界面到庭院
  314. :return:
  315. """
  316. logger.hr("Exit Shikigami", 2)
  317. self.ui_get_current_page()
  318. self.ui_goto(page_main)
  319. def random_reward_click(self, exclude_bottom=False):
  320. options = [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP]
  321. if not exclude_bottom:
  322. options.append(self.C_RANDOM_BOTTOM)
  323. target = random.choice(options)
  324. self.click(target, interval=1.8)
  325. return 1
  326. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  327. # 通用战斗结束判断
  328. self.device.stuck_record_add("BATTLE_STATUS_S")
  329. self.device.click_record_clear()
  330. logger.info("Start battle process")
  331. for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
  332. btn.name = "BATTLE_RANDOM"
  333. ok_cnt, max_retry = 0, 5
  334. while 1:
  335. self.screenshot()
  336. sleep(0.5)
  337. # 已经回到对应挑战界面
  338. if self.ui_page_appear(self.page_map[self.climb_type]):
  339. break
  340. # 达到最大重试次数且没有回到活动界面
  341. if ok_cnt > max_retry:
  342. self.click(self.random_reward_click(exclude_bottom=True), interval=1)
  343. break
  344. # 已经胜利但是后续识别失败则重新识别并点击
  345. if 0 < ok_cnt <= max_retry:
  346. # 紫蛇皮消失
  347. self.ui_click_until_smt_disappear(self.random_reward_click(exclude_bottom=True),
  348. self.I_REWARD_PURPLE_SNAKE_SKIN, interval=1.6)
  349. self.ui_get_current_page()
  350. self.ui_goto(self.page_map[self.climb_type])
  351. ok_cnt += 1
  352. continue
  353. # 胜利(鼓 | 魂 | 获得奖励)
  354. if self.appear(self.I_WIN) or self.appear(self.I_REWARD) or self.appear(self.I_UI_REWARD):
  355. if ok_cnt == 0:
  356. logger.info("Win battle")
  357. # 鼓消失
  358. self.ui_click_until_smt_disappear(self.random_reward_click(), self.I_WIN, interval=1.1)
  359. # 魂消失
  360. self.ui_click_until_smt_disappear(self.random_reward_click(exclude_bottom=True), self.I_REWARD,
  361. interval=1.3)
  362. # 紫蛇皮消失
  363. self.ui_click_until_smt_disappear(self.random_reward_click(exclude_bottom=True),
  364. self.I_REWARD_PURPLE_SNAKE_SKIN, interval=1.6)
  365. # 获得奖励消失
  366. self.ui_click_until_smt_disappear(self.random_reward_click(),
  367. self.I_UI_REWARD, interval=1.6)
  368. ok_cnt += 1
  369. continue
  370. # 失败
  371. if self.appear(self.I_FALSE):
  372. logger.warning("False battle")
  373. self.ui_click_until_smt_disappear(self.random_reward_click(), self.I_FALSE, interval=1.5)
  374. return False
  375. # 战斗中随机滑动
  376. if random_click_swipt_enable:
  377. self.random_click_swipt()
  378. return True
  379. if __name__ == '__main__':
  380. from module.config.config import Config
  381. from module.device.device import Device
  382. c = Config('oas3')
  383. d = Device(c)
  384. t = ScriptTask(c, d)
  385. t.switch_buff(c.activity_shikigami.general_climb)