script_task.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import time
  5. import cv2
  6. import numpy as np
  7. import random
  8. from module.atom.click import RuleClick
  9. from module.base.timer import Timer
  10. from tasks.base_task import BaseTask
  11. from tasks.Component.GeneralBattle.general_battle import GeneralBattle
  12. from tasks.Component.GeneralBattle.battle import Battle
  13. from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy, battle_wait_options
  14. from tasks.GameUi.game_ui import GameUi
  15. from tasks.GameUi.page import page_area_boss, page_shikigami_records
  16. from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
  17. from tasks.AreaBoss.assets import AreaBossAssets
  18. from tasks.AreaBoss.config_boss import AreaBossFloor
  19. from module.logger import logger
  20. from module.exception import GameStuckError, TaskEnd
  21. from module.atom.image import RuleImage
  22. from typing import List
  23. class ScriptTask(Battle, GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
  24. def _get_dynamic_boss_count(self) -> int:
  25. """
  26. 从地域鬼王主界面 OCR 声望值,动态决定可挑战次数
  27. :return: 可挑战鬼王数量 (1/2/3)
  28. """
  29. self.screenshot()
  30. rep = self.O_AB_REPUTATION.ocr_digit(self.device.image)
  31. logger.info(f"Area boss reputation: {rep}")
  32. if rep >= 10000:
  33. return 3
  34. elif rep >= 2000:
  35. return 2
  36. else:
  37. return 1
  38. def run(self) -> bool:
  39. """
  40. 运行脚本
  41. :return:
  42. """
  43. # 直接手动关闭这个锁定阵容的设置
  44. self.config.area_boss.general_battle.lock_team_enable = False
  45. con = self.config.area_boss.boss
  46. if self.config.area_boss.switch_soul.enable:
  47. self.goto_page(page_shikigami_records)
  48. self.run_switch_soul(self.config.area_boss.switch_soul.switch_group_team)
  49. if self.config.area_boss.switch_soul.enable_switch_by_name:
  50. self.goto_page(page_shikigami_records)
  51. self.run_switch_soul_by_name(self.config.area_boss.switch_soul.group_name,
  52. self.config.area_boss.switch_soul.team_name)
  53. self.goto_page(page_area_boss)
  54. reward_name = self.fight_reward_boss() if con.boss_reward else None
  55. defeated = {reward_name} if reward_name else set()
  56. boss_fought = len(defeated)
  57. self.open_filter()
  58. # 切换到对应集合(热门/收藏)
  59. if con.use_collect:
  60. self.switch_to_collect()
  61. else:
  62. self.switch_to_famous()
  63. # 动态获取可挑战次数
  64. dynamic_count = self._get_dynamic_boss_count()
  65. for battle in (self.I_BATTLE_1, self.I_BATTLE_2, self.I_BATTLE_3):
  66. if boss_fought >= dynamic_count:
  67. break
  68. if self.boss_fight(battle, defeated=defeated if reward_name else None):
  69. boss_fought += 1
  70. if boss_fought < dynamic_count:
  71. logger.warning(f"Only defeated {boss_fought}/{dynamic_count} area bosses")
  72. # 退出
  73. self.go_back()
  74. self.set_next_run(task='AreaBoss', success=boss_fought == dynamic_count, finish=False)
  75. # 以抛出异常的形式结束
  76. raise TaskEnd
  77. def go_back(self) -> None:
  78. """
  79. 从地域鬼王返回主页,处理战后可能重新出现的详情页。
  80. :return:
  81. """
  82. # 点击返回
  83. logger.info("Script back home")
  84. timeout = Timer(20).start()
  85. while 1:
  86. self.screenshot()
  87. if timeout.reached():
  88. raise GameStuckError("Area boss return home timed out")
  89. if self._handle_boss_detail():
  90. continue
  91. if self.appear(self.I_CHECK_MAIN, threshold=0.6):
  92. return
  93. self.appear_then_click(self.I_UI_BACK_YELLOW, threshold=0.6, interval=2)
  94. def _handle_boss_detail(self) -> bool:
  95. """True 表示详情页仍遮挡当前帧,包括关闭按钮处于点击冷却时。"""
  96. if not self.appear(self.I_AB_CLOSE_RED):
  97. return False
  98. # 入场动画中红叉可能先出现,等挑战按钮就绪后再关闭。
  99. if self.appear(self.I_FIRE):
  100. self.appear_then_click(self.I_AB_CLOSE_RED, interval=1)
  101. return True
  102. def boss(self, battle: RuleImage, collect: bool = False):
  103. # 点击右上角的鬼王选择
  104. logger.info("Script filter")
  105. while 1:
  106. self.screenshot()
  107. # 如果筛选界面已经打开 点击热门按钮
  108. if self.appear(self.I_AB_FILTER_OPENED):
  109. self.click(self.C_AB_FAMOUS_BTN)
  110. break
  111. if self.appear_then_click(self.I_FILTER, interval=3):
  112. continue
  113. if collect:
  114. self.switch_to_collect()
  115. # 页面没有可挑战的BOSS
  116. if not (self.appear(self.I_BATTLE_1) or self.appear(self.I_BATTLE_2) or self.appear(self.I_BATTLE_3)):
  117. logger.error("There is no boss could be challenged")
  118. return
  119. # 点击第几个鬼王
  120. logger.info(f'Script area boss {battle}')
  121. self.ui_click(battle, self.I_AB_CLOSE_RED)
  122. # 点击挑战
  123. logger.info("Script fire ")
  124. while 1:
  125. self.screenshot()
  126. if self.appear_then_click(self.I_FIRE, interval=1):
  127. continue
  128. if not self.appear(self.I_AB_CLOSE_RED): # 如果这个红色的关闭不见了才可以进行继续
  129. break
  130. if not self.run_general_battle(self.config.area_boss.general_battle):
  131. logger.info("地域鬼王第2只战斗失败")
  132. # 红色关闭
  133. logger.info("Script close red")
  134. self.wait_until_appear(self.I_AB_CLOSE_RED)
  135. self.ui_click(self.I_AB_CLOSE_RED, self.I_FILTER)
  136. def boss_fight(self, battle: RuleImage, fileter_open: bool = True, defeated: set[str] | None = None) -> bool:
  137. """
  138. 完成挑战一个鬼王的全流程
  139. 从打开筛选界面开始 到关闭鬼王详情界面结束
  140. @param battle: 挑战按钮,鬼王头像也可,只要点击能进入详情界面
  141. @type battle:
  142. @return: True 挑战成功
  143. False 挑战失败
  144. @rtype:
  145. """
  146. reward_floor = self.config.area_boss.boss.reward_floor
  147. if fileter_open and not self.appear(self.I_AB_FILTER_OPENED):
  148. self.open_filter()
  149. # 如果打不开鬼王详情界面,直接退出
  150. if not self.open_boss_detail(battle, 3):
  151. return False
  152. if defeated is not None:
  153. name = self.read_boss_name()
  154. if not name or name in defeated:
  155. logger.info(f"Skip area boss: {name or 'unreadable name'}")
  156. self._return_from_boss_detail()
  157. return False
  158. # 根据 reward_floor 决定模式
  159. if reward_floor in (AreaBossFloor.ONE, AreaBossFloor.TEN):
  160. # 极模式分支
  161. if self.setup_ultra(reward_floor):
  162. pass
  163. elif reward_floor == AreaBossFloor.NORMAL_LV60:
  164. # 普通模式-拉到60级
  165. self.setup_normal()
  166. self.switch_to_level_60()
  167. elif reward_floor == AreaBossFloor.NORMAL_LV1:
  168. # 普通模式-保持1级
  169. self.setup_normal()
  170. # DEFAULT: 不更改,直接打
  171. result = True
  172. if not self.start_fight():
  173. result = False
  174. logger.warning("Area Boss Fight Failed ")
  175. elif defeated is not None:
  176. defeated.add(name)
  177. self._return_from_boss_detail()
  178. return result
  179. def _return_from_boss_detail(self):
  180. timeout = Timer(20).start()
  181. while 1:
  182. self.screenshot()
  183. if timeout.reached():
  184. raise GameStuckError("Area boss battle return timed out")
  185. if self._handle_boss_detail():
  186. continue
  187. # 结算和关闭动画后可能直接回地图,不固定等待红叉出现。
  188. # 若地图只是过渡帧,后续 open_filter/go_back 会继续处理详情页。
  189. if self.appear(self.I_FILTER) or self.appear(self.I_AB_FILTER_OPENED):
  190. return
  191. def start_fight(self) -> bool:
  192. while 1:
  193. self.screenshot()
  194. if self.appear_then_click(self.I_FIRE, interval=1):
  195. continue
  196. if not self.appear(self.I_AB_CLOSE_RED): # 如果这个红色的关闭不见了才可以进行继续
  197. break
  198. strategies, options = self.loadout_from_config(self.config.area_boss.general_battle)
  199. options['completion'].check_imgs = [self.I_FIRE, self.I_FILTER]
  200. self.loadout_show((strategies, options)) # 使用的是默认的策略: strategies
  201. with battle_wait_strategy(**strategies), battle_wait_options(**options):
  202. win = self.battle_wait()
  203. return win
  204. def setup_ultra(self, floor: AreaBossFloor = AreaBossFloor.ONE) -> bool:
  205. # 确定进入鬼王界面
  206. self.wait_until_appear(self.I_AB_CLOSE_RED)
  207. # 尝试切换
  208. if not self.get_difficulty():
  209. # 如果可以切换,直接切换
  210. if self.appear(self.I_AB_DIFFICULTY_NORMAL):
  211. self.switch_difficulty(True)
  212. else:
  213. logger.warning("Cannot switch difficulty")
  214. return False
  215. # 调整极地鬼层数
  216. match floor:
  217. case AreaBossFloor.ONE:
  218. self.switch_to_floor_1()
  219. case AreaBossFloor.TEN:
  220. self.switch_to_floor_10()
  221. return True
  222. def setup_normal(self) -> bool:
  223. """
  224. 确保当前为普通地鬼模式
  225. :return: True 成功(已处于普通模式),False 失败
  226. """
  227. self.wait_until_appear(self.I_AB_CLOSE_RED)
  228. if self.get_difficulty():
  229. # 当前是极地鬼,需要切回普通
  230. if self.appear(self.I_AB_DIFFICULTY_JI):
  231. self.switch_difficulty(False)
  232. else:
  233. logger.warning("Cannot switch to normal difficulty")
  234. return False
  235. return True
  236. def switch_to_level_60(self):
  237. logger.info("Switch to level 60")
  238. while 1:
  239. self.screenshot()
  240. if self.appear(self.I_AB_LEVEL_60):
  241. break
  242. if self.appear(self.I_AB_LEVEL_HANDLE):
  243. x, y = self.I_AB_LEVEL_HANDLE.front_center()
  244. self.S_AB_LEVEL_RIGHT.roi_front = (x, y, 10, 10)
  245. self.swipe(self.S_AB_LEVEL_RIGHT, interval=3)
  246. def get_difficulty(self) -> bool:
  247. """
  248. @return: True 极地鬼
  249. False 普通地鬼
  250. @rtype: bool
  251. """
  252. self.screenshot()
  253. return self.appear(self.I_AB_DIFFICULTY_JI)
  254. def switch_difficulty(self, ultra: bool = True):
  255. """
  256. 切换普通地鬼/极地鬼
  257. @param ultra: 是否切换到极地鬼
  258. True 切换到极地鬼
  259. False 切换到普通地鬼
  260. @type ultra:
  261. """
  262. _from = self.I_AB_DIFFICULTY_NORMAL if ultra else self.I_AB_DIFFICULTY_JI
  263. _to = self.I_AB_DIFFICULTY_JI if ultra else self.I_AB_DIFFICULTY_NORMAL
  264. while 1:
  265. self.screenshot()
  266. if self.appear(_to):
  267. break
  268. if self.appear(_from):
  269. self.click(_from, interval=3)
  270. continue
  271. def switch_to_floor_1(self):
  272. """
  273. 更改层数为一层
  274. """
  275. # _Floor = ["壹星", "贰星", "叁星", "肆星", "伍星", "陆星", "柒星", "捌星", "玖星", "拾星"]
  276. # 打开选择列表
  277. self.ui_click(self.C_AB_JI_FLOOR_SELECTED, self.I_AB_JI_FLOOR_LIST_CHECK, interval=3)
  278. while 1:
  279. self.screenshot()
  280. if self.appear(self.I_AB_JI_FLOOR_ONE):
  281. self.click(self.I_AB_JI_FLOOR_ONE)
  282. logger.info("Switch to floor 1")
  283. break
  284. self.swipe(self.S_AB_FLOOR_DOWN, interval=1)
  285. # 等待滑动动画
  286. self.wait_until_appear(self.I_AB_JI_FLOOR_ONE, False, 1)
  287. def switch_to_floor_10(self):
  288. """
  289. 更改层数为十层
  290. """
  291. # 打开选择列表
  292. self.ui_click(self.C_AB_JI_FLOOR_SELECTED, self.I_AB_JI_FLOOR_LIST_CHECK, interval=3)
  293. while 1:
  294. self.screenshot()
  295. if self.appear(self.I_AB_JI_FLOOR_TEN):
  296. self.click(self.I_AB_JI_FLOOR_TEN)
  297. logger.info("Switch to floor 10")
  298. break
  299. self.wait_until_appear(self.I_AB_JI_FLOOR_TEN, False, 1)
  300. def fight_reward_boss(self) -> str | None:
  301. BOSS_REWARD_PHOTO1 = [self.C_AB_BOSS_REWARD_PHOTO_1, self.C_AB_BOSS_REWARD_PHOTO_2, self.C_AB_BOSS_REWARD_PHOTO_3]
  302. BOSS_REWARD_PHOTO2 = [self.C_AB_BOSS_REWARD_PHOTO_MINUS_2, self.C_AB_BOSS_REWARD_PHOTO_MINUS_1]
  303. need_open_filter, boss_name, photo = self.get_hot_in_reward() # 获取挑战人数最多的Boss的名字
  304. if photo is None or boss_name == '声望不够':
  305. return None
  306. # 不需要打开筛选界面说明直接找到了目标boss, 直接挑战
  307. if not need_open_filter:
  308. return boss_name if self.boss_fight(photo, fileter_open=False) else None
  309. # 滑动到最顶层
  310. logger.info("Swipe to top")
  311. for i in range(random.randint(1, 3)):
  312. self.swipe(self.S_AB_FILTER_DOWN)
  313. # 遍历所有boss找到名称一致的即目前挑战人数最多的
  314. for PHOTO in BOSS_REWARD_PHOTO1:
  315. self.open_filter()
  316. name = self.get_bossName(PHOTO)
  317. if self.check_common_chars(str(name), boss_name):
  318. return name if self.boss_fight(PHOTO, fileter_open=False) else None
  319. self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
  320. # 倒数一和二
  321. for i in range(random.randint(1, 3)):
  322. self.swipe(self.S_AB_FILTER_UP)
  323. for PHOTO in BOSS_REWARD_PHOTO2:
  324. self.open_filter()
  325. name = self.get_bossName(PHOTO)
  326. if self.check_common_chars(str(name), boss_name):
  327. return name if self.boss_fight(PHOTO, fileter_open=False) else None
  328. self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
  329. self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
  330. def get_hot_in_reward(self):
  331. """
  332. 返回挑战人数最多的悬赏鬼王
  333. @return: 是否打开筛选界面, boss名称, boss图片的click
  334. @rtype:
  335. """
  336. self.switch_to_reward()
  337. boss_configs = [
  338. {"photo": self.C_AB_BOSS_REWARD_PHOTO_1, "need_swipe": False},
  339. {"photo": self.C_AB_BOSS_REWARD_PHOTO_2, "need_swipe": False},
  340. {"photo": self.C_AB_BOSS_REWARD_PHOTO_3, "need_swipe": False},
  341. {"photo": self.C_AB_BOSS_REWARD_PHOTO_MINUS_2, "need_swipe": True},
  342. {"photo": self.C_AB_BOSS_REWARD_PHOTO_MINUS_1, "need_swipe": True},
  343. ]
  344. def check_boss(photo: RuleClick):
  345. """
  346. 检查boss是否满足条件
  347. :param photo:
  348. :return: 是否满足条件, 挑战数量, boss名称
  349. """
  350. self.open_filter()
  351. num = self.get_num_challenge(photo) or 0
  352. if not num:
  353. name = '声望不够'
  354. else:
  355. name = self.get_bossName(photo)
  356. if not name:
  357. logger.warning("Skip reward boss: unreadable name")
  358. num = 0
  359. elif num >= 20000 and not self.appear(self.I_AB_NUM_CHALLENGE_RAIL):
  360. logger.info("The number of challenges is enough")
  361. return True, num, name
  362. # 没找到满足的则关闭boss页面
  363. self.ui_click_until_disappear(self.I_AB_CLOSE_RED)
  364. return False, num, name
  365. mx_challenge_boss_name = None
  366. mx_challenge_num = 0
  367. photo = None
  368. # 遍历所有boss配置, 找挑战人数最多的boss
  369. for cfg in boss_configs:
  370. if cfg["need_swipe"]:
  371. self.open_filter()
  372. for _ in range(random.randint(1, 3)):
  373. self.swipe(self.S_AB_FILTER_UP)
  374. self.wait_until_appear(cfg["photo"], wait_time=1)
  375. ret, challenge_num, boss_name = check_boss(cfg["photo"])
  376. if ret: # 直接找到满足条件的, 则不需要打开筛选界面直接挑战即可
  377. return False, boss_name, cfg["photo"]
  378. if challenge_num > mx_challenge_num:
  379. mx_challenge_num = challenge_num
  380. mx_challenge_boss_name = boss_name
  381. photo = cfg['photo']
  382. logger.attr(mx_challenge_num, f'Select:{boss_name},{photo.name}')
  383. return True, mx_challenge_boss_name if mx_challenge_boss_name else '声望不够', photo if mx_challenge_boss_name else None
  384. def get_num_challenge(self, click_area):
  385. """
  386. 获取鬼王挑战人数
  387. @param click_area: 鬼王相应的挑战按钮
  388. @type click_area:
  389. @return:
  390. @rtype:
  391. """
  392. # 如果鬼王不可挑战(未解锁),限制3次尝试打开鬼王详情界面
  393. if not self.open_boss_detail(click_area, 3):
  394. logger.info("%s unavailable", str(click_area))
  395. return 0
  396. return self.O_AB_NUM_OF_CHALLENGE.ocr_digit(self.device.image)
  397. def get_bossName(self, click_area):
  398. """
  399. 获取鬼王名字
  400. @param click_area: 鬼王相应的挑战按钮
  401. @type click_area:
  402. @return:
  403. @rtype:
  404. """
  405. # 如果鬼王不可挑战(未解锁),限制3次尝试打开鬼王详情界面
  406. if not self.open_boss_detail(click_area, 3):
  407. logger.info("%s unavailable", str(click_area))
  408. return 0
  409. return self.read_boss_name()
  410. def read_boss_name(self) -> str:
  411. for attempt in range(2):
  412. if attempt:
  413. self.screenshot()
  414. rows = self.O_AB_BOSS_NAME.detect_and_ocr(self.device.image)
  415. name = ''.join(''.join(row.ocr_text.split()) for row in rows)
  416. if name:
  417. return name
  418. return ''
  419. def open_boss_detail(self, battle: RuleImage, try_num: int = 3) -> bool:
  420. """
  421. 打开鬼王详情界面
  422. @param battle:
  423. @type battle:
  424. @param try_num: 重试次数
  425. @type try_num:
  426. @return: True 打开成功
  427. False 打开失败
  428. @rtype:
  429. """
  430. try_count = 0
  431. while 1:
  432. self.screenshot()
  433. if self.appear(self.I_AB_CLOSE_RED) and self.appear(self.I_FIRE):
  434. self.screenshot()
  435. if not self.appear(self.I_FIRE):
  436. continue
  437. return True
  438. if try_count >= try_num:
  439. logger.warning(f"Cannot boss_detail, try {try_count} times")
  440. return False
  441. if self.click(battle, interval=3):
  442. try_count += 1
  443. continue
  444. return True
  445. def is_group_ranked(self):
  446. """
  447. 判断该鬼王是否已经获取到小组排名
  448. """
  449. return not self.appear(self.I_AB_GROUP_RANK_NONE)
  450. pass
  451. def open_filter(self):
  452. """打开筛选界面"""
  453. logger.info("openFilter")
  454. timeout = Timer(20).start()
  455. while 1:
  456. self.screenshot()
  457. if timeout.reached():
  458. raise GameStuckError("Area boss filter did not open")
  459. if self._handle_boss_detail():
  460. continue
  461. if self.appear(self.I_AB_FILTER_OPENED):
  462. return
  463. self.appear_then_click(self.I_FILTER, interval=3)
  464. def switch_to_collect(self):
  465. while 1:
  466. self.screenshot()
  467. if self.appear(self.I_AB_FILTER_TITLE_COLLECTION):
  468. break
  469. if self.appear(self.I_AB_FILTER_OPENED):
  470. self.click(self.C_AB_COLLECTION_BTN, 1.5)
  471. continue
  472. def switch_to_famous(self):
  473. while 1:
  474. self.screenshot()
  475. if self.appear(self.I_AB_FILTER_TITLE_FAMOUS):
  476. break
  477. if self.appear(self.I_AB_FILTER_OPENED):
  478. self.click(self.C_AB_FAMOUS_BTN, 1.5)
  479. continue
  480. def switch_to_reward(self):
  481. self.open_filter()
  482. while 1:
  483. self.screenshot()
  484. if self.appear(self.I_AB_FILTER_TITLE_REWARD):
  485. break
  486. if self.appear(self.I_AB_FILTER_OPENED):
  487. self.click(self.C_AB_REWARD_BTN, 1.5)
  488. continue
  489. def check_common_chars(self, bossName, name):
  490. # 将两个字符串转为集合,去除重复的字符
  491. set_boss = set(bossName)
  492. set_name = set(name)
  493. # 计算交集,判断交集的元素个数
  494. common_chars = set_boss & set_name # & 是集合的交集运算符
  495. if len(common_chars) >= 2:
  496. return 1
  497. else:
  498. return 0 # 如果交集的字符少于2个,可以根据需要返回其他值
  499. if __name__ == '__main__':
  500. from module.config.config import Config
  501. from module.device.device import Device
  502. c = Config('oas1')
  503. d = Device(c)
  504. t = ScriptTask(c, d)
  505. # time.sleep(3)
  506. # t.switchFloor2One()
  507. # t.switch2Level60()
  508. t.run()