game_ui.py 13 KB

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