game_ui.py 13 KB

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