game_ui.py 16 KB

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