base.py 18 KB

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