script_task.py 17 KB

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