general_battle.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import time
  5. import random
  6. import difflib
  7. from time import sleep
  8. import cv2
  9. from module.base.timer import Timer
  10. from module.config.utils import convert_to_underscore
  11. from module.base.utils import get_color, color_similar
  12. from tasks.base_task import BaseTask
  13. from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GreenMarkEnum, GeneralBattleConfig
  14. from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
  15. from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GreenMarkEnum, GeneralBattleConfig
  16. from tasks.Component.GeneralBuff.config_buff import BuffClass
  17. from tasks.Component.GeneralBuff.general_buff import GeneralBuff
  18. from tasks.Component.GeneralBattle.battle_wait import BattleWait
  19. from module.logger import logger
  20. class GeneralBattle(BattleWait, GeneralBuff):
  21. """
  22. 使用这个通用的战斗必须要求这个任务的config有config_general_battle
  23. """
  24. def run_general_battle(self, config: GeneralBattleConfig = None, buff: BuffClass or list[BuffClass] = None) -> bool:
  25. """
  26. 运行脚本
  27. :return:
  28. """
  29. logger.hr("General battle start", 2)
  30. if config is None:
  31. config = GeneralBattleConfig()
  32. # 本人选择的策略是只要进来了就算一次,不管是不是打完了
  33. # 战斗统计
  34. self.current_count += 1
  35. logger.info(f"Current count: {self.current_count}")
  36. # 战前设置
  37. self.battle_before(buff, config)
  38. # 绿标
  39. if self.is_in_battle(False):
  40. self.green_mark(
  41. config.green_enable, config.green_mark,
  42. green_mark_type=config.green_mark_type,
  43. green_mark_name=config.green_mark_name,
  44. )
  45. # 战中设置
  46. win = self.battle_wait(random_click_swipt_enable=config.random_click_swipt_enable)
  47. if win:
  48. return True
  49. else:
  50. return False
  51. def battle_before(self, buff: BuffClass | list[BuffClass], config: GeneralBattleConfig, timeout: float = 5) -> bool:
  52. """战斗前设置
  53. :return: True:进入战斗或点击了准备按钮且识别不到准备按钮了 False:超过timeout s还没有进入战斗且没有点击过准备
  54. """
  55. timeout_timer = Timer(timeout).start()
  56. confed = False
  57. while not timeout_timer.reached():
  58. self.screenshot()
  59. if self.is_in_real_battle(False): # 战斗阶段
  60. return True
  61. if self.appear_then_click(self.I_DISABLE_7DAYS_DIFF_SOUL, interval=0.6): # 关闭御魂不一致提示
  62. continue
  63. if self.appear_then_click(self.I_CONFIRM_CLOSE_DIFF_SOUL, interval=0.6): # 确认关闭御魂不一致提示
  64. continue
  65. if self.is_in_prepare(False): # 战斗准备阶段
  66. if not getattr(config, 'lock_team_enable', False): # 没有锁定阵容
  67. if self.current_count == 1 and not confed: # 第一次战斗且是本次第一次配置
  68. self.switch_preset_team(config.preset_enable, config.preset_group, config.preset_team)
  69. self.check_and_open_buff(buff)
  70. confed = True
  71. # 点击准备(锁定阵容自动点准备,不锁定阵容前面也已经配置完毕需要点准备)
  72. if self.appear_then_click(self.I_PREPARE_HIGHLIGHT, interval=0.8):
  73. continue
  74. continue
  75. # 未知界面, 既不是准备界面也不是战斗界面
  76. # logger.info('Wait for preparation page') # 这玩意刷屏
  77. sleep(random.uniform(0.4, 0.8))
  78. return False
  79. def run_general_battle_back(self, config: GeneralBattleConfig = None, exit_four: bool = False) -> bool:
  80. """
  81. 进入挑战然后直接返回
  82. :param config:
  83. :return:
  84. """
  85. # 如果没有锁定队伍那么在点击准备后才退出的,退四的话就直接退出
  86. if not config.lock_team_enable and not exit_four:
  87. # 点击准备按钮
  88. self.wait_until_appear(self.I_PREPARE_HIGHLIGHT, wait_time=5)
  89. while 1:
  90. self.screenshot()
  91. if self.appear_then_click(self.I_PREPARE_HIGHLIGHT, interval=1.5):
  92. continue
  93. if not (self.appear(self.I_PRESET) or self.appear(self.I_PRESET_WIT_NUMBER)):
  94. break
  95. logger.info(f"Click {self.I_PREPARE_HIGHLIGHT.name}")
  96. # 点击返回
  97. while 1:
  98. self.screenshot()
  99. if self.appear_then_click(self.I_EXIT, interval=1.5):
  100. continue
  101. if self.appear(self.I_EXIT_ENSURE):
  102. break
  103. logger.info(f"Click {self.I_EXIT.name}")
  104. # 点击返回确认
  105. while 1:
  106. self.screenshot()
  107. if self.appear_then_click(self.I_EXIT_ENSURE, interval=1.5):
  108. continue
  109. if self.appear(self.I_FALSE):
  110. break
  111. logger.info(f"Click {self.I_EXIT_ENSURE.name}")
  112. # 点击失败确认
  113. self.wait_until_appear(self.I_FALSE)
  114. while 1:
  115. self.screenshot()
  116. if self.appear_then_click(self.I_FALSE, interval=1.5):
  117. continue
  118. if not self.appear(self.I_FALSE):
  119. break
  120. logger.info(f"Click {self.I_FALSE.name}")
  121. return True
  122. def exit_battle(self, skip_first: bool = False) -> bool:
  123. """
  124. 在战斗的时候强制退出战斗
  125. :return:
  126. """
  127. if skip_first:
  128. self.screenshot()
  129. if not self.appear(self.I_EXIT):
  130. return False
  131. # 点击返回
  132. logger.info(f"Click {self.I_EXIT.name}")
  133. while 1:
  134. self.screenshot()
  135. if self.appear_then_click(self.I_EXIT, interval=1.5):
  136. continue
  137. if self.appear(self.I_EXIT_ENSURE):
  138. break
  139. # 点击返回确认
  140. while 1:
  141. self.screenshot()
  142. if self.appear_then_click(self.I_EXIT_ENSURE, interval=1.5):
  143. continue
  144. if self.appear_then_click(self.I_FALSE, interval=1.5):
  145. continue
  146. if not self.appear(self.I_EXIT):
  147. break
  148. return True
  149. def battle_wait(self, random_click_swipt_enable: bool) -> bool:
  150. """
  151. 等待战斗结束 !!!
  152. 很重要 这个函数是原先写的, 优化版本在tasks/Secret/script_task下。本着不改动原先的代码的原则,所以就不改了
  153. :param random_click_swipt_enable:
  154. :return:
  155. """
  156. # 有的时候是长战斗,需要在设置stuck检测为长战斗
  157. # 但是无需取消设置,因为如果有点击或者滑动的话 handle_control_check会自行取消掉
  158. self.device.stuck_record_add('BATTLE_STATUS_S')
  159. self.device.click_record_clear()
  160. # 战斗过程 随机点击和滑动 防封
  161. logger.info("Start battle process")
  162. win: bool = False
  163. while 1:
  164. self.screenshot()
  165. # 如果出现赢 就点击, 第二个是针对封魔的图片
  166. if self.appear(self.I_WIN, threshold=0.8) or self.appear(self.I_DE_WIN):
  167. logger.info("Battle result is win")
  168. if self.appear(self.I_DE_WIN):
  169. self.ui_click_until_disappear(self.I_DE_WIN)
  170. win = True
  171. break
  172. # 如果出现失败 就点击,返回False
  173. if self.appear(self.I_FALSE, threshold=0.8):
  174. logger.info("Battle result is false")
  175. win = False
  176. break
  177. # 如果领奖励
  178. if self.appear(self.I_REWARD, threshold=0.6):
  179. win = True
  180. break
  181. # 如果领奖励出现金币
  182. if self.appear(self.I_REWARD_GOLD, threshold=0.8):
  183. win = True
  184. break
  185. # 如果开启战斗过程随机滑动
  186. if random_click_swipt_enable:
  187. self.random_click_swipt()
  188. # 再次确认战斗结果
  189. logger.info("Reconfirm the results of the battle")
  190. while 1:
  191. self.screenshot()
  192. if win:
  193. # 点击赢了
  194. action_click = random.choice([self.C_WIN_1, self.C_WIN_2, self.C_WIN_3])
  195. if self.appear_then_click(self.I_WIN, action=action_click, interval=0.5):
  196. continue
  197. if not self.appear(self.I_WIN):
  198. break
  199. else:
  200. # 如果失败且 点击失败后
  201. if self.appear_then_click(self.I_FALSE, threshold=0.6):
  202. continue
  203. if not self.appear(self.I_FALSE, threshold=0.6):
  204. return False
  205. # 最后保证能点击 获得奖励
  206. if not self.wait_until_appear(self.I_REWARD, wait_time=10):
  207. if not self.appear(self.I_STATISTICS):
  208. # 有些的战斗没有下面的奖励,所以直接返回
  209. logger.info("There is no reward, Exit battle")
  210. return win
  211. logger.info("Get reward")
  212. while 1:
  213. self.screenshot()
  214. # 如果出现领奖励
  215. action_click = random.choice([self.C_REWARD_1, self.C_REWARD_2, self.C_REWARD_3])
  216. if (self.appear_then_click(self.I_REWARD, action=action_click, interval=1.5) or
  217. self.appear_then_click(self.I_REWARD_GOLD, action=action_click, interval=1.5)# or
  218. # self.appear_then_click(self.I_REWARD_STATISTICS, action=action_click, interval=1.5) or
  219. # self.appear_then_click(self.I_REWARD_PURPLE_SNAKE_SKIN, action=action_click, interval=1.5) or
  220. # self.appear_then_click(self.I_REWARD_GOLD_SNAKE_SKIN, action=action_click, interval=1.5) or
  221. # self.appear_then_click(self.I_REWARD_EXP_SOUL_4, action=action_click, interval=1.5) or
  222. # self.appear_then_click(self.I_REWARD_SOUL_5, action=action_click, interval=1.5) or
  223. # self.appear_then_click(self.I_REWARD_SOUL_6, action=action_click, interval=1.5)
  224. ):
  225. continue
  226. if self._hook_special_reward():
  227. continue
  228. if (not self.appear(self.I_REWARD) and
  229. not self.appear(self.I_REWARD_GOLD) # and
  230. # not self.appear(self.I_REWARD_STATISTICS) and
  231. # not self.appear(self.I_REWARD_PURPLE_SNAKE_SKIN) and
  232. # not self.appear(self.I_REWARD_GOLD_SNAKE_SKIN) and
  233. # not self.appear(self.I_REWARD_EXP_SOUL_4) and
  234. # not self.appear(self.I_REWARD_SOUL_5) and
  235. # not self.appear(self.I_REWARD_SOUL_6)
  236. ):
  237. break
  238. return win
  239. def battle_wait_v2(self, random_click_swipt_enable: bool) -> bool:
  240. """
  241. 第二版战斗等待,参考 Orochi 和 Secret 的优化版本。
  242. :return: 胜利返回 True,失败返回 False
  243. """
  244. # 统一点击名称,防止 GameTooManyClickError 误报
  245. self.C_REWARD_1.name, self.C_REWARD_2.name, self.C_REWARD_3.name = 'C_REWARD', 'C_REWARD', 'C_REWARD'
  246. self.device.stuck_record_add('BATTLE_STATUS_S')
  247. self.device.click_record_clear()
  248. logger.info("Start battle process")
  249. while 1:
  250. self.screenshot()
  251. # 出现赢的鼓,点击直到消失
  252. if self.appear_then_click(self.I_WIN, interval=0.8):
  253. continue
  254. # 逢魔胜利图
  255. if self.appear(self.I_DE_WIN):
  256. self.ui_click_until_disappear(self.I_DE_WIN)
  257. continue
  258. if self.appear(self.I_FALSE, threshold=0.8):
  259. logger.warning('False battle')
  260. self.ui_click_until_disappear(self.I_FALSE)
  261. return False
  262. appear_ghost, appear_reward, appear_gold = (
  263. self.appear(self.I_GREED_GHOST),
  264. self.appear(self.I_REWARD),
  265. self.appear(self.I_REWARD_GOLD)
  266. )
  267. if appear_ghost or appear_reward or appear_gold:
  268. logger.info('Win battle')
  269. timer = Timer(20).start()
  270. while 1:
  271. self.screenshot()
  272. _appear_ghost, _appear_reward, _appear_gold = (
  273. self.appear(self.I_GREED_GHOST, threshold=0.6),
  274. self.appear(self.I_REWARD),
  275. self.appear(self.I_REWARD_GOLD)
  276. )
  277. # logger.info(f'_appear_ghost: {_appear_ghost} _appear_reward: {_appear_reward} _appear_gold: {_appear_gold}')
  278. if any([_appear_ghost, _appear_reward, _appear_gold]):
  279. action_click = random.choice([self.C_REWARD_1, self.C_REWARD_2, self.C_REWARD_3])
  280. self.click(action_click, interval=1.5)
  281. else:
  282. logger.info('Battle done')
  283. return True
  284. if self._hook_special_reward():
  285. continue
  286. if timer.reached_and_reset():
  287. logger.warning('battle ')
  288. break
  289. # 随机滑动
  290. if random_click_swipt_enable:
  291. self.random_click_swipt()
  292. return False
  293. def _hook_special_reward(self) -> bool:
  294. """
  295. For overwrite https://github.com/runhey/OnmyojiAutoScript/issues/1580
  296. """
  297. return False
  298. def green_mark(self, enable: bool = False, mark_mode: GreenMarkType = GreenMarkType.GREEN_MAIN,
  299. green_mark_type: GreenMarkEnum = GreenMarkEnum.CHOOSE, green_mark_name: str = ''):
  300. """
  301. 绿标, 如果不使能就直接返回
  302. :param enable:
  303. :param mark_mode:绿标目标位置
  304. :param green_mark_type: 按坐标还是按式神名点击
  305. :param green_mark_name: 式神名,仅 green_mark_type 为 NAME 时生效
  306. :return:
  307. """
  308. if not enable:
  309. return
  310. logger.info("Green is enable")
  311. self.device.screenshot_interval_set()
  312. match green_mark_type:
  313. case GreenMarkEnum.CHOOSE:
  314. self.green_mark_choose(mark_mode)
  315. case GreenMarkEnum.NAME:
  316. self.green_mark_name(green_mark_name)
  317. self.device.screenshot_interval_set('combat')
  318. def green_mark_choose(self, mark_mode: GreenMarkType = GreenMarkType.GREEN_MAIN):
  319. x, y = None, None
  320. match mark_mode:
  321. case GreenMarkType.GREEN_LEFT1:
  322. x, y = self.C_GREEN_LEFT_1.coord()
  323. logger.info("Green left 1")
  324. case GreenMarkType.GREEN_LEFT2:
  325. x, y = self.C_GREEN_LEFT_2.coord()
  326. logger.info("Green left 2")
  327. case GreenMarkType.GREEN_LEFT3:
  328. x, y = self.C_GREEN_LEFT_3.coord()
  329. logger.info("Green left 3")
  330. case GreenMarkType.GREEN_LEFT4:
  331. x, y = self.C_GREEN_LEFT_4.coord()
  332. logger.info("Green left 4")
  333. case GreenMarkType.GREEN_LEFT5:
  334. x, y = self.C_GREEN_LEFT_5.coord()
  335. logger.info("Green left 5")
  336. case GreenMarkType.GREEN_MAIN:
  337. x, y = self.C_GREEN_MAIN.coord()
  338. logger.info("Green main")
  339. while 1:
  340. self.screenshot()
  341. if not self.appear(self.I_PREPARE_HIGHLIGHT):
  342. break
  343. if self.appear_then_click(self.I_LOCAL):
  344. time.sleep(0.3)
  345. self.device.click(x, y)
  346. def green_mark_name(self, name: str = ''):
  347. if name == '':
  348. logger.warning("Green mark name is empty")
  349. return
  350. timeout_timer = Timer(6).start()
  351. best = {'name': '', 'x': -1, 'y': -1, 'similarity': 0.0}
  352. while not timeout_timer.reached():
  353. self.screenshot()
  354. results = self.O_GREEN_MARK_AREA.detect_and_ocr(self.device.image)
  355. for ret in results:
  356. similarity = difflib.SequenceMatcher(None, ret.ocr_text, name).ratio()
  357. if similarity > best['similarity']:
  358. x = self.O_GREEN_MARK_AREA.roi[0] + ret.box[0, 0] + 5
  359. y = self.O_GREEN_MARK_AREA.roi[1] + ret.box[0, 1] + 30
  360. x = 1280 if x > 1280 else x
  361. y = 720 if y > 720 else y
  362. best = {'name': ret.ocr_text, 'x': x, 'y': y, 'similarity': similarity}
  363. if best['similarity'] > 0.5:
  364. logger.info(f'Green name success, text: {best["name"]}[{best["similarity"]:.2f}]')
  365. self.device.click(best['x'], best['y'], control_name=best['name'])
  366. return
  367. logger.warning(f'Green name failed, best text: {best["name"]}[{best["similarity"]:.2f}]')
  368. def switch_preset_team(self, enable: bool = False, preset_group: int = 1, preset_team: int = 1):
  369. """
  370. 切换预设的队伍, 要求是在不锁定队伍时的情况下
  371. :param enable:
  372. :param preset_group:
  373. :param preset_team:
  374. :return:
  375. """
  376. if not enable:
  377. logger.info("Preset is disable")
  378. return None
  379. logger.info("Preset is enable")
  380. # 点击预设按钮
  381. while 1:
  382. self.screenshot()
  383. if self.appear(self.I_PRESET_ENSURE):
  384. break
  385. # 首个队伍没有满足5个式神,未出现预设按钮的情况下跳出循环
  386. if self.appear(self.I_PRESENT_LESS_THAN_5):
  387. break
  388. if self.appear_then_click(self.I_PRESET, threshold=0.8, interval=1):
  389. continue
  390. if self.appear_then_click(self.I_PRESET_WIT_NUMBER, threshold=0.8, interval=1):
  391. continue
  392. if self.ocr_appear(self.O_PRESET):
  393. self.click(self.O_PRESET, interval=1)
  394. continue
  395. if self.ocr_appear(self.O_PRESET_FULL):
  396. self.click(self.O_PRESET_FULL, interval=1)
  397. continue
  398. logger.info("Click preset button")
  399. def get_unselect_color(tmp1, tmp2, tmp3, size):
  400. # 获取未选择分组的颜色,3组之中必定存在两个颜色相似
  401. # area 参数格式是(x1,y1,x2,y2)
  402. color_1 = get_color(self.device.image,
  403. (tmp1.roi_back[0], tmp1.roi_back[1],
  404. tmp1.roi_back[0] + size[0], tmp1.roi_back[1] + size[1]))
  405. color_2 = get_color(self.device.image,
  406. (tmp2.roi_back[0], tmp2.roi_back[1],
  407. tmp2.roi_back[0] + size[0], tmp2.roi_back[1] + size[1]))
  408. color_3 = get_color(self.device.image,
  409. (tmp3.roi_back[0], tmp3.roi_back[1],
  410. tmp3.roi_back[0] + size[0], tmp3.roi_back[1] + size[1]))
  411. if color_similar(color_1, color_2):
  412. return color_1
  413. if color_similar(color_2, color_3):
  414. return color_2
  415. return color_3
  416. # 选择预设组
  417. tmp = self.__getattribute__("C_PRESET_GROUP_" + str(preset_group))
  418. if tmp is None:
  419. tmp = self.C_PRESET_GROUP_1
  420. color_size = [self.C_PRESET_GROUP_1.roi_back[2],
  421. self.C_PRESET_GROUP_1.roi_back[3]]
  422. # unselected_color = get_unselect_color(self.C_PRESET_GROUP_1, self.C_PRESET_GROUP_2, self.C_PRESET_GROUP_3, size=color_size)
  423. # 考虑到有些预设组没有预设,所以这里取一个比较固定的颜色
  424. unselected_color = (224.9, 208.3, 187.4)
  425. while True:
  426. self.screenshot()
  427. color_tmp = get_color(self.device.image,
  428. (tmp.roi_back[0], tmp.roi_back[1], tmp.roi_back[0] + color_size[0],
  429. tmp.roi_back[1] + color_size[1]))
  430. if color_similar(color_tmp, unselected_color):
  431. self.click(tmp, interval=0.2)
  432. continue
  433. break
  434. logger.info("Select preset group")
  435. # 选择预设的队伍
  436. time.sleep(0.5)
  437. tmp = self.__getattribute__("C_PRESET_TEAM_" + str(preset_team))
  438. if tmp is None:
  439. tmp = self.C_PRESET_TEAM_1
  440. color_size = [5, 5]
  441. # unselected_color = get_unselect_color(self.C_PRESET_TEAM_1, self.C_PRESET_TEAM_2, self.C_PRESET_TEAM_3, size=color_size )
  442. unselected_color = (216.8, 185.0, 146.8)
  443. while True:
  444. self.screenshot()
  445. color_tmp = get_color(self.device.image,
  446. (tmp.roi_back[0], tmp.roi_back[1], tmp.roi_back[0] + color_size[0],
  447. tmp.roi_back[1] + color_size[1]))
  448. if color_similar(color_tmp, unselected_color):
  449. self.click(tmp, interval=0.2)
  450. continue
  451. break
  452. self.click(tmp)
  453. logger.info("Select preset team")
  454. # 点击预设确认
  455. self.wait_until_appear(self.I_PRESET_ENSURE, wait_time=1)
  456. click_timer = Timer(10).start()
  457. while 1:
  458. self.screenshot()
  459. if click_timer.reached():
  460. logger.warning("Switch preset failure")
  461. if not self.appear(self.I_PRESET_ENSURE):
  462. break
  463. if self.appear_then_click(self.I_PRESET_ENSURE, threshold=0.8, interval=1):
  464. continue
  465. logger.info("Click preset ensure")
  466. return None
  467. def random_click_swipt(self):
  468. if 0 <= random.randint(0, 500) <= 3: # 百分之4的概率
  469. rand_type = random.randint(0, 2)
  470. match rand_type:
  471. case 0:
  472. self.click(self.C_RANDOM_CLICK, interval=20)
  473. case 1:
  474. self.swipe(self.S_BATTLE_RANDOM_LEFT, interval=20)
  475. case 2:
  476. self.swipe(self.S_BATTLE_RANDOM_RIGHT, interval=20)
  477. # 重新设置为长战斗
  478. # self.device.stuck_record_add('BATTLE_STATUS_S')
  479. else:
  480. time.sleep(0.4) # 这样的好像不对
  481. # 判断是否在战斗中
  482. def is_in_battle(self, is_screenshot: bool = True) -> bool:
  483. """
  484. 判断是否在战斗中
  485. tip: 因为有friends判别, 所以即使在准备界面也会识别在战斗中
  486. :return:
  487. """
  488. if is_screenshot:
  489. self.screenshot()
  490. if self.appear(self.I_BATTLE_INFO) or \
  491. self.appear(self.I_FRIENDS) or \
  492. self.appear(self.I_WIN) or \
  493. self.appear(self.I_FALSE) or \
  494. self.appear(self.I_REWARD):
  495. return True
  496. else:
  497. return False
  498. def is_in_real_battle(self, is_screenshot: bool = True):
  499. """
  500. 判断是否在真正的战斗中(不是战斗准备界面也不是战斗结束界面)
  501. :param is_screenshot:
  502. :return:
  503. """
  504. if is_screenshot:
  505. self.screenshot()
  506. return self.appear(self.I_BATTLE_INFO)
  507. def is_in_prepare(self, is_screenshot: bool = True) -> bool:
  508. """
  509. 判断是否在准备中
  510. :return:
  511. """
  512. if is_screenshot:
  513. self.screenshot()
  514. if self.appear(self.I_BUFF):
  515. return True
  516. elif self.appear(self.I_PREPARE_HIGHLIGHT):
  517. return True
  518. elif self.appear(self.I_PREPARE_DARK):
  519. return True
  520. elif self.appear(self.I_PRESET) or self.appear(self.I_PRESET_WIT_NUMBER):
  521. return True
  522. else:
  523. return False
  524. def check_take_over_battle(self, is_screenshot: bool, config: GeneralBattleConfig) -> bool or None:
  525. """
  526. 中途接入战斗,并且接管
  527. :return: 赢了返回True, 输了返回False, 不是在战斗中返回None
  528. """
  529. if is_screenshot:
  530. self.screenshot()
  531. if not self.is_in_battle():
  532. return None
  533. return self.run_general_battle(config=config)
  534. def check_lock(self, enable: bool, lock_image, unlock_image):
  535. """
  536. 检测是否锁定队伍,
  537. :param enable:
  538. :param lock_image:
  539. :param unlock_image:
  540. :return:
  541. """
  542. if enable:
  543. logger.info("Lock team")
  544. while 1:
  545. self.screenshot()
  546. if self.appear(lock_image):
  547. break
  548. if self.appear_then_click(unlock_image, interval=1):
  549. continue
  550. else:
  551. logger.info("Unlock team")
  552. while 1:
  553. self.screenshot()
  554. if self.appear(unlock_image):
  555. break
  556. if self.appear_then_click(lock_image, interval=1):
  557. continue
  558. def check_and_open_buff(self, buff: BuffClass or list[BuffClass] = None):
  559. """
  560. 检测是否开启buff
  561. :param buff:
  562. :return:
  563. """
  564. if not buff:
  565. return
  566. logger.info(f'Open buff {buff}')
  567. self.ui_click(self.I_BUFF, self.I_CLOUD, interval=2)
  568. if isinstance(buff, BuffClass):
  569. buff = [buff]
  570. match_method = {
  571. BuffClass.AWAKE: (self.awake, True),
  572. BuffClass.SOUL: (self.soul, True),
  573. BuffClass.GOLD_50: (self.gold_50, True),
  574. BuffClass.GOLD_100: (self.gold_100, True),
  575. BuffClass.EXP_50: (self.exp_50, True),
  576. BuffClass.EXP_100: (self.exp_100, True),
  577. BuffClass.AWAKE_CLOSE: (self.awake, False),
  578. BuffClass.SOUL_CLOSE: (self.soul, False),
  579. BuffClass.GOLD_50_CLOSE: (self.gold_50, False),
  580. BuffClass.GOLD_100_CLOSE: (self.gold_100, False),
  581. BuffClass.EXP_50_CLOSE: (self.exp_50, False),
  582. BuffClass.EXP_100_CLOSE: (self.exp_100, False),
  583. }
  584. for b in buff:
  585. func, is_open = match_method[b]
  586. func(is_open)
  587. time.sleep(0.1)
  588. logger.info(f'Open buff success')
  589. while 1:
  590. self.screenshot()
  591. if not self.appear(self.I_CLOUD):
  592. break
  593. if self.appear_then_click(self.I_BUFF, interval=1):
  594. continue
  595. def boss_mark(self, enable=True) -> bool:
  596. if not enable or self._boss_mark_flag:
  597. return False
  598. if self.ocr_appear(self.O_BOSS_MARK):
  599. self.screenshot()
  600. if self.ocr_appear(self.O_BOSS_MARK):
  601. self._boss_mark_flag = True
  602. logger.info('Boss marked')
  603. self.device.stuck_record_add('BATTLE_STATUS_S')
  604. return True
  605. if self.device.click_record.count(str(self.O_BOSS_MARK)) >= 3:
  606. self._boss_mark_flag = True
  607. logger.info('Boss mark skipped due to maybe no boss')
  608. self.device.stuck_record_add('BATTLE_STATUS_S')
  609. return False
  610. if self.click(self.O_BOSS_MARK, interval=1.8):
  611. return False
  612. return False
  613. def boss_mark_reset(self):
  614. self._boss_mark_flag = False
  615. if __name__ == '__main__':
  616. from module.config.config import Config
  617. from module.device.device import Device
  618. c = Config('oas1')
  619. d = Device(c)
  620. t = GeneralBattle(c, d)
  621. self = t
  622. # t.check_buff([BuffClass.EXP_50, BuffClass.GOLD_50])
  623. img = cv2.imread(r"E:\preset3.png")
  624. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  625. self.device.image = img
  626. def get_unselect_color(tmp1, tmp2, tmp3, size):
  627. # 获取未选择分组的颜色,3组之中必定存在两个颜色相似
  628. # area 参数格式是(x1,y1,x2,y2)
  629. color_1 = get_color(self.device.image,
  630. (tmp1.roi_back[0], tmp1.roi_back[1],
  631. tmp1.roi_back[0] + size[0], tmp1.roi_back[1] + size[1]))
  632. color_2 = get_color(self.device.image,
  633. (tmp2.roi_back[0], tmp2.roi_back[1],
  634. tmp2.roi_back[0] + size[0], tmp2.roi_back[1] + size[1]))
  635. color_3 = get_color(self.device.image,
  636. (tmp3.roi_back[0], tmp3.roi_back[1],
  637. tmp3.roi_back[0] + size[0], tmp3.roi_back[1] + size[1]))
  638. if color_similar(color_1, color_2):
  639. return color_1
  640. if color_similar(color_2, color_3):
  641. return color_2
  642. return color_3
  643. color_size = [self.C_PRESET_GROUP_1.roi_back[2],
  644. self.C_PRESET_GROUP_1.roi_back[3]]
  645. unselected_color = get_unselect_color(self.C_PRESET_GROUP_1, self.C_PRESET_GROUP_2, self.C_PRESET_GROUP_3,
  646. size=color_size)
  647. color_size = [5, 5]
  648. unselected_color = get_unselect_color(self.C_PRESET_TEAM_1, self.C_PRESET_TEAM_2, self.C_PRESET_TEAM_3,
  649. size=color_size
  650. )
  651. def run_task_or_default_general_battle(task) -> bool:
  652. """
  653. 超时或异常时接管战斗的兜底函数
  654. https://github.com/runhey/OnmyojiAutoScript/issues/1884
  655. """
  656. # Config exposes task groups, not a top-level general_battle_config.
  657. # Some tasks initialize conf themselves; navigation also runs before run().
  658. sources = [getattr(task, 'conf', None)]
  659. task_name = getattr(getattr(task.config, 'model', None), 'running_task', '')
  660. if not task_name:
  661. task_name = getattr(getattr(task, 'navigator', None), 'task_category', '')
  662. if isinstance(task_name, str) and task_name:
  663. sources.append(getattr(task.config, convert_to_underscore(task_name), None))
  664. sources.append(task.config)
  665. config = next((
  666. candidate for source in sources
  667. if isinstance(candidate := getattr(source, 'general_battle_config', None), GeneralBattleConfig)
  668. ), None)
  669. # Reuse task overrides, counters and asset customizations. Do not catch
  670. # exceptions from the battle itself and accidentally start a second run.
  671. run_battle = getattr(task, 'run_general_battle', None)
  672. if callable(run_battle):
  673. return run_battle(config=config)
  674. class DefaultGeneralBattle(GeneralBattle):
  675. def get_task_name(self):
  676. # Costume setup validates the scheduler task against its owner.
  677. return task.get_task_name()
  678. gb = DefaultGeneralBattle(config=task.config, device=task.device)
  679. return gb.run_general_battle(config=config)