base.py 19 KB

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