base.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import time
  5. import numpy as np
  6. import random
  7. from enum import Enum
  8. from cached_property import cached_property
  9. from datetime import timedelta, datetime
  10. from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
  11. from tasks.Component.GeneralRoom.general_room import GeneralRoom
  12. from tasks.Component.GeneralInvite.general_invite import GeneralInvite
  13. from tasks.Component.ReplaceShikigami.replace_shikigami import ReplaceShikigami
  14. from tasks.Exploration.assets import ExplorationAssets
  15. from tasks.Exploration.config import ChooseRarity, AutoRotate, AttackNumber, UpType, ExplorationLevel
  16. from tasks.Component.GeneralBattle.general_battle import GeneralBattle
  17. from tasks.GameUi.game_ui import GameUi
  18. from tasks.GameUi.page import page_shikigami_records, page_main
  19. import tasks.Exploration.page as pages
  20. from tasks.RealmRaid.script_task import ScriptTask as RealmRaidScriptTask
  21. from tasks.Utils.config_enum import ShikigamiClass
  22. from module.logger import logger
  23. from module.base.timer import Timer
  24. from module.exception import RequestHumanTakeover, TaskEnd, GameStuckError
  25. from module.atom.image_grid import ImageGrid
  26. from module.atom.animate import RuleAnimate
  27. from module.base.utils import load_image
  28. class Scene(Enum):
  29. UNKNOWN = 0 #
  30. WORLD = 1 # 探索大世界
  31. ENTRANCE = 2 # 入口弹窗
  32. MAIN = 3 # 探索里面
  33. BATTLE_PREPARE = 4 # 战斗准备
  34. BATTLE_FIGHTING = 5 # 战斗中
  35. TEAM = 6 # 组队
  36. class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, ReplaceShikigami, SwitchSoul, ExplorationAssets):
  37. minions_cnt = 0
  38. @cached_property
  39. def _config(self):
  40. self.config.exploration.general_battle_config.lock_team_enable = True
  41. limit_time = self.config.exploration.exploration_config.limit_time
  42. self.limit_time: timedelta = timedelta(
  43. hours=limit_time.hour,
  44. minutes=limit_time.minute,
  45. seconds=limit_time.second
  46. )
  47. return self.config.model.exploration
  48. @cached_property
  49. def _match_end(self):
  50. return RuleAnimate(self.I_SWIPE_END)
  51. def is_swipe_unchanged(self, before_image, after_image, threshold: float = 20) -> bool:
  52. # 对比滑屏前后同一块区域,变化很小说明地图大概率没有移动,已经滑到尽头。
  53. swipe_check_roi = (1216, 86, 64, 225)
  54. before = self.I_SWIPE_END.corp(before_image, swipe_check_roi)
  55. after = self.I_SWIPE_END.corp(after_image, swipe_check_roi)
  56. diff = np.mean(np.abs(before.astype(np.int16) - after.astype(np.int16)))
  57. logger.info(f'Swipe end area diff: {diff:.2f}')
  58. return diff <= threshold
  59. def get_current_scene(self, reuse_screenshot: bool = True) -> Scene:
  60. if not reuse_screenshot:
  61. self.screenshot()
  62. if self.appear(self.I_CHECK_EXPLORATION) and not self.appear(self.I_E_SETTINGS_BUTTON):
  63. return Scene.WORLD
  64. elif self.appear(self.I_E_EXPLORATION_CLICK):
  65. return Scene.ENTRANCE
  66. elif self.appear(self.I_E_SETTINGS_BUTTON) or self.appear(self.I_E_AUTO_ROTATE_ON) or self.appear(self.I_E_AUTO_ROTATE_OFF):
  67. return Scene.MAIN
  68. elif self.is_in_prepare():
  69. return Scene.BATTLE_PREPARE
  70. elif self.is_in_battle():
  71. return Scene.BATTLE_FIGHTING
  72. elif self.is_in_room() or self.appear(self.I_CREATE_ENSURE):
  73. return Scene.TEAM
  74. logger.info("Unknown scene")
  75. return Scene.UNKNOWN
  76. def pre_process(self):
  77. explorationConfig = self._config
  78. if explorationConfig.switch_soul_config.enable:
  79. self.goto_page(page_shikigami_records)
  80. self.run_switch_soul(explorationConfig.switch_soul_config.switch_group_team)
  81. if explorationConfig.switch_soul_config.enable_switch_by_name:
  82. self.goto_page(page_shikigami_records)
  83. self.run_switch_soul_by_name(explorationConfig.switch_soul_config.group_name,
  84. explorationConfig.switch_soul_config.team_name)
  85. # 开启加成
  86. con = self.config.exploration.exploration_config
  87. if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
  88. self.goto_page(page_main)
  89. self.open_buff()
  90. if con.buff_gold_50_click:
  91. self.gold_50()
  92. if con.buff_gold_100_click:
  93. self.gold_100()
  94. if con.buff_exp_50_click:
  95. self.exp_50()
  96. if con.buff_exp_100_click:
  97. self.exp_100()
  98. self.close_buff()
  99. # 探索页面(大地图始终处于主线/玩法 tab 之一,裸 page_exploration 永远被 prio 60 的 tab 页遮蔽、
  100. # 无法作为当前页抵达,故直接进入主线 tab)
  101. self.goto_page(pages.page_mainline)
  102. def post_process(self):
  103. self.wait_until_stable(self.I_UI_BACK_RED)
  104. if self.appear(self.I_UI_BACK_RED):
  105. self.ui_click_until_disappear(self.I_UI_BACK_RED)
  106. self.goto_page(page_main)
  107. con = self._config.exploration_config
  108. if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
  109. self.open_buff()
  110. self.gold_50(is_open=False)
  111. self.gold_100(is_open=False)
  112. self.exp_50(is_open=False)
  113. self.exp_100(is_open=False)
  114. self.close_buff()
  115. self.set_next_run(task='Exploration', success=True, finish=False)
  116. raise TaskEnd
  117. # 打开指定的章节:
  118. def open_expect_level(self):
  119. # 选关依赖主线 tab 右侧的章节列表(I_E_EXPLORATION_CLICK + 章节名 OCR)。
  120. # 探索大地图常驻「主线/玩法」之一,若停在玩法 tab 不选回主线,右边会是御魂/今日掉落等模块名,
  121. # I_E_EXPLORATION_CLICK 不出现、OCR 交集为空 → 一直滑屏卡死。故进选关前无条件确保主线 tab。
  122. self.goto_page(pages.page_mainline)
  123. target_level = self.config.exploration.exploration_config.exploration_level
  124. level_numbers = {level.value: index for index, level in enumerate(ExplorationLevel)}
  125. target_number = level_numbers[target_level]
  126. # 新版列表按章节递增排列;OCR 暂时为空时沿用上一次方向。
  127. swipe = self.S_SWIPE_LEVEL_DOWN
  128. swipeCount = 0
  129. while 1:
  130. # 判断有无目标章节
  131. self.screenshot()
  132. # 获取当前章节名
  133. results = self.O_E_EXPLORATION_LEVEL_NUMBER.detect_and_ocr(self.device.image)
  134. text1 = [result.ocr_text for result in results]
  135. # https://github.com/runhey/OnmyojiAutoScript/issues/1540
  136. text1 = [text.replace("名", "第").replace("书", "第") for text in text1]
  137. # 判断当前章节有无目标章节
  138. # 有则跳出检测
  139. if self.appear(self.I_E_EXPLORATION_CLICK) or target_level in text1:
  140. break
  141. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  142. continue
  143. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  144. continue
  145. visible_numbers = [level_numbers[text] for text in text1 if text in level_numbers]
  146. if visible_numbers:
  147. if target_number < min(visible_numbers):
  148. swipe = self.S_SWIPE_LEVEL_UP
  149. elif target_number > max(visible_numbers):
  150. swipe = self.S_SWIPE_LEVEL_DOWN
  151. self.device.click_record_clear()
  152. self.swipe(swipe)
  153. swipeCount += 1
  154. debug_info = f"Swiped {swipeCount} times ({swipe.name}), current exploration level: {text1}"
  155. logger.info(debug_info)
  156. if swipeCount >= 15:
  157. raise GameStuckError(
  158. f"Swiped too many times ({swipeCount}), seems stuck in exploration level selection"
  159. )
  160. time.sleep(1)
  161. # 选中对应章节
  162. while 1:
  163. self.screenshot()
  164. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  165. continue
  166. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  167. continue
  168. self.O_E_EXPLORATION_LEVEL_NUMBER.keyword = target_level
  169. if self.ocr_appear_click(self.O_E_EXPLORATION_LEVEL_NUMBER):
  170. self.wait_until_appear(self.I_E_EXPLORATION_CLICK, wait_time=3)
  171. if self.appear(self.I_E_EXPLORATION_CLICK):
  172. break
  173. if self.is_in_room():
  174. break
  175. return True
  176. # 候补:
  177. def enter_settings_and_do_operations(self):
  178. # 打开设置
  179. while 1:
  180. self.screenshot()
  181. if self.appear(self.I_E_OPEN_SETTINGS):
  182. logger.info("Open settings")
  183. break
  184. if self.is_in_battle():
  185. logger.warning('Opening settings failed due to now in battle')
  186. return
  187. if (self.appear_then_click(self.I_UI_CONFIRM, interval=1)
  188. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1)):
  189. continue
  190. if self.click(self.C_CLICK_SETTINGS, interval=2):
  191. continue
  192. # 候补出战数量识别
  193. self.screenshot()
  194. if not self.appear(self.I_E_OPEN_SETTINGS):
  195. logger.warning('Opening settings failed due to now in battle')
  196. return
  197. cu, res, total = self.O_E_ALTERNATE_NUMBER.ocr(self.device.image)
  198. if cu >= 40:
  199. logger.info("Alternate number is enough")
  200. self.ui_click_until_disappear(self.I_E_SURE_BUTTON)
  201. return
  202. else:
  203. self.add_shiki()
  204. # 添加式神
  205. def add_shiki(self, screenshot=True):
  206. if screenshot:
  207. self.screenshot()
  208. if not self.appear(self.I_E_OPEN_SETTINGS):
  209. logger.warning('Opening settings failed due to now in battle')
  210. return
  211. # 先点候补式神区域,再切换稀有度,避免点击失败
  212. self.click(self.C_CLICK_STANDBY_TEAM)
  213. choose_rarity = self._config.exploration_config.choose_rarity
  214. rarity = ShikigamiClass.N if choose_rarity == ChooseRarity.N else ShikigamiClass.MATERIAL
  215. self.switch_shikigami_class(rarity)
  216. # 移动至未候补的狗粮
  217. while 1:
  218. # 慢一点
  219. time.sleep(0.5)
  220. self.screenshot()
  221. if not self.appear(self.I_E_OPEN_SETTINGS):
  222. logger.warning('Opening settings failed due to now in battle')
  223. return
  224. if self.appear(self.I_E_RATATE_EXSIT):
  225. self.swipe(self.S_SWIPE_SHIKI_TO_LEFT)
  226. else:
  227. break
  228. while 1:
  229. # 候补出战数量识别
  230. self.screenshot()
  231. if not self.appear(self.I_E_OPEN_SETTINGS):
  232. logger.warning('Opening settings failed due to now in battle')
  233. return
  234. cu, res, total = self.O_E_ALTERNATE_NUMBER.ocr(self.device.image)
  235. if cu >= 40:
  236. break
  237. self.swipe(self.S_SWIPE_SHIKI_TO_LEFT_ONE)
  238. # 慢一点
  239. time.sleep(0.5)
  240. self.screenshot()
  241. self.click(self.L_ROTATE_1)
  242. self.device.click_record_clear()
  243. self.appear_then_click(self.I_E_SURE_BUTTON)
  244. # 找up按钮
  245. def search_up_fight(self, up_type: UpType = None):
  246. if up_type is None:
  247. up_type = self._config.exploration_config.up_type
  248. # 1. 如果选择了特定的 UP 类型 (比如达摩)
  249. if up_type != UpType.ALL:
  250. match up_type:
  251. case UpType.EXP:
  252. find_flag = self.I_UP_EXP
  253. case UpType.COIN:
  254. find_flag = self.I_UP_COIN
  255. case UpType.DARUMAA:
  256. find_flag = self.I_UP_DARUMA
  257. case _:
  258. find_flag = self.I_UP_EXP
  259. # 尝试寻找 UP 图标
  260. if self.appear(find_flag):
  261. # 获取 UP 图标的坐标和中心点
  262. x, y, w, h = find_flag.roi_front
  263. x_center, y_center = find_flag.front_center()
  264. logger.info(f'Found up type: {up_type} at {find_flag.roi_front}')
  265. # 缩小搜索范围 (ROI)
  266. # 原来左右各扩 160-200,太宽了容易甚至把隔壁怪算进来
  267. # 现在改为左右各扩 50-80,强制只找垂直线附近的战斗图标
  268. roi_back_y = max(0, y - 300) # 向上找300像素
  269. roi_back_h = y - 20 - roi_back_y #直到UP图标上方20像素截止
  270. # 左右范围缩窄:防止误触旁边的怪
  271. roi_back_x = max(0, x - 60)
  272. roi_back_w = min(1280, x + w + 60) - roi_back_x
  273. logger.info(f'Searching sword icon in narrowed area: {roi_back_x, roi_back_y, roi_back_w, roi_back_h}')
  274. matches = self.I_NORMAL_BATTLE_BUTTON.match_all(
  275. image=self.device.image,
  276. threshold=0.9,
  277. roi=[roi_back_x, roi_back_y, roi_back_w, roi_back_h]
  278. )
  279. if matches:
  280. distances = []
  281. for match in matches:
  282. # 这里假设 match[1], match[2] 是 x, y
  283. x_match = match[1] + match[3] / 2 # 战斗图标中心 X
  284. y_match = match[2] + match[4] / 2 # 战斗图标中心 Y
  285. # 这样能完美避开“距离很近但属于隔壁怪”的情况
  286. x_diff = abs(x_center - x_match)
  287. y_diff = abs(y_center - y_match)
  288. weighted_distance = (x_diff * 3) + y_diff
  289. distances.append((weighted_distance, match))
  290. # 按加权距离排序,取最正对着的一个
  291. distances.sort(key=lambda x: x[0], reverse=False)
  292. match = distances[0][1]
  293. roi_front = list(match[1:]) # x,y,w,h
  294. self.I_NORMAL_BATTLE_BUTTON.roi_front = roi_front
  295. logger.info(f"Target locked: sword at {roi_front} (aligned with UP icon)")
  296. return self.I_NORMAL_BATTLE_BUTTON
  297. else:
  298. # 没找到 UP 图标,返回 None 让外层逻辑去处理(滑动或退出)
  299. return None
  300. # 2. 如果是默认情况 (UpType.ALL),则只要有怪就打
  301. if self.appear(self.I_NORMAL_BATTLE_BUTTON):
  302. return self.I_NORMAL_BATTLE_BUTTON
  303. return None
  304. def activate_realm_raid(self, con_scrolls, con) -> None:
  305. # 判断是否开启突破票检测
  306. if not con_scrolls.scrolls_enable:
  307. return
  308. if self.appear(self.I_E_EXPLORATION_CLICK) and self.appear(self.I_EXP_CREATE_TEAM):
  309. cu, res, total = self.O_REALM_RAID_NUMBER1.ocr(self.device.image)
  310. else:
  311. cu, res, total = self.O_REALM_RAID_NUMBER.ocr(self.device.image)
  312. # 判断突破票数量
  313. if cu < con_scrolls.scrolls_threshold:
  314. return
  315. # 关闭加成
  316. if self.appear(self.I_RED_CLOSE):
  317. self.ui_click_until_disappear(self.I_RED_CLOSE)
  318. if self.appear(self.I_UI_CANCEL):
  319. self.ui_click_until_disappear(self.I_UI_CANCEL)
  320. if self.appear(self.I_UI_CANCEL_SAMLL):
  321. self.ui_click_until_disappear(self.I_UI_CANCEL_SAMLL)
  322. self.goto_page(page_main)
  323. if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
  324. self.open_buff()
  325. self.gold_50(is_open=False)
  326. self.gold_100(is_open=False)
  327. self.exp_50(is_open=False)
  328. self.exp_100(is_open=False)
  329. self.close_buff()
  330. # 设置下次执行行时间
  331. logger.info("RealmRaid and Exploration set_next_run !")
  332. next_run = datetime.now() + con_scrolls.scrolls_cd
  333. self.set_next_run(task='Exploration', success=False, finish=False, target=next_run)
  334. self.set_next_run(task='RealmRaid', success=False, finish=False, server=False, target=datetime.now())
  335. self.set_next_run(task='MemoryScrolls', success=False, finish=False, target=datetime.now())
  336. raise TaskEnd
  337. #
  338. def check_exit(self) -> bool:
  339. # True 表示要退出这个任务
  340. if self.minions_cnt >= self._config.exploration_config.minions_cnt:
  341. logger.info('Minions count is enough, exit')
  342. return True
  343. if datetime.now() - self.start_time >= self.limit_time:
  344. logger.info('Exploration time limit out')
  345. return True
  346. self.activate_realm_raid(self._config.scrolls, self._config.exploration_config)
  347. return False
  348. def quit_explore(self):
  349. logger.info('Quit explore')
  350. boss_timer = Timer(15)
  351. boss_timer.start()
  352. # click_yellow_button = 0 #用于保证只点一次左上返回按钮,不要直接触发连点回到主界面
  353. while 1:
  354. self.screenshot()
  355. # 探索章节标题界面
  356. if self.appear(self.I_UI_BACK_YELLOW) and self.appear(self.I_E_EXPLORATION_CLICK):
  357. break
  358. # 探索大世界界面
  359. if self.appear(self.I_CHECK_EXPLORATION) and not self.appear(self.I_E_SETTINGS_BUTTON):
  360. break
  361. # 防止BOSS打完箱子刚落地,脚本就手快点退出了
  362. if self.appear_then_click(self.I_BATTLE_REWARD, interval=1.5):
  363. logger.info("Found battle reward during exit, picking it up.")
  364. boss_timer.reset()
  365. continue
  366. if boss_timer.reached():
  367. logger.warning('Exit timeout, force clicking back button')
  368. boss_timer.reset()
  369. self.click(self.I_UI_BACK_BLUE)
  370. continue
  371. if self.appear_then_click(self.I_E_EXIT_CONFIRM, interval=0.8):
  372. continue
  373. if self.appear_then_click(self.I_BACK_YOLLOW, interval=3.5):
  374. continue
  375. if self.appear(self.I_EXPLORATION_TITLE) or self.appear(self.I_CHECK_EXPLORATION):
  376. continue
  377. def _hook_special_reward(self) -> bool:
  378. if self.appear(self.I_STATISTICS) and not self.appear(self.I_REWARD) and not self.appear(self.I_WIN):
  379. if self.appear_then_click(self.I_CONFIRM_CLOSE_DIFF_SOUL):
  380. return True
  381. self.click(self.C_RANDOM_CLICK, interval=1.5)
  382. return False
  383. def fire(self, button) -> bool:
  384. self.ui_click_until_disappear(button, interval=3)
  385. self.screenshot()
  386. if (self.appear(self.I_E_SETTINGS_BUTTON) or
  387. self.appear(self.I_E_AUTO_ROTATE_ON) or
  388. self.appear(self.I_E_AUTO_ROTATE_OFF)):
  389. # 如果还在探索说明,这个是显示滑动导致挑战按钮不在范围内
  390. logger.warning('Fire button disappear, but still in exploration')
  391. return False
  392. self.run_general_battle(self._config.general_battle_config)
  393. self.minions_cnt += 1
  394. return True
  395. def wait_world_stable(self) -> bool:
  396. """
  397. # 打开右边箭头 and https://github.com/runhey/OnmyojiAutoScript/pull/1589/
  398. https://github.com/runhey/OnmyojiAutoScript/issues/1588
  399. @return:
  400. """
  401. while 1:
  402. scene = self.get_current_scene(reuse_screenshot=False)
  403. if scene == Scene.WORLD and self.appear(self.I_EXP_ARROW_RIGHT):
  404. return True
  405. if scene == Scene.ENTRANCE:
  406. logger.warning('World scene unstable, possibly transient frame after paper doll collection')
  407. return False
  408. if self.appear_then_click(self.I_EXP_ARROW_LEFT, interval=2):
  409. continue
  410. if __name__ == "__main__":
  411. from module.config.config import Config
  412. from module.device.device import Device
  413. config = Config('oas1')
  414. device = Device(config)
  415. t = BaseExploration(config, device)
  416. t.screenshot()
  417. # IMAGE_FILE = r"C:\Users\萌萌哒\Desktop\QQ20240818-163854.png"
  418. # image = load_image(IMAGE_FILE)
  419. # t.device.image = image
  420. while 1:
  421. # print(t.search_up_fight(UpType.EXP))
  422. t.screenshot()
  423. print(t.get_current_scene())
  424. from PIL import Image
  425. # Image.fromarray(t.device.image.astype(np.uint8)).show()