script_task.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import random
  5. from datetime import datetime, timedelta, time
  6. import time as time_mode
  7. from tasks.base_task import BaseTask
  8. from tasks.Component.GeneralBattle.general_battle import GeneralBattle
  9. from tasks.AreaBoss.assets import AreaBossAssets
  10. from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
  11. from tasks.Component.BaseActivity.base_activity import BaseActivity
  12. from tasks.Component.BaseActivity.config_activity import ApMode
  13. from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
  14. from tasks.GameUi.page import page_main, page_shikigami_records
  15. from tasks.GameUi.game_ui import GameUi
  16. from module.logger import logger
  17. from module.exception import TaskEnd
  18. from module.base.protect import random_sleep
  19. import cv2
  20. import numpy as np
  21. from module.atom.ocr import RuleOcr
  22. class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
  23. def run(self) -> None:
  24. config = self.config.activity_shikigami
  25. self.limit_time: timedelta = config.general_climb.limit_time
  26. if isinstance(self.limit_time, time):
  27. self.limit_time = timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
  28. seconds=self.limit_time.second)
  29. self.limit_count = config.general_climb.limit_count
  30. if config.switch_soul_config.enable:
  31. self.ui_get_current_page()
  32. self.ui_goto(page_shikigami_records)
  33. self.run_switch_soul(config.switch_soul_config.switch_group_team)
  34. if config.switch_soul_config.enable_switch_by_name:
  35. self.ui_get_current_page()
  36. self.ui_goto(page_shikigami_records)
  37. self.run_switch_soul_by_name(
  38. config.switch_soul_config.group_name,
  39. config.switch_soul_config.team_name
  40. )
  41. self.ui_get_current_page()
  42. self.ui_goto(page_main)
  43. # 某些活动需要开启御魂加成
  44. # self.open_buff()
  45. # self.soul(is_open=True)
  46. # self.close_buff()
  47. self.home_main()
  48. # 选择是游戏的体力还是活动的体力
  49. current_ap = config.general_climb.ap_mode
  50. self.switch(current_ap)
  51. # 设定是否锁定阵容
  52. if config.general_battle.lock_team_enable:
  53. logger.info("Lock team")
  54. while 1:
  55. self.screenshot()
  56. if self.appear_then_click(self.I_UNLOCK, interval=1):
  57. continue
  58. if self.appear(self.I_LOCK):
  59. break
  60. else:
  61. logger.info("Unlock team")
  62. while 1:
  63. self.screenshot()
  64. if self.appear_then_click(self.I_LOCK, interval=1):
  65. continue
  66. if self.appear(self.I_UNLOCK):
  67. break
  68. # 流程应该是 在页面处:
  69. # 1. 判定计数是否超了,时间是否超了
  70. # 2. 如果是消耗活动体力,判定活动体力是否足够 如果是消耗一般的体力,判定一般体力是否足够
  71. # 3. 如果开启买体力,就买体力
  72. # 4. 如果开启了切换到游戏体力,就切换
  73. while 1:
  74. # 1
  75. if self.limit_time is not None and self.limit_time + self.start_time < datetime.now():
  76. logger.info("Time out")
  77. break
  78. if self.current_count >= self.limit_count:
  79. logger.info("Count out")
  80. break
  81. # 2
  82. self.wait_until_appear(self.I_FIRE)
  83. is_remain = self.check_ap_remain(current_ap)
  84. # 如果没有剩余了且这个时候是体力,就退出活动
  85. if not is_remain and current_ap == ApMode.AP_GAME:
  86. logger.info("Game ap out")
  87. break
  88. # 如果不是那就切换到体力
  89. elif not is_remain and current_ap == ApMode.AP_ACTIVITY:
  90. if config.general_climb.activity_toggle:
  91. logger.info("Activity ap out and switch to game ap")
  92. current_ap = ApMode.AP_GAME
  93. self.switch(current_ap)
  94. else:
  95. logger.info("Activity ap out")
  96. break
  97. # 随机休息
  98. if config.general_climb.random_sleep:
  99. random_sleep(probability=0.2)
  100. # 点击战斗
  101. logger.info("Click battle")
  102. while 1:
  103. self.screenshot()
  104. if self.appear_then_click(self.I_FIRE, interval=2):
  105. continue
  106. if not self.appear(self.I_FIRE):
  107. break
  108. if self.appear_then_click(self.I_C_CONFIRM1, interval=0.6):
  109. continue
  110. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  111. continue
  112. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  113. continue
  114. if self.appear_then_click(self.I_N_CONFIRM, interval=1):
  115. continue
  116. if self.run_general_battle(config=config.general_battle):
  117. logger.info("General battle success")
  118. self.main_home()
  119. # 某些活动需要开启御魂加成
  120. # self.open_buff()
  121. # self.soul(is_open=False)
  122. # self.close_buff()
  123. if config.general_climb.active_souls_clean:
  124. self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
  125. self.set_next_run(task="ActivityShikigami", success=True)
  126. raise TaskEnd
  127. def home_main(self) -> bool:
  128. """
  129. 从庭院到活动的爬塔界面,统一入口
  130. :return:
  131. """
  132. logger.hr("Enter Shikigami", 2)
  133. while 1:
  134. self.screenshot()
  135. self.C_RANDOM_LEFT.name = "BATTLE_RANDOM"
  136. self.C_RANDOM_RIGHT.name = "BATTLE_RANDOM"
  137. self.C_RANDOM_TOP.name = "BATTLE_RANDOM"
  138. self.C_RANDOM_BOTTOM.name = "BATTLE_RANDOM"
  139. if self.appear(self.I_FIRE):
  140. break
  141. if self.appear_then_click(self.I_SHI, interval=1):
  142. continue
  143. if self.ocr_appear_click(self.O_ENTRY_ACTIVITY, interval=1):
  144. continue
  145. if self.appear_then_click(self.I_TOGGLE_BUTTON, interval=3):
  146. time_mode.sleep(2)
  147. continue
  148. if self.appear_then_click(self.I_SKIP_BUTTON, interval=1.5):
  149. continue
  150. # 如果出现了 “获得奖励”
  151. reward_click = random.choice([self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM])
  152. if self.appear_then_click(self.I_UI_REWARD, action=reward_click, interval=1.3):
  153. continue
  154. if self.appear_then_click(self.I_RED_EXIT, interval=1.5):
  155. continue
  156. if self.appear_then_click(self.I_BATTLE, interval=2):
  157. continue
  158. def main_home(self) -> bool:
  159. """
  160. 从活动的爬塔界面到庭院
  161. :return:
  162. """
  163. logger.hr("Exit Shikigami", 2)
  164. while 1:
  165. self.screenshot()
  166. if self.appear(self.I_SHI):
  167. break
  168. if self.appear_then_click(self.I_UI_BACK_RED, interval=2):
  169. continue
  170. if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=2):
  171. continue
  172. if self.appear_then_click(self.I_BACK_GREEN, interval=2):
  173. continue
  174. if self.appear_then_click(self.I_EXIT, interval=2.2, threshold=0.6):
  175. continue
  176. def check_ap_remain(self, current_ap: ApMode) -> bool:
  177. """
  178. 检查体力是否足够
  179. :return: 如何还有体力,返回True,否则返回False
  180. """
  181. self.screenshot()
  182. if current_ap == ApMode.AP_ACTIVITY:
  183. res: int = self.O_REMAIN_AP_ACTIVITY2.ocr_digit(
  184. self._prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP_ACTIVITY2))
  185. if res <= 0:
  186. logger.warning(f'Activity ap {res} not enough')
  187. return False
  188. return True
  189. # cu, res, total = self.O_REMAIN_AP_ACTIVITY.ocr(image=self.device.image)
  190. # if cu == 0 and cu + res == total:
  191. # logger.warning("Activity ap not enough")
  192. # return False
  193. # return True
  194. elif current_ap == ApMode.AP_GAME:
  195. cu: int = self.O_REMAIN_AP.ocr_digit(self._prepare_image_for_ocr(self.device.image,asset=self.O_REMAIN_AP))
  196. if cu > 0:
  197. logger.warning(f'Game ap {cu} more than 0')
  198. return True
  199. logger.warning(f'Game ap not enough: {cu}')
  200. return False
  201. # cu, res, total = self.O_REMAIN_AP.ocr(image=self.device.image)
  202. # if cu == total and cu + res == total:
  203. # if cu > total:
  204. # logger.warning(f'Game ap {cu} more than total {total}')
  205. # return True
  206. # logger.warning(f'Game ap not enough: {cu}')
  207. # return False
  208. #
  209. # return True
  210. def switch(self, current_ap: ApMode) -> None:
  211. """
  212. 切换体力
  213. :param current_ap:
  214. :return:
  215. """
  216. if current_ap == ApMode.AP_ACTIVITY:
  217. logger.info("Select activity ap")
  218. while 1:
  219. self.screenshot()
  220. if self.appear(self.I_AP_ACTIVITY):
  221. break
  222. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
  223. continue
  224. if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
  225. continue
  226. if self.appear(self.I_AP, interval=1):
  227. self.appear_then_click(self.I_SWITCH, interval=2) # 点击切换
  228. else:
  229. logger.info("Select game ap")
  230. while 1:
  231. self.screenshot()
  232. if self.appear(self.I_AP):
  233. break
  234. if self.appear(self.I_AP_ACTIVITY, interval=1):
  235. self.appear_then_click(self.I_SWITCH, interval=2)
  236. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  237. # 重写,不出现达摩版本999专用
  238. self.device.stuck_record_add('BATTLE_STATUS_S')
  239. self.device.click_record_clear()
  240. logger.info("Start battle process")
  241. self.C_RANDOM_LEFT.name = "BATTLE_RANDOM"
  242. self.C_RANDOM_RIGHT.name = "BATTLE_RANDOM"
  243. self.C_RANDOM_TOP.name = "BATTLE_RANDOM"
  244. self.C_RANDOM_BOTTOM.name = "BATTLE_RANDOM"
  245. click_count = 0
  246. while 1:
  247. self.screenshot()
  248. # 如果出现了 “获得奖励”
  249. reward_click = random.choice([self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM])
  250. if self.appear_then_click(self.I_UI_REWARD, action=reward_click, interval=1.3):
  251. click_count += 1
  252. continue
  253. # 如果出现了 “鼓”
  254. if self.appear(self.I_WIN) or click_count >= 1:
  255. logger.info("Win")
  256. while 1:
  257. self.screenshot()
  258. if not self.appear(self.I_WIN):
  259. break
  260. if self.appear_then_click(self.I_WIN, action=self.C_RANDOM_ALL, interval=1.1):
  261. continue
  262. if self.appear(self.I_FIRE):
  263. return True
  264. # 失败 -> 正常人不会失败
  265. if self.appear(self.I_FALSE):
  266. logger.warning('False battle')
  267. self.ui_click_until_disappear(self.I_FALSE)
  268. return False
  269. # 如果开启战斗过程随机滑动
  270. if random_click_swipt_enable:
  271. self.random_click_swipt()
  272. def _prepare_image_for_ocr(self, image: np.ndarray, asset: RuleOcr) -> np.ndarray:
  273. image_copy = image.copy()
  274. x, y, w, h = asset.roi
  275. roi_to_process = image_copy[y:y + h, x:x + w]
  276. if len(roi_to_process.shape) == 3:
  277. gray_image = cv2.cvtColor(roi_to_process, cv2.COLOR_BGR2GRAY)
  278. else:
  279. gray_image = roi_to_process
  280. # 自适应二值化
  281. _, binary_norm = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  282. _, binary_inv = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
  283. if cv2.countNonZero(binary_norm) < cv2.countNonZero(binary_inv):
  284. binary_correct = binary_norm
  285. else:
  286. binary_correct = binary_inv
  287. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 1))
  288. dilated_image = cv2.dilate(binary_correct, kernel, iterations=1)
  289. # 找轮廓
  290. contours, _ = cv2.findContours(dilated_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  291. processed_roi_content = None
  292. if contours:
  293. all_points = np.concatenate(contours, axis=0)
  294. bx, by, bw, bh = cv2.boundingRect(all_points)
  295. processed_roi_content = binary_correct[by:by + bh, bx:bx + bw]
  296. centered_roi = np.full((h, w), 255, dtype=np.uint8) # 255代表白色
  297. if processed_roi_content is not None:
  298. content_h, content_w = processed_roi_content.shape
  299. if content_h <= h and content_w <= w:
  300. # 计算居中粘贴的位置,放到中间
  301. start_y = (h - content_h) // 2
  302. start_x = (w - content_w) // 2
  303. paste_area = centered_roi[start_y:start_y + content_h, start_x:start_x + content_w]
  304. paste_area[processed_roi_content == 255] = 0
  305. else:
  306. logger.warning(f"Content for asset '{asset.name}' is larger than ROI. Skipping centering.")
  307. # 内容过大,直接使用原始二值图的反转作为结果
  308. centered_roi = cv2.bitwise_not(binary_correct)
  309. else:
  310. logger.warning(f"No content found in ROI for asset: {asset.name}. ROI will be blank.")
  311. processed_roi_bgr = cv2.cvtColor(centered_roi, cv2.COLOR_GRAY2BGR)
  312. image_copy[y:y + h, x:x + w] = processed_roi_bgr
  313. return image_copy
  314. """
  315. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  316. # 重写,出现达摩版本月度常用
  317. self.device.stuck_record_add('BATTLE_STATUS_S')
  318. self.device.click_record_clear()
  319. logger.info("Start battle process")
  320. self.C_RANDOM_LEFT.name = "BATTLE_RANDOM"
  321. self.C_RANDOM_RIGHT.name = "BATTLE_RANDOM"
  322. self.C_RANDOM_TOP.name = "BATTLE_RANDOM"
  323. self.C_RANDOM_BOTTOM.name = "BATTLE_RANDOM"
  324. click_count = 0
  325. while 1:
  326. self.screenshot()
  327. # 如果出现了 “鼓”
  328. if self.appear_then_click(self.I_WIN, interval=2.3):
  329. logger.info("Win")
  330. continue
  331. # 出现 “魂” 和 紫蛇皮
  332. if self.appear(self.I_REWARD):
  333. logger.info('Win battle')
  334. self.wait_until_appear(self.I_REWARD_PURPLE_SNAKE_SKIN, wait_time=5)
  335. while 1:
  336. self.screenshot()
  337. appear_reward = self.appear(self.I_REWARD)
  338. appear_reward_purple_snake_skin = self.appear(self.I_REWARD_PURPLE_SNAKE_SKIN)
  339. if not appear_reward and not appear_reward_purple_snake_skin and click_count >= 1:
  340. break
  341. if appear_reward or appear_reward_purple_snake_skin:
  342. reward_click = random.choice(
  343. [self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP])
  344. self.click(reward_click, interval=1.8)
  345. click_count += 1
  346. continue
  347. return True
  348. # 失败 -> 正常人不会失败
  349. if self.appear(self.I_FALSE):
  350. logger.warning('False battle')
  351. self.ui_click_until_disappear(self.I_FALSE)
  352. return False
  353. # 如果开启战斗过程随机滑动
  354. if random_click_swipt_enable:
  355. self.random_click_swipt()
  356. """
  357. if __name__ == '__main__':
  358. from module.config.config import Config
  359. from module.device.device import Device
  360. c = Config('oas1')
  361. d = Device(c)
  362. t = ScriptTask(c, d)
  363. t.run()