base.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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
  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 = 15) -> bool:
  52. # 对比滑屏前后中上部背景区域(避开顶部跑马灯、下方小怪挑战图标及最右侧浮动鬼火),变化很小说明地图已滑到尽头。
  53. swipe_check_roi = (250, 140, 800, 90)
  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. swipeCount = 0
  124. while 1:
  125. # 探索的 config
  126. explorationConfig = self.config.exploration
  127. # 判断有无目标章节
  128. self.screenshot()
  129. # 获取当前章节名
  130. results = self.O_E_EXPLORATION_LEVEL_NUMBER.detect_and_ocr(self.device.image)
  131. text1 = [result.ocr_text for result in results]
  132. # https://github.com/runhey/OnmyojiAutoScript/issues/1540
  133. text1 = [text.replace("名", "第").replace("书", "第") for text in text1]
  134. # 判断当前章节有无目标章节
  135. result = set(text1).intersection({explorationConfig.exploration_config.exploration_level})
  136. # 有则跳出检测
  137. if self.appear(self.I_E_EXPLORATION_CLICK) or result and len(result) > 0:
  138. break
  139. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  140. continue
  141. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  142. continue
  143. self.device.click_record_clear()
  144. self.swipe(self.S_SWIPE_LEVEL_DOWN)
  145. swipeCount += 1
  146. debug_info = f"Swiped {swipeCount} times, current exploration level: {text1}"
  147. logger.info(debug_info)
  148. if swipeCount >= 15:
  149. raise GameStuckError(
  150. f"Swiped too many times ({swipeCount}), seems stuck in exploration level selection"
  151. )
  152. time.sleep(1)
  153. # 选中对应章节
  154. while 1:
  155. self.screenshot()
  156. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  157. continue
  158. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  159. continue
  160. self.O_E_EXPLORATION_LEVEL_NUMBER.keyword = explorationConfig.exploration_config.exploration_level
  161. if self.ocr_appear_click(self.O_E_EXPLORATION_LEVEL_NUMBER):
  162. self.wait_until_appear(self.I_E_EXPLORATION_CLICK, wait_time=3)
  163. if self.appear(self.I_E_EXPLORATION_CLICK):
  164. break
  165. if self.is_in_room():
  166. break
  167. return True
  168. # 候补:
  169. def enter_settings_and_do_operations(self):
  170. # 打开设置
  171. while 1:
  172. self.screenshot()
  173. if self.appear(self.I_E_OPEN_SETTINGS):
  174. logger.info("Open settings")
  175. break
  176. if self.is_in_battle():
  177. logger.warning('Opening settings failed due to now in battle')
  178. return
  179. if (self.appear_then_click(self.I_UI_CONFIRM, interval=1)
  180. or self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1)):
  181. continue
  182. if self.click(self.C_CLICK_SETTINGS, interval=2):
  183. continue
  184. # 候补出战数量识别
  185. self.screenshot()
  186. if not self.appear(self.I_E_OPEN_SETTINGS):
  187. logger.warning('Opening settings failed due to now in battle')
  188. return
  189. cu, res, total = self.O_E_ALTERNATE_NUMBER.ocr(self.device.image)
  190. if cu >= 40:
  191. logger.info("Alternate number is enough")
  192. self.ui_click_until_disappear(self.I_E_SURE_BUTTON)
  193. return
  194. else:
  195. self.add_shiki()
  196. # 添加式神
  197. def add_shiki(self, screenshot=True):
  198. if screenshot:
  199. self.screenshot()
  200. if not self.appear(self.I_E_OPEN_SETTINGS):
  201. logger.warning('Opening settings failed due to now in battle')
  202. return
  203. # 先点候补式神区域,再切换稀有度,避免点击失败
  204. self.click(self.C_CLICK_STANDBY_TEAM)
  205. choose_rarity = self._config.exploration_config.choose_rarity
  206. rarity = ShikigamiClass.N if choose_rarity == ChooseRarity.N else ShikigamiClass.MATERIAL
  207. self.switch_shikigami_class(rarity)
  208. # 移动至未候补的狗粮
  209. while 1:
  210. # 慢一点
  211. time.sleep(0.5)
  212. self.screenshot()
  213. if not self.appear(self.I_E_OPEN_SETTINGS):
  214. logger.warning('Opening settings failed due to now in battle')
  215. return
  216. if self.appear(self.I_E_RATATE_EXSIT):
  217. self.swipe(self.S_SWIPE_SHIKI_TO_LEFT)
  218. else:
  219. break
  220. while 1:
  221. # 候补出战数量识别
  222. self.screenshot()
  223. if not self.appear(self.I_E_OPEN_SETTINGS):
  224. logger.warning('Opening settings failed due to now in battle')
  225. return
  226. cu, res, total = self.O_E_ALTERNATE_NUMBER.ocr(self.device.image)
  227. if cu >= 40:
  228. break
  229. self.swipe(self.S_SWIPE_SHIKI_TO_LEFT_ONE)
  230. # 慢一点
  231. time.sleep(0.5)
  232. self.screenshot()
  233. self.click(self.L_ROTATE_1)
  234. self.device.click_record_clear()
  235. self.appear_then_click(self.I_E_SURE_BUTTON)
  236. # 找up按钮
  237. def search_up_fight(self, up_type: UpType = None):
  238. if up_type is None:
  239. up_type = self._config.exploration_config.up_type
  240. # 1. 如果选择了特定的 UP 类型 (比如达摩)
  241. if up_type != UpType.ALL:
  242. match up_type:
  243. case UpType.EXP:
  244. find_flag = self.I_UP_EXP
  245. case UpType.COIN:
  246. find_flag = self.I_UP_COIN
  247. case UpType.DARUMAA:
  248. find_flag = self.I_UP_DARUMA
  249. case _:
  250. find_flag = self.I_UP_EXP
  251. # 尝试寻找 UP 图标
  252. if self.appear(find_flag):
  253. # 获取 UP 图标的坐标和中心点
  254. x, y, w, h = find_flag.roi_front
  255. x_center, y_center = find_flag.front_center()
  256. logger.info(f'Found up type: {up_type} at {find_flag.roi_front}')
  257. # 缩小搜索范围 (ROI)
  258. # 原来左右各扩 160-200,太宽了容易甚至把隔壁怪算进来
  259. # 现在改为左右各扩 50-80,强制只找垂直线附近的战斗图标
  260. roi_back_y = max(0, y - 300) # 向上找300像素
  261. roi_back_h = y - 20 - roi_back_y #直到UP图标上方20像素截止
  262. # 左右范围缩窄:防止误触旁边的怪
  263. roi_back_x = max(0, x - 60)
  264. roi_back_w = min(1280, x + w + 60) - roi_back_x
  265. logger.info(f'Searching sword icon in narrowed area: {roi_back_x, roi_back_y, roi_back_w, roi_back_h}')
  266. matches = self.I_NORMAL_BATTLE_BUTTON.match_all(
  267. image=self.device.image,
  268. threshold=0.9,
  269. roi=[roi_back_x, roi_back_y, roi_back_w, roi_back_h]
  270. )
  271. if matches:
  272. distances = []
  273. for match in matches:
  274. # 这里假设 match[1], match[2] 是 x, y
  275. x_match = match[1] + match[3] / 2 # 战斗图标中心 X
  276. y_match = match[2] + match[4] / 2 # 战斗图标中心 Y
  277. # 这样能完美避开“距离很近但属于隔壁怪”的情况
  278. x_diff = abs(x_center - x_match)
  279. y_diff = abs(y_center - y_match)
  280. weighted_distance = (x_diff * 3) + y_diff
  281. distances.append((weighted_distance, match))
  282. # 按加权距离排序,取最正对着的一个
  283. distances.sort(key=lambda x: x[0], reverse=False)
  284. match = distances[0][1]
  285. roi_front = list(match[1:]) # x,y,w,h
  286. self.I_NORMAL_BATTLE_BUTTON.roi_front = roi_front
  287. logger.info(f"Target locked: sword at {roi_front} (aligned with UP icon)")
  288. return self.I_NORMAL_BATTLE_BUTTON
  289. # 没找到 UP 图标或对应战斗图标,返回 None 让外层逻辑去处理(滑动或退出)
  290. return None
  291. # 2. 如果是默认情况 (UpType.ALL),则只要有怪就打
  292. self.I_NORMAL_BATTLE_BUTTON.roi_back = (0, 0, 1279, 719)
  293. if self.appear(self.I_NORMAL_BATTLE_BUTTON):
  294. return self.I_NORMAL_BATTLE_BUTTON
  295. return None
  296. def activate_realm_raid(self, con_scrolls, con) -> None:
  297. # 判断是否开启突破票检测
  298. if not con_scrolls.scrolls_enable:
  299. return
  300. if self.appear(self.I_E_EXPLORATION_CLICK) and self.appear(self.I_EXP_CREATE_TEAM):
  301. cu, res, total = self.O_REALM_RAID_NUMBER1.ocr(self.device.image)
  302. else:
  303. cu, res, total = self.O_REALM_RAID_NUMBER.ocr(self.device.image)
  304. # 判断突破票数量
  305. if cu < con_scrolls.scrolls_threshold:
  306. return
  307. # 关闭加成
  308. if self.appear(self.I_RED_CLOSE):
  309. self.ui_click_until_disappear(self.I_RED_CLOSE)
  310. if self.appear(self.I_UI_CANCEL):
  311. self.ui_click_until_disappear(self.I_UI_CANCEL)
  312. if self.appear(self.I_UI_CANCEL_SAMLL):
  313. self.ui_click_until_disappear(self.I_UI_CANCEL_SAMLL)
  314. self.goto_page(page_main)
  315. if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
  316. self.open_buff()
  317. self.gold_50(is_open=False)
  318. self.gold_100(is_open=False)
  319. self.exp_50(is_open=False)
  320. self.exp_100(is_open=False)
  321. self.close_buff()
  322. # 设置下次执行行时间
  323. logger.info("RealmRaid and Exploration set_next_run !")
  324. next_run = datetime.now() + con_scrolls.scrolls_cd
  325. self.set_next_run(task='Exploration', success=False, finish=False, target=next_run)
  326. self.set_next_run(task='RealmRaid', success=False, finish=False, server=False, target=datetime.now())
  327. self.set_next_run(task='MemoryScrolls', success=False, finish=False, target=datetime.now())
  328. raise TaskEnd
  329. #
  330. def check_exit(self) -> bool:
  331. # True 表示要退出这个任务
  332. if self.minions_cnt >= self._config.exploration_config.minions_cnt:
  333. logger.info('Minions count is enough, exit')
  334. return True
  335. if datetime.now() - self.start_time >= self.limit_time:
  336. logger.info('Exploration time limit out')
  337. return True
  338. self.activate_realm_raid(self._config.scrolls, self._config.exploration_config)
  339. return False
  340. def quit_explore(self):
  341. logger.info('Quit explore')
  342. self.device.click_record_remove(self.S_SWIPE_BACKGROUND_RIGHT.name)
  343. boss_timer = Timer(15)
  344. boss_timer.start()
  345. # click_yellow_button = 0 #用于保证只点一次左上返回按钮,不要直接触发连点回到主界面
  346. while 1:
  347. self.screenshot()
  348. # 探索章节标题界面
  349. if self.appear(self.I_UI_BACK_YELLOW) and self.appear(self.I_E_EXPLORATION_CLICK):
  350. break
  351. # 探索大世界界面
  352. if self.appear(self.I_CHECK_EXPLORATION) and not self.appear(self.I_E_SETTINGS_BUTTON):
  353. break
  354. # 防止BOSS打完箱子刚落地,脚本就手快点退出了
  355. if self.appear_then_click(self.I_BATTLE_REWARD, interval=1.5):
  356. logger.info("Found battle reward during exit, picking it up.")
  357. boss_timer.reset()
  358. continue
  359. if boss_timer.reached():
  360. logger.warning('Exit timeout, force clicking back button')
  361. boss_timer.reset()
  362. self.click(self.I_UI_BACK_BLUE)
  363. continue
  364. if self.appear_then_click(self.I_E_EXIT_CONFIRM, interval=0.8):
  365. continue
  366. if self.appear_then_click(self.I_BACK_YOLLOW, interval=3.5):
  367. continue
  368. if self.appear(self.I_EXPLORATION_TITLE) or self.appear(self.I_CHECK_EXPLORATION):
  369. continue
  370. def _hook_special_reward(self) -> bool:
  371. if self.appear(self.I_STATISTICS) and not self.appear(self.I_REWARD) and not self.appear(self.I_WIN):
  372. if self.appear_then_click(self.I_CONFIRM_CLOSE_DIFF_SOUL):
  373. return True
  374. self.click(self.C_RANDOM_CLICK, interval=1.5)
  375. return False
  376. def fire(self, button) -> bool:
  377. self.ui_click_until_disappear(button, interval=3)
  378. self.screenshot()
  379. if (self.appear(self.I_E_SETTINGS_BUTTON) or
  380. self.appear(self.I_E_AUTO_ROTATE_ON) or
  381. self.appear(self.I_E_AUTO_ROTATE_OFF)):
  382. # 如果还在探索说明,这个是显示滑动导致挑战按钮不在范围内
  383. logger.warning('Fire button disappear, but still in exploration')
  384. return False
  385. self.run_general_battle(self._config.general_battle_config)
  386. self.minions_cnt += 1
  387. return True
  388. def wait_world_stable(self) -> bool:
  389. """
  390. # 打开右边箭头 and https://github.com/runhey/OnmyojiAutoScript/pull/1589/
  391. https://github.com/runhey/OnmyojiAutoScript/issues/1588
  392. @return:
  393. """
  394. while 1:
  395. scene = self.get_current_scene(reuse_screenshot=False)
  396. if scene == Scene.WORLD and self.appear(self.I_EXP_ARROW_RIGHT):
  397. return True
  398. if scene == Scene.ENTRANCE:
  399. logger.warning('World scene unstable, possibly transient frame after paper doll collection')
  400. return False
  401. if self.appear_then_click(self.I_EXP_ARROW_LEFT, interval=2):
  402. continue
  403. if __name__ == "__main__":
  404. from module.config.config import Config
  405. from module.device.device import Device
  406. config = Config('oas1')
  407. device = Device(config)
  408. t = BaseExploration(config, device)
  409. t.screenshot()
  410. # IMAGE_FILE = r"C:\Users\萌萌哒\Desktop\QQ20240818-163854.png"
  411. # image = load_image(IMAGE_FILE)
  412. # t.device.image = image
  413. while 1:
  414. # print(t.search_up_fight(UpType.EXP))
  415. t.screenshot()
  416. print(t.get_current_scene())
  417. from PIL import Image
  418. # Image.fromarray(t.device.image.astype(np.uint8)).show()