script_task.py 18 KB

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