game_ui.py 15 KB

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