base.py 20 KB

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