general_battle.py 30 KB

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