base.py 20 KB

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