game_ui.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import time
  5. from datetime import datetime
  6. from time import sleep
  7. import random
  8. from collections import deque
  9. from module.atom.gif import RuleGif
  10. from module.atom.image import RuleImage
  11. from module.atom.list import RuleList
  12. from module.atom.ocr import RuleOcr
  13. from module.base.decorator import run_once
  14. from module.base.timer import Timer
  15. from module.exception import (GameNotRunningError, GamePageUnknownError)
  16. from module.logger import logger
  17. from tasks.GameUi.assets import GameUiAssets
  18. from tasks.GameUi.page import *
  19. from tasks.Restart.assets import RestartAssets
  20. from tasks.SixRealms.assets import SixRealmsAssets
  21. from tasks.base_task import BaseTask
  22. from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
  23. class GameUi(BaseTask, GameUiAssets):
  24. ui_current: Page = None
  25. ui_pages = [
  26. # 登录
  27. page_login,
  28. # 主页
  29. page_main, page_summon, page_exploration, page_town,
  30. # 探索的
  31. page_awake_zones, page_soul_zones, page_realm_raid, page_goryou_realm, page_delegation,
  32. page_secret_zones, page_area_boss, page_heian_kitan, page_six_gates, page_bondling_fairyland,
  33. page_kekkai_toppa,
  34. # 町中的
  35. page_duel, page_demon_encounter, page_hunt, page_hunt_kirin, page_draft_duel, page_hyakkisen,
  36. # 庭院里面的
  37. page_shikigami_records, page_onmyodo, page_friends, page_daily, page_mall, page_guild, page_team,
  38. page_collection, page_act_list,
  39. # 爬塔活动
  40. page_act_list_climb_act, page_climb_act, page_climb_act_2, page_climb_act_pass, page_climb_act_ap,
  41. page_climb_act_boss, page_climb_act_buff, page_climb_act_ap100,
  42. # 战斗
  43. page_battle_auto, page_battle_hand, page_reward, page_failed
  44. ]
  45. ui_close = [GameUiAssets.I_BACK_MALL, GeneralBattleAssets.I_CONFIRM,
  46. BaseTask.I_UI_BACK_RED, BaseTask.I_UI_BACK_YELLOW, BaseTask.I_UI_BACK_BLUE,
  47. GameUiAssets.I_BACK_FRIENDS, GameUiAssets.I_BACK_DAILY,
  48. GameUiAssets.I_REALM_RAID_GOTO_EXPLORATION,
  49. GameUiAssets.I_SIX_GATES_GOTO_EXPLORATION, SixRealmsAssets.I_EXIT_SIXREALMS,
  50. ActivityShikigamiAssets.I_SKIP_BUTTON, ActivityShikigamiAssets.I_RED_EXIT,
  51. ActivityShikigamiAssets.I_RED_EXIT_2]
  52. def home_explore(self) -> bool:
  53. """
  54. 使用ocr识别到探索按钮并点击
  55. :return:
  56. """
  57. while 1:
  58. self.screenshot()
  59. if self.ocr_appear_click(self.O_HOME_EXPLORE, interval=2):
  60. continue
  61. if self.appear(self.I_BACK_BLUE, threshold=0.6):
  62. break
  63. logger.info(f'Click {self.O_HOME_EXPLORE.name}')
  64. return True
  65. def explore_home(self) -> bool:
  66. """
  67. :return:
  68. """
  69. while 1:
  70. self.screenshot()
  71. if self.appear_then_click(self.I_BACK_BLUE, threshold=0.6, interval=2):
  72. continue
  73. if self.appear(self.I_HOME_SHIKIKAMI, threshold=0.6):
  74. break
  75. logger.info(f'Click {self.I_HOME_SHIKIKAMI.name}')
  76. return True
  77. def ui_page_appear(self, page: Page, skip_first_screenshot: bool = True, interval: float = random.uniform(0.5, 1)):
  78. """
  79. 判断当前页面是否为page
  80. """
  81. if interval:
  82. interval_timer = Timer(interval).start()
  83. interval_timer.wait()
  84. if not skip_first_screenshot:
  85. self.screenshot()
  86. if isinstance(page.check_button, list):
  87. for button in page.check_button:
  88. if self.appear(button):
  89. return True
  90. return False
  91. return self.appear(page.check_button)
  92. def ui_wait_until_appear(self, page: Page, timeout: float = 3, interval: float = 0.5,
  93. skip_first_screenshot: bool = True) -> bool:
  94. """
  95. 等待页面出现
  96. """
  97. logger.info(f'Waiting for {page}')
  98. timeout_timer = Timer(timeout).start()
  99. interval_timer = Timer(interval).start()
  100. while not timeout_timer.reached():
  101. if self.ui_page_appear(page, skip_first_screenshot):
  102. return True
  103. skip_first_screenshot = False
  104. interval_timer.wait().reset()
  105. return False
  106. def ensure_scroll_open(self):
  107. """
  108. 判断庭院界面卷轴是否打开
  109. """
  110. return self.appear(RestartAssets.I_LOGIN_SCROOLL_CLOSE)
  111. def ensure_button_execute(self, button):
  112. """
  113. 确保button执行
  114. """
  115. if isinstance(button, RuleImage) and self.appear(button):
  116. return True
  117. elif callable(button) and button():
  118. return True
  119. else:
  120. return False
  121. def ui_get_current_page(self, skip_first_screenshot=True) -> Page:
  122. """
  123. 获取当前页面
  124. :param skip_first_screenshot:
  125. :return:
  126. """
  127. logger.info("UI get current page")
  128. @run_once
  129. def app_check():
  130. if not self.device.app_is_running():
  131. raise GameNotRunningError("Game not running")
  132. @run_once
  133. def minicap_check():
  134. if self.config.script.device.control_method == "uiautomator2":
  135. self.device.uninstall_minicap()
  136. @run_once
  137. def rotation_check():
  138. self.device.get_orientation()
  139. timeout = Timer(10, count=20).start()
  140. while 1:
  141. if skip_first_screenshot:
  142. skip_first_screenshot = False
  143. if not hasattr(self.device, "image") or self.device.image is None:
  144. self.screenshot()
  145. else:
  146. self.screenshot()
  147. # 如果20S还没有到底,那么就抛出异常
  148. if timeout.reached():
  149. break
  150. # Known pages
  151. for page in self.ui_pages:
  152. if not page.check_button:
  153. continue
  154. if self.ui_page_appear(page=page, interval=None):
  155. logger.attr("UI", page.name)
  156. self.ui_current = page
  157. if page == page_main and self.ensure_scroll_open():
  158. self.ui_click_until_disappear(RestartAssets.I_LOGIN_SCROOLL_CLOSE)
  159. return page
  160. # Try to close unknown page
  161. for close in self.ui_close:
  162. if self.appear_then_click(close, interval=1.5):
  163. logger.info('Trying to switch to supported page')
  164. timeout = Timer(10, count=20).start()
  165. app_check()
  166. minicap_check()
  167. rotation_check()
  168. # Unknown page, need manual switching
  169. logger.warning("Unknown ui page")
  170. logger.attr("EMULATOR__SCREENSHOT_METHOD", self.config.script.device.screenshot_method)
  171. logger.attr("EMULATOR__CONTROL_METHOD", self.config.script.device.control_method)
  172. logger.warning("Starting from current page is not supported")
  173. logger.warning(f"Supported page: {[str(page) for page in self.ui_pages]}")
  174. logger.warning('Supported page: Any page with a "HOME" button on the upper-right')
  175. logger.critical("Please switch to a supported page before starting oas")
  176. raise GamePageUnknownError
  177. def ui_button_interval_reset(self, button):
  178. """
  179. Reset interval of some button to avoid mistaken clicks
  180. Args:
  181. button (Button):
  182. """
  183. if getattr(button, 'name', None) and button.name in self.interval_timer:
  184. self.interval_timer[button.name].reset()
  185. def build_reverse_path_dict(self, destination: Page) -> dict[Page, list[Page]]:
  186. """
  187. 构建从每个页面到目标页面的最短路径(反向 BFS)
  188. Returns:
  189. dict[Page, list[Page]] -> {start_page: [page1, ...destinationPage], ...}
  190. """
  191. paths = {destination: [destination]}
  192. queue = deque([destination])
  193. while queue:
  194. cur = queue.popleft()
  195. for page in self.ui_pages:
  196. if page not in paths and cur in page.links:
  197. # page -> cur
  198. paths[page] = [page] + paths[cur]
  199. queue.append(page)
  200. return paths
  201. def build_reverse_paths(self, destination: Page) -> list[tuple[Page, list[Page]]]:
  202. """
  203. 构建从每个页面到目标页面的最短路径(反向 BFS)
  204. 路径从短到长排序
  205. Returns:
  206. [(start_page, [page1, ...destinationPage]), ...]
  207. """
  208. paths = self.build_reverse_path_dict(destination)
  209. # 转换成列表并按路径长度排序, 短到长
  210. sorted_paths = sorted(paths.items(), key=lambda kv: len(kv[1]))
  211. return sorted_paths
  212. def ui_goto(self, destination: Page, confirm_wait=0, skip_first_screenshot=True, timeout: int = 60):
  213. """
  214. Args:
  215. destination (Page):
  216. confirm_wait:
  217. skip_first_screenshot:
  218. :return: find destination page or timeout reached
  219. """
  220. logger.hr(f"UI goto {destination}")
  221. # 初始化
  222. timeout_timer = Timer(timeout).start()
  223. confirm_timer = Timer(confirm_wait, count=int(confirm_wait // 0.5)).start()
  224. close_unknown_timer = Timer(3).start()
  225. # 构建路径映射
  226. path_dict = self.build_reverse_path_dict(destination)
  227. while not timeout_timer.reached():
  228. # 已经在目标页面
  229. if self.ui_page_appear(destination, skip_first_screenshot):
  230. if confirm_timer.reached():
  231. logger.info(f'Page arrive: {destination}')
  232. return True
  233. continue
  234. skip_first_screenshot = False
  235. # 尝试关闭未知页面
  236. if close_unknown_timer.reached_and_reset():
  237. logger.warning('Trying to switch to supported page')
  238. for close in self.ui_close:
  239. if self.appear_then_click(close, interval=1.5):
  240. logger.info(f'[{close_unknown_timer.current():.1f}s]Click {close} on {self.ui_current} success')
  241. confirm_timer.reset()
  242. path = path_dict.get(self.ui_current, None)
  243. # 找不到路径则重新获取页面重试
  244. if not path:
  245. self.ui_get_current_page(skip_first_screenshot)
  246. continue
  247. logger.info(f"Current page: {self.ui_current}. Following shortest path:")
  248. show_paths: str = ' -> '.join([p.name for p in path])
  249. logger.info(f"{show_paths}")
  250. # 遍历路径
  251. if self._execute_path(path, timeout_timer) and confirm_timer.reached():
  252. return True
  253. else:
  254. logger.error(f'Cannot goto page[{destination}], timeout[{timeout}s] reached')
  255. return False
  256. def _execute_path(self, path: list, timeout_timer):
  257. """
  258. 执行路径
  259. :param path: currentPage,page1,page2,...,destinationPage
  260. :param timeout_timer: 超时定时器
  261. :return: currentPage==destinationPage
  262. """
  263. for i in range(len(path) - 1):
  264. current_page, next_page = path[i], path[i + 1]
  265. if timeout_timer.reached():
  266. return False
  267. # 当前页不等于路径中对应页, 尝试下一页
  268. if self.ui_current != current_page:
  269. continue
  270. # 执行附加操作
  271. if current_page.additional:
  272. for button in current_page.additional:
  273. if self.appear_then_operate(button, skip_first_screenshot=False, interval=random.uniform(0.4, 0.6)):
  274. logger.info(f'Page {current_page} additional {button} clicked')
  275. logger.info(f'Page switch: {current_page} -> {next_page}')
  276. # 获取页面跳转操作
  277. button = current_page.links.get(next_page)
  278. if not button:
  279. logger.warning(f"No link from {current_page} to {next_page}")
  280. continue
  281. # 跳转页面
  282. max_wait_timer = Timer(5).start()
  283. while not max_wait_timer.reached():
  284. if timeout_timer.reached():
  285. return False
  286. if self.appear_then_operate(button, skip_first_screenshot=False):
  287. break
  288. logger.warning(f"[{max_wait_timer.current():.1f}s]Failed click {button} on {current_page}, retry...")
  289. sleep(0.3)
  290. else:
  291. self.ui_get_current_page(skip_first_screenshot=False)
  292. # 当前页面不是对应路径的页面, 则尝试下一个页面
  293. if self.ui_current != current_page:
  294. continue
  295. max_wait_timer.reset()
  296. while not max_wait_timer.reached():
  297. if timeout_timer.reached():
  298. return False
  299. if self.ui_wait_until_appear(next_page, timeout=1.5, interval=random.uniform(0.4, 0.8),
  300. skip_first_screenshot=False):
  301. logger.info(f'[{max_wait_timer.current():.1f}s]Page arrived {next_page}')
  302. self.ui_current = next_page
  303. break
  304. else:
  305. # 重新获取当前页
  306. self.ui_get_current_page(skip_first_screenshot=False)
  307. return self.ui_current == path[-1]
  308. def appear_then_operate(self, target: RuleList | RuleImage | RuleGif | RuleOcr | RuleClick,
  309. interval: float = random.uniform(0.6, 1.2), skip_first_screenshot: bool = True):
  310. self.ui_button_interval_reset(target)
  311. interval_timer = Timer(interval).start()
  312. interval_timer.wait()
  313. if not skip_first_screenshot:
  314. self.screenshot()
  315. if isinstance(target, RuleList):
  316. return self.list_appear_click(target)
  317. if isinstance(target, (RuleImage, RuleGif)):
  318. return self.appear_then_click(target)
  319. if isinstance(target, RuleOcr):
  320. return self.ocr_appear_click(target)
  321. if isinstance(target, RuleClick):
  322. return self.click(target)
  323. # ------------------------------------------------------------------------------------------------------------------
  324. # 下面的这些是一些特殊的页面,需要额外处理
  325. # ------------------------------------------------------------------------------------------------------------------
  326. def main_goto_daily(self):
  327. """
  328. 无法直接一步到花合战,需要先到主页,然后再到花合战
  329. :return:
  330. """
  331. while 1:
  332. self.screenshot()
  333. if self.appear(self.I_CHECK_DAILY):
  334. break
  335. if self.appear_then_click(self.I_MAIN_GOTO_DAILY, interval=1):
  336. continue
  337. if self.ocr_appear_click(self.O_CLICK_CLOSE_1, interval=1):
  338. continue
  339. if self.ocr_appear_click(self.O_CLICK_CLOSE_2, interval=1):
  340. continue
  341. logger.info('Page arrive: Daily')
  342. time.sleep(1)
  343. return
  344. if __name__ == '__main__':
  345. from module.config.config import Config
  346. from module.device.device import Device
  347. c = Config('oas2')
  348. d = Device(c)
  349. game = GameUi(config=c, device=d)
  350. game.ui_get_current_page()
  351. game.ui_goto(page_main)