game_ui.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 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. # End
  137. # 如果20S还没有到底,那么就抛出异常
  138. if timeout.reached():
  139. break
  140. # Known pages
  141. for page in self.ui_pages:
  142. if page.check_button is None:
  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. # Unknown page but able to handle
  156. # logger.info("Unknown ui page")
  157. # if self.appear_then_click(GOTO_MAIN, offset=(30, 30), interval=2) or self.ui_additional():
  158. # timeout.reset()
  159. # continue
  160. app_check()
  161. minicap_check()
  162. rotation_check()
  163. # Unknown page, need manual switching
  164. logger.warning("Unknown ui page")
  165. logger.attr("EMULATOR__SCREENSHOT_METHOD", self.config.script.device.screenshot_method)
  166. logger.attr("EMULATOR__CONTROL_METHOD", self.config.script.device.control_method)
  167. logger.warning("Starting from current page is not supported")
  168. logger.warning(f"Supported page: {[str(page) for page in self.ui_pages]}")
  169. logger.warning('Supported page: Any page with a "HOME" button on the upper-right')
  170. logger.critical("Please switch to a supported page before starting oas")
  171. raise GamePageUnknownError
  172. def ui_button_interval_reset(self, button):
  173. """
  174. Reset interval of some button to avoid mistaken clicks
  175. Args:
  176. button (Button):
  177. """
  178. pass
  179. def ui_goto(self, destination: Page, confirm_wait=0, skip_first_screenshot=True, timeout: int = 45):
  180. """
  181. Args:
  182. destination (Page):
  183. confirm_wait:
  184. skip_first_screenshot:
  185. :return: find destination page or timeout reached
  186. """
  187. # Reset connection
  188. for page in self.ui_pages:
  189. page.parent = None
  190. # Create connection
  191. visited = [destination]
  192. visited = set(visited)
  193. # 广度优先搜索
  194. while 1:
  195. new = visited.copy()
  196. for page in visited:
  197. for link in self.ui_pages:
  198. if link in visited:
  199. continue
  200. if page in link.links:
  201. link.parent = page
  202. new.add(link)
  203. # 没有新的页面加入,说明已经遍历完毕
  204. if len(new) == len(visited):
  205. break
  206. visited = new
  207. timeout_timer = Timer(timeout).start()
  208. def dfs(current_page: Page) -> bool:
  209. if current_page is None:
  210. return False
  211. if current_page == destination:
  212. return True
  213. if timeout_timer.reached():
  214. return False
  215. # wait current page
  216. self.ui_wait_until_appear(current_page)
  217. logger.info(f'Page switch: {current_page} -> {current_page.parent}')
  218. # current page additional
  219. if current_page.additional and isinstance(current_page.additional, list):
  220. for button in current_page.additional:
  221. if ((isinstance(button, RuleClick) and self.click(button)) or
  222. self.appear_then_click(button, interval=0.6) or
  223. (isinstance(button, RuleOcr) and self.ocr_appear_click(button, interval=2))):
  224. logger.info(f'Page {current_page} AB {button} clicked')
  225. # to next page
  226. button = current_page.links[current_page.parent]
  227. if ((isinstance(button, RuleList) and self.list_appear_click(button)) or
  228. (isinstance(button, RuleClick) and self.click(button)) or
  229. self.appear_then_click(button, interval=2) or
  230. (isinstance(button, RuleOcr) and self.ocr_appear_click(button, interval=2))):
  231. self.ui_button_interval_reset(button)
  232. confirm_timer.reset()
  233. return dfs(current_page.parent)
  234. return False
  235. logger.hr(f"UI goto {destination}")
  236. confirm_timer = Timer(confirm_wait, count=int(confirm_wait // 0.5)).start()
  237. try_close_unknown_timer = Timer(3).start()
  238. while 1:
  239. if skip_first_screenshot:
  240. skip_first_screenshot = False
  241. else:
  242. self.screenshot()
  243. # Destination page
  244. if self.ui_page_appear(destination):
  245. if confirm_timer.reached():
  246. logger.info(f'Page arrive: {destination}')
  247. break
  248. else:
  249. confirm_timer.reset()
  250. # 超时退出
  251. if timeout_timer.reached():
  252. logger.error(f'Cannot goto page[{destination}], timeout[{timeout}s] reached')
  253. break
  254. # Try to close unknown page every 3 seconds
  255. if try_close_unknown_timer.reached():
  256. for close in self.ui_close:
  257. if self.appear_then_click(close, interval=1.5):
  258. logger.warning('Trying to switch to supported page')
  259. try_close_unknown_timer.reset()
  260. # Other pages
  261. fined = False
  262. for page in visited:
  263. if page.check_button is None or not self.ui_page_appear(page):
  264. continue
  265. fined = dfs(page)
  266. if fined:
  267. break
  268. if fined:
  269. continue
  270. sleep(0.5)
  271. # Reset connection
  272. for page in self.ui_pages:
  273. page.parent = None
  274. # ------------------------------------------------------------------------------------------------------------------
  275. # 下面的这些是一些特殊的页面,需要额外处理
  276. # ------------------------------------------------------------------------------------------------------------------
  277. def main_goto_daily(self):
  278. """
  279. 无法直接一步到花合战,需要先到主页,然后再到花合战
  280. :return:
  281. """
  282. while 1:
  283. self.screenshot()
  284. if self.appear(self.I_CHECK_DAILY):
  285. break
  286. if self.appear_then_click(self.I_MAIN_GOTO_DAILY, interval=1):
  287. continue
  288. if self.ocr_appear_click(self.O_CLICK_CLOSE_1, interval=1):
  289. continue
  290. if self.ocr_appear_click(self.O_CLICK_CLOSE_2, interval=1):
  291. continue
  292. logger.info('Page arrive: Daily')
  293. time.sleep(1)
  294. return
  295. if __name__ == '__main__':
  296. from module.config.config import Config
  297. from module.device.device import Device
  298. c = Config('oas2')
  299. d = Device(c)
  300. game = GameUi(config=c, device=d)
  301. game.ui_get_current_page()
  302. game.ui_goto(page_main)