Просмотр исходного кода

Merge pull request #1804 from runhey/dev

Dev
huangrunheng 2 месяцев назад
Родитель
Сommit
042ce93129
47 измененных файлов с 1264 добавлено и 199 удалено
  1. 65 1
      assets/i18n/zh-CN.json
  2. 139 0
      module/atom/click.py
  3. 2 3
      module/atom/ocr.py
  4. 2 1
      module/device/platform2/emulator_base.py
  5. 9 2
      module/device/platform2/platform_windows.py
  6. 6 2
      module/ocr/base_ocr.py
  7. 3 3
      module/ocr/sub_ocr.py
  8. 0 1
      tasks/AbyssShadows/config.py
  9. BIN
      tasks/ActivityShikigami/as/as_climb_mode_pass.png
  10. BIN
      tasks/ActivityShikigami/as/as_climb_mode_switch.png
  11. BIN
      tasks/ActivityShikigami/as/as_shi.png
  12. BIN
      tasks/ActivityShikigami/as/as_to_battle_main.png
  13. 3 3
      tasks/ActivityShikigami/as/pages.json
  14. 4 4
      tasks/ActivityShikigami/assets.py
  15. 38 38
      tasks/ActivityShikigami/config.py
  16. 4 4
      tasks/ActivityShikigami/fire/ocr.json
  17. 4 47
      tasks/ActivityShikigami/script_task.py
  18. 4 4
      tasks/BondlingFairyland/general_invite.py
  19. 1 1
      tasks/BudokaiTournament/assets.py
  20. 82 0
      tasks/Component/GeneralBattle/assets.py
  21. 192 54
      tasks/Component/GeneralBattle/battle_wait.py
  22. 1 1
      tasks/Component/GeneralBattle/general_battle.py
  23. 80 0
      tasks/Component/GeneralBattle/gw/click.json
  24. 116 0
      tasks/Component/GeneralBattle/gw/click2.json
  25. 8 0
      tasks/Component/GeneralBattle/gw/click_activity.json
  26. BIN
      tasks/Component/GeneralBattle/gw/gw_end_fix_1.png
  27. BIN
      tasks/Component/GeneralBattle/gw/gw_end_fix_2.png
  28. 20 0
      tasks/Component/GeneralBattle/gw/image.json
  29. 4 5
      tasks/Component/GeneralInvite/general_invite.py
  30. 2 0
      tasks/DemonEncounter/assets.py
  31. 9 0
      tasks/DemonEncounter/demon/ocr.json
  32. 19 0
      tasks/DemonEncounter/script_task.py
  33. 8 0
      tasks/EvoZone/script_task.py
  34. 2 3
      tasks/GameUi/game_ui.py
  35. 24 8
      tasks/KekkaiActivation/script_task.py
  36. 1 1
      tasks/Nian/assets.py
  37. 2 2
      tasks/Nian/nian/image.json
  38. 4 2
      tasks/RealmRaid/script_task.py
  39. 1 1
      tasks/Restart/assets.py
  40. 4 2
      tasks/Restart/login.py
  41. 13 0
      tasks/RichMan/guild.py
  42. 5 0
      tasks/RyouToppa/script_task.py
  43. 1 1
      tasks/SoulsTidy/script_task.py
  44. 8 5
      tasks/base_task.py
  45. 120 0
      tests/module/atom/test_click.py
  46. 233 0
      tests/tasks/Component/GeneralBattle/test_battle_wait.py
  47. 21 0
      tests/test_ocr_filter.py

+ 65 - 1
assets/i18n/zh-CN.json

@@ -70,5 +70,69 @@
   "long_rest_duration_help": "触发累计活跃上限后的强制休息时长。格式:天 时:分:秒。",
   "min_run_interval": "最小再运行间隔",
   "min_run_interval_help": "防风控:两次蹭卡运行之间的最小间隔,避免蹭卡过于频繁被服务端标记。设为 0(默认)保持原逻辑(按结界卡剩余时间安排下次)。格式:天 时:分:秒。",
-  "costume_shikigami_11": "花札幕台"
+  "costume_shikigami_11": "花札幕台",
+  "enable_switch_pass": "切换门票爬塔御魂",
+  "enable_switch_pass_help": "是否切换门票爬塔御魂",
+  "pass_group_team": "门票爬塔御魂分组",
+  "pass_group_team_help": "组1-7,队伍1-4 中间用英文,分隔",
+  "enable_switch_pass_by_name": "通过OCR切换门票爬塔御魂",
+  "enable_switch_pass_by_name_help": "是否通过OCR切换御魂",
+  "pass_group_team_name": "门票爬塔御魂分组名、队伍名",
+  "pass_group_team_name_help": "组名,队伍名 中间用英文,分隔",
+  "enable_switch_ap": "切换体力爬塔御魂",
+  "enable_switch_ap_help": "是否切换体力爬塔御魂",
+  "ap_group_team": "体力爬塔御魂分组",
+  "ap_group_team_help": "组1-7,队伍1-4 中间用英文,分隔",
+  "enable_switch_ap_by_name": "通过OCR切换体力爬塔御魂",
+  "enable_switch_ap_by_name_help": "是否通过OCR切换御魂",
+  "ap_group_team_name": "体力爬塔御魂分组名、队伍名",
+  "ap_group_team_name_help": "组名,队伍名 中间用英文,分隔",
+  "enable_switch_boss": "切换Boss爬塔御魂",
+  "enable_switch_boss_help": "是否切换boss爬塔御魂",
+  "boss_group_team": "Boss爬塔御魂分组",
+  "boss_group_team_help": "组1-7,队伍1-4 中间用英文,分隔",
+  "enable_switch_boss_by_name": "通过OCR切换Boss爬塔御魂",
+  "enable_switch_boss_by_name_help": "是否通过OCR切换御魂",
+  "boss_group_team_name": "Boss爬塔御魂分组名、队伍名",
+  "boss_group_team_name_help": "组名,队伍名 中间用英文,分隔",
+  "enable_switch_ap100": "切换100体爬塔御魂",
+  "enable_switch_ap100_help": "是否切换100体爬塔御魂",
+  "ap100_group_team": "100体爬塔御魂分组",
+  "ap100_group_team_help": "组1-7,队伍1-4 中间用英文,分隔",
+  "enable_switch_ap100_by_name": "通过OCR切换100体爬塔御魂",
+  "enable_switch_ap100_by_name_help": "是否通过OCR切换御魂",
+  "ap100_group_team_name": "100体爬塔御魂分组名、队伍名",
+  "ap100_group_team_name_help": "组名,队伍名 中间用英文,分隔",
+  "enable_pass_preset": "切换门票爬塔预设",
+  "enable_pass_preset_help": "是否切换门票爬塔预设, 仅数字切换御魂可用",
+  "enable_pass_green": "开启门票爬塔绿标",
+  "enable_pass_green_help": "是否开启门票爬塔绿标",
+  "pass_green_mark": "门票爬塔绿标位置",
+  "pass_green_mark_help": "门票爬塔绿标位置",
+  "enable_pass_anti_detect": "门票爬塔防检测",
+  "enable_pass_anti_detect_help": "门票爬塔战斗过程是否随机点击或滑动",
+  "enable_ap_preset": "切换体力爬塔预设",
+  "enable_ap_preset_help": "是否切换体力爬塔预设, 仅数字切换御魂可用",
+  "enable_ap_green": "开启体力爬塔绿标",
+  "enable_ap_green_help": "是否开启体力爬塔绿标",
+  "ap_green_mark": "体力爬塔绿标位置",
+  "ap_green_mark_help": "体力爬塔绿标位置",
+  "enable_ap_anti_detect": "体力爬塔防检测",
+  "enable_ap_anti_detect_help": "体力爬塔战斗过程是否随机点击或滑动",
+  "enable_boss_preset": "切换Boss爬塔预设",
+  "enable_boss_preset_help": "是否切换boss爬塔预设, 仅数字切换御魂可用",
+  "enable_boss_green": "开启Boss爬塔绿标",
+  "enable_boss_green_help": "是否开启boss爬塔绿标",
+  "boss_green_mark": "Boss爬塔绿标位置",
+  "boss_green_mark_help": "boss爬塔绿标位置",
+  "enable_boss_anti_detect": "Boss爬塔防检测",
+  "enable_boss_anti_detect_help": "boss爬塔战斗过程是否随机点击或滑动",
+  "enable_ap100_preset": "切换100体爬塔预设",
+  "enable_ap100_preset_help": "是否切换100体爬塔预设, 仅数字切换御魂可用",
+  "enable_ap100_green": "开启100体爬塔绿标",
+  "enable_ap100_green_help": "是否开启100体爬塔绿标",
+  "ap100_green_mark": "100体爬塔绿标位置",
+  "ap100_green_mark_help": "100体爬塔绿标位置",
+  "enable_ap100_anti_detect": "100体爬塔防检测",
+  "enable_ap100_anti_detect_help": "100体爬塔战斗过程是否随机点击或滑动"
 }

+ 139 - 0
module/atom/click.py

@@ -1,6 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+import random
 import numpy as np
 
 from module.base.decorator import cached_property
@@ -72,3 +73,141 @@ class RuleClick:
             y = 720
 
         self.roi_front = x, y, w, h
+
+
+class RuleClickExclude(RuleClick):
+    """Randomly click within the screen while excluding other click regions."""
+
+    SCREEN_WIDTH = 1280
+    SCREEN_HEIGHT = 720
+
+    def __init__(self, clicks, strategy: str | None = None, distribution: str | None = None,
+                 max_attempts: int = 100, name: str = 'exclude_random_click') -> None:
+        """
+        初始化排除区域随机点击规则。
+
+        :param clicks: 需要排除的 RuleClick,或 RuleClick 序列;使用其 roi_back 作为排除区域
+        :param strategy: 取点策略,None 时在初始化时随机选择 rejection 或 complement
+        :param distribution: 坐标分布,None 时在初始化时随机选择 uniform 或 normal
+        :param max_attempts: 拒绝采样的最大尝试次数,耗尽后自动使用补集矩形采样
+        :param name: 点击规则名称,用于 BaseTask.click 的间隔计时器
+        :raises TypeError: clicks 不是 RuleClick 或 RuleClick 序列
+        :raises ValueError: strategy、distribution 或 max_attempts 参数无效,或排除区域覆盖整个屏幕
+        """
+        super().__init__((0, 0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT),
+                         (0, 0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT), name=name)
+        if strategy is None:
+            strategy = random.choice(('rejection', 'complement'))
+        if distribution is None:
+            distribution = random.choice(('uniform', 'normal'))
+        if strategy not in ('rejection', 'complement'):
+            raise ValueError("strategy must be 'rejection' or 'complement'")
+        if distribution not in ('uniform', 'normal'):
+            raise ValueError("distribution must be 'uniform' or 'normal'")
+        if max_attempts < 1:
+            raise ValueError('max_attempts must be positive')
+
+        if isinstance(clicks, RuleClick):
+            clicks = (clicks,)
+        self.clicks = tuple(clicks)
+        if not all(isinstance(click, RuleClick) for click in self.clicks):
+            raise TypeError('clicks must contain RuleClick instances')
+        self.strategy = strategy
+        self.distribution = distribution
+        self.max_attempts = max_attempts
+        self._excluded = tuple(
+            rect for click in self.clicks
+            for rect in (self._clip_roi(click.roi_back),)
+            if rect is not None
+        )
+        self._allowed = self._build_complement()
+        if not self._allowed:
+            raise ValueError('Excluded regions cover the whole screen')
+
+    def __str__(self):
+        click_names = ', '.join(click.name for click in self.clicks) or 'none'
+        return (
+            f'{self.name}(strategy={self.strategy}, '
+            f'distribution={self.distribution}, clicks=[{click_names}])'
+        )
+
+    __repr__ = __str__
+
+    @classmethod
+    def _clip_roi(cls, roi):
+        x, y, w, h = roi
+        left, top = max(0, x), max(0, y)
+        right, bottom = min(cls.SCREEN_WIDTH, x + w), min(cls.SCREEN_HEIGHT, y + h)
+        if left >= right or top >= bottom:
+            return None
+        return left, top, right - left, bottom - top
+
+    def _is_excluded(self, x, y):
+        return any(left <= x < left + width and top <= y < top + height
+                   for left, top, width, height in self._excluded)
+
+    def _build_complement(self):
+        x_edges = {0, self.SCREEN_WIDTH}
+        y_edges = {0, self.SCREEN_HEIGHT}
+        for x, y, width, height in self._excluded:
+            x_edges.update((x, x + width))
+            y_edges.update((y, y + height))
+
+        x_edges, y_edges = sorted(x_edges), sorted(y_edges)
+        allowed = []
+        for x1, x2 in zip(x_edges, x_edges[1:]):
+            for y1, y2 in zip(y_edges, y_edges[1:]):
+                if not self._is_excluded(x1, y1):
+                    allowed.append((x1, y1, x2 - x1, y2 - y1))
+        return allowed
+
+    def _sample_axis(self, start, size, distribution):
+        if size == 1:
+            return start
+        if distribution == 'uniform':
+            return random.randrange(start, start + size)
+        return max(start, min(start + size - 1,
+                              random_normal_distribution_int(start, start + size)))
+
+    def _sample_point(self, rect, distribution):
+        x, y, width, height = rect
+        return self._sample_axis(x, width, distribution), self._sample_axis(y, height, distribution)
+
+    def _coord_rejection(self, distribution):
+        for _ in range(self.max_attempts):
+            point = self._sample_point((0, 0, self.SCREEN_WIDTH, self.SCREEN_HEIGHT), distribution)
+            if not self._is_excluded(*point):
+                return point
+        return self._coord_complement(distribution)
+
+    def _coord_complement(self, distribution):
+        total = sum(width * height for _, _, width, height in self._allowed)
+        offset = random.randrange(total)
+        for rect in self._allowed:
+            area = rect[2] * rect[3]
+            if offset < area:
+                return self._sample_point(rect, distribution)
+            offset -= area
+        raise RuntimeError('Unable to select a click region')
+
+    def coord(self) -> tuple:
+        if self.strategy == 'rejection':
+            return self._coord_rejection(self.distribution)
+        return self._coord_complement(self.distribution)
+
+    def coord_in_excluded(self, areas: list[str] | None = None) -> tuple:
+        """
+        
+        """
+        if not areas:
+            areas = ['C_END_1_1', 'C_END_1_2', 'C_END_1_3', 'C_END_1_4', 'C_END_1_5', 'C_END_1_6',
+                     'C_END_2_1', 'C_END_2_2', 'C_END_2_3', 'C_END_2_4', 'C_END_2_5', 'C_END_2_6']
+        area_names = {area.casefold() for area in areas}
+        matched = []
+        for click in self.clicks:
+            names = {str(click), click.name, click.name.upper(), f'C_{click.name.upper()}'}
+            if area_names.intersection(name.casefold() for name in names):
+                matched.append(click)
+        if not matched:
+            raise ValueError(f'No excluded click matches areas: {areas!r}')
+        return random.choice(matched).coord()

+ 2 - 3
module/atom/ocr.py

@@ -28,10 +28,10 @@ class RuleOcr(Digit, DigitCounter, Duration, Single, Full, Quantity):
             case OcrMode.QUANTITY: return Quantity.after_process(self, result)
             case _: return result
 
-    def ocr(self, image, keyword=None):
+    def ocr(self, image, keyword=None, exact: bool=False):
 
         match self.mode:
-            case OcrMode.FULL: return Full.ocr_full(self, image, keyword)
+            case OcrMode.FULL: return Full.ocr_full(self, image, keyword, exact=exact)
             case OcrMode.SINGLE: return Single.ocr_single(self, image)
             case OcrMode.DIGIT: return Digit.ocr_digit(self, image)
             case OcrMode.DIGITCOUNTER: return DigitCounter.ocr_digit_counter(self, image)
@@ -88,4 +88,3 @@ if __name__ == "__main__":
     )
 
     print(rule.ocr_quantity(image))
-

+ 2 - 1
module/device/platform2/emulator_base.py

@@ -100,12 +100,13 @@ class EmulatorInstanceBase:
         Convert MuMu 12 instance name to instance id.
         Example names:
             MuMuPlayer-12.0-3
+            MuMuPlayerGlobal-15.0-1
             YXArkNights-12.0-1
 
         Returns:
             int: Instance ID, or None if this is not a MuMu 12 instance
         """
-        res = re.search(r'MuMuPlayer(?:Global)?-12.0-(\d+)', self.name)
+        res = re.search(r'MuMuPlayer(?:Global)?-(?:12|15)\.0-(\d+)', self.name)
         if res:
             return int(res.group(1))
         res = re.search(r'YXArkNights-12.0-(\d+)', self.name)

+ 9 - 2
module/device/platform2/platform_windows.py

@@ -180,7 +180,10 @@ class PlatformWindows(PlatformBase, EmulatorManager):
             # MuMuPlayer.exe -v 0
             if instance.MuMuPlayer12_id is None:
                 logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
-            self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}', show_window=show_window)
+            if re.search(r'MuMuPlayer(?:Global)?-15\.0-\d+', instance.name):
+                self.execute(f'"{Emulator.single_to_console(exe)}" control -v {instance.MuMuPlayer12_id} --version 15 launch', show_window=show_window)
+            else:
+                self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}', show_window=show_window)
         elif instance == Emulator.LDPlayerFamily:
             # ldconsole.exe launch --index 0
             self.execute(f'"{Emulator.single_to_console(exe)}" launch --index {instance.LDPlayer_id}', show_window=show_window)
@@ -236,7 +239,11 @@ class PlatformWindows(PlatformBase, EmulatorManager):
             # MuMuManager.exe api -v 1 shutdown_player
             if instance.MuMuPlayer12_id is None:
                 logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
-            self.execute(f'"{Emulator.single_to_console(exe)}" api -v {instance.MuMuPlayer12_id} shutdown_player')
+            if re.search(r'MuMuPlayer(?:Global)?-15\.0-\d+', instance.name):
+                # Finish shutdown before emulator_start() launches the same instance.
+                self.execute(f'"{Emulator.single_to_console(exe)}" control -v {instance.MuMuPlayer12_id} --version 15 shutdown').wait(timeout=30)
+            else:
+                self.execute(f'"{Emulator.single_to_console(exe)}" api -v {instance.MuMuPlayer12_id} shutdown_player')
         elif instance == Emulator.LDPlayerFamily:
             # ldconsole.exe quit --index 0
             self.execute(f'"{Emulator.single_to_console(exe)}" quit --index {instance.LDPlayer_id}')

+ 6 - 2
module/ocr/base_ocr.py

@@ -215,11 +215,12 @@ class BaseCor:
         else:
             return self.keyword == result
 
-    def filter(self, boxed_results: list[BoxedResult], keyword: str=None) -> list or None:
+    def filter(self, boxed_results: list[BoxedResult], keyword: str=None, exact: bool=False) -> list or None:
         """
         使用ocr获取结果后和keyword进行匹配. 返回匹配的index list
         :param keyword: 如果不指定默认适用对象的keyword
         :param boxed_results:
+        :param exact: 是否只匹配完整的单个 OCR 文本
         :return:
         """
         # 首先先将所有的ocr的str顺序拼接起来, 然后再进行匹配
@@ -228,7 +229,10 @@ class BaseCor:
         concatenated_string = "".join(strings)
         if keyword is None:
             keyword = self.keyword
-        if keyword in concatenated_string:
+        if exact:
+            result = [index for index, word in enumerate(strings) if word == keyword]
+            return result or None
+        elif keyword in concatenated_string:
             result = [index for index, word in enumerate(strings) if keyword in word]
         else:
             result = None

+ 3 - 3
module/ocr/sub_ocr.py

@@ -23,11 +23,12 @@ class Full(BaseCor):
     def after_process(self, result):
         return result
 
-    def ocr_full(self, image, keyword: str=None) -> tuple:
+    def ocr_full(self, image, keyword: str=None, exact: bool=False) -> tuple:
         """
         检测整个图片的文本,并对结果进行过滤。返回的是匹配到的keyword的左边。如果没有匹配到返回(0, 0, 0, 0)
         :param image:
         :param keyword:
+        :param exact: 是否只匹配完整的单个 OCR 文本
         :return:
         """
         if keyword is None:
@@ -37,7 +38,7 @@ class Full(BaseCor):
         if not boxed_results:
             return 0, 0, 0, 0
 
-        index_list = self.filter(boxed_results, keyword)
+        index_list = self.filter(boxed_results, keyword, exact=exact)
         logger.info(f"OCR [{self.name}] detected in {index_list}")
         # 如果一个都没有匹配到
         if not index_list:
@@ -258,4 +259,3 @@ class Quantity(BaseCor):
 if __name__ == '__main__':
     import cv2
     image = cv2.imread(r'E:\Project\OnmyojiAutoScript-assets\jade.png')
-

+ 0 - 1
tasks/AbyssShadows/config.py

@@ -7,7 +7,6 @@
 from pydantic import BaseModel, Field
 # from pygments.lexer import default
 # from scripts.regsetup import description
-from sympy.testing.pytest import Failed
 
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
 from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig

BIN
tasks/ActivityShikigami/as/as_climb_mode_pass.png


BIN
tasks/ActivityShikigami/as/as_climb_mode_switch.png


BIN
tasks/ActivityShikigami/as/as_shi.png


BIN
tasks/ActivityShikigami/as/as_to_battle_main.png


+ 3 - 3
tasks/ActivityShikigami/as/pages.json

@@ -38,8 +38,8 @@
   {
     "itemName": "to_battle_main",
     "imageName": "as_to_battle_main.png",
-    "roiFront": "600,418,38,152",
-    "roiBack": "499,347,238,269",
+    "roiFront": "302,178,98,111",
+    "roiBack": "223,110,238,269",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "进入主要的战斗界面"
@@ -48,7 +48,7 @@
     "itemName": "to_battle_boss",
     "imageName": "as_to_battle_boss.png",
     "roiFront": "1111,248,37,136",
-    "roiBack": "973,174,234,327",
+    "roiBack": "979,142,234,327",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "点击进入boss战斗页面"

+ 4 - 4
tasks/ActivityShikigami/assets.py

@@ -46,9 +46,9 @@ class ActivityShikigamiAssets:
 	# 红色退出 
 	I_RED_EXIT = RuleImage(roi_front=(1162,96,39,38), roi_back=(1120,49,110,135), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_red_exit.png")
 	# 进入主要的战斗界面 
-	I_TO_BATTLE_MAIN = RuleImage(roi_front=(600,418,38,152), roi_back=(499,347,238,269), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_to_battle_main.png")
+	I_TO_BATTLE_MAIN = RuleImage(roi_front=(302,178,98,111), roi_back=(223,110,238,269), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_to_battle_main.png")
 	# 点击进入boss战斗页面 
-	I_TO_BATTLE_BOSS = RuleImage(roi_front=(1111,248,37,136), roi_back=(973,174,234,327), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_to_battle_boss.png")
+	I_TO_BATTLE_BOSS = RuleImage(roi_front=(1111,248,37,136), roi_back=(979,142,234,327), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_to_battle_boss.png")
 	# description 
 	I_CHECK_BATTLE_MAIN = RuleImage(roi_front=(50,642,62,58), roi_back=(1,510,415,203), threshold=0.65, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_battle_main.png")
 	# description 
@@ -94,9 +94,9 @@ class ActivityShikigamiAssets:
 	# 挑战 
 	O_FIRE = RuleOcr(roi=(1135,599,85,49), area=(1123,570,106,100), mode="Single", method="Default", keyword="挑战", name="fire")
 	# 体力的数量检测 
-	O_REMAIN_AP = RuleOcr(roi=(944,28,63,27), area=(943,26,63,30), mode="DigitCounter", method="Default", keyword="", name="remain_ap")
+	O_REMAIN_AP = RuleOcr(roi=(584,17,63,27), area=(583,16,63,30), mode="DigitCounter", method="Default", keyword="", name="remain_ap")
 	# 活动体力的剩余检测 
-	O_REMAIN_PASS = RuleOcr(roi=(563,26,50,29), area=(563,26,49,28), mode="DigitCounter", method="Default", keyword="", name="remain_pass")
+	O_REMAIN_PASS = RuleOcr(roi=(791,18,50,29), area=(791,18,49,28), mode="DigitCounter", method="Default", keyword="", name="remain_pass")
 	# 还有多少次购买体力的机会 
 	O_REMAIN_BUY = RuleOcr(roi=(808,531,39,42), area=(808,531,39,42), mode="DigitCounter", method="Default", keyword="", name="remain_buy")
 	# 活动票数(没有百分比) 

+ 38 - 38
tasks/ActivityShikigami/config.py

@@ -36,25 +36,25 @@ def check_soul_by_ocr(enable_switch: bool, group_team: str, label: str):
 
 
 class SwitchSoulConfig(BaseModel):
-    enable_switch_pass: bool = Field(default=False, description='是否切换门票爬塔御魂')
-    pass_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
-    enable_switch_pass_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
-    pass_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-
-    enable_switch_ap: bool = Field(default=False, description='是否切换体力爬塔御魂')
-    ap_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
-    enable_switch_ap_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
-    ap_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-
-    enable_switch_boss: bool = Field(default=False, description='是否切换boss爬塔御魂')
-    boss_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
-    enable_switch_boss_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
-    boss_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-
-    enable_switch_ap100: bool = Field(default=False, description='是否切换100体爬塔御魂')
-    ap100_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
-    enable_switch_ap100_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
-    ap100_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
+    enable_switch_pass: bool = Field(default=False, description='enable_switch_pass_help')
+    pass_group_team: str = Field(default='-1,-1', description='pass_group_team_help')
+    enable_switch_pass_by_name: bool = Field(default=False, description='enable_switch_pass_by_name_help')
+    pass_group_team_name: str = Field(default='', description='pass_group_team_name_help')
+
+    enable_switch_ap: bool = Field(default=False, description='enable_switch_ap_help')
+    ap_group_team: str = Field(default='-1,-1', description='ap_group_team_help')
+    enable_switch_ap_by_name: bool = Field(default=False, description='enable_switch_ap_by_name_help')
+    ap_group_team_name: str = Field(default='', description='ap_group_team_name_help')
+
+    enable_switch_boss: bool = Field(default=False, description='enable_switch_boss_help')
+    boss_group_team: str = Field(default='-1,-1', description='boss_group_team_help')
+    enable_switch_boss_by_name: bool = Field(default=False, description='enable_switch_boss_by_name_help')
+    boss_group_team_name: str = Field(default='', description='boss_group_team_name_help')
+
+    enable_switch_ap100: bool = Field(default=False, description='enable_switch_ap100_help')
+    ap100_group_team: str = Field(default='-1,-1', description='ap100_group_team_help')
+    enable_switch_ap100_by_name: bool = Field(default=False, description='enable_switch_ap100_by_name_help')
+    ap100_group_team_name: str = Field(default='', description='ap100_group_team_name_help')
 
     # @model_validator(mode='after')
     def validate_switch_soul(self):
@@ -75,25 +75,25 @@ class SwitchSoulConfig(BaseModel):
 
 
 class GeneralBattleConfig(BaseModel):
-    enable_pass_preset: bool = Field(default=False, description='是否切换门票爬塔预设, 仅数字切换御魂可用')
-    enable_pass_green: bool = Field(default=False, description='是否开启门票爬塔绿标')
-    pass_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='门票爬塔绿标位置')
-    enable_pass_anti_detect: bool = Field(default=False, description='门票爬塔战斗过程是否随机点击或滑动')
-
-    enable_ap_preset: bool = Field(default=False, description='是否切换体力爬塔预设, 仅数字切换御魂可用')
-    enable_ap_green: bool = Field(default=False, description='是否开启体力爬塔绿标')
-    ap_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='体力爬塔绿标位置')
-    enable_ap_anti_detect: bool = Field(default=False, description='体力爬塔战斗过程是否随机点击或滑动')
-
-    enable_boss_preset: bool = Field(default=False, description='是否切换boss爬塔预设, 仅数字切换御魂可用')
-    enable_boss_green: bool = Field(default=False, description='是否开启boss爬塔绿标')
-    boss_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='boss爬塔绿标位置')
-    enable_boss_anti_detect: bool = Field(default=False, description='boss爬塔战斗过程是否随机点击或滑动')
-
-    enable_ap100_preset: bool = Field(default=False, description='是否切换100体爬塔预设, 仅数字切换御魂可用')
-    enable_ap100_green: bool = Field(default=False, description='是否开启100体爬塔绿标')
-    ap100_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='100体爬塔绿标位置')
-    enable_ap100_anti_detect: bool = Field(default=False, description='100体爬塔战斗过程是否随机点击或滑动')
+    enable_pass_preset: bool = Field(default=False, description='enable_pass_preset_help')
+    enable_pass_green: bool = Field(default=False, description='enable_pass_green_help')
+    pass_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='pass_green_mark_help')
+    enable_pass_anti_detect: bool = Field(default=False, description='enable_pass_anti_detect_help')
+
+    enable_ap_preset: bool = Field(default=False, description='enable_ap_preset_help')
+    enable_ap_green: bool = Field(default=False, description='enable_ap_green_help')
+    ap_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='ap_green_mark_help')
+    enable_ap_anti_detect: bool = Field(default=False, description='enable_ap_anti_detect_help')
+
+    enable_boss_preset: bool = Field(default=False, description='enable_boss_preset_help')
+    enable_boss_green: bool = Field(default=False, description='enable_boss_green_help')
+    boss_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='boss_green_mark_help')
+    enable_boss_anti_detect: bool = Field(default=False, description='enable_boss_anti_detect_help')
+
+    enable_ap100_preset: bool = Field(default=False, description='enable_ap100_preset_help')
+    enable_ap100_green: bool = Field(default=False, description='enable_ap100_green_help')
+    ap100_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='ap100_green_mark_help')
+    enable_ap100_anti_detect: bool = Field(default=False, description='enable_ap100_anti_detect_help')
 
 
 class ActivityShikigami(ConfigBase):

+ 4 - 4
tasks/ActivityShikigami/fire/ocr.json

@@ -10,8 +10,8 @@
   },
   {
     "itemName": "remain_ap",
-    "roiFront": "944,28,63,27",
-    "roiBack": "943,26,63,30",
+    "roiFront": "584,17,63,27",
+    "roiBack": "583,16,63,30",
     "mode": "DigitCounter",
     "method": "Default",
     "keyword": "",
@@ -19,8 +19,8 @@
   },
   {
     "itemName": "remain_pass",
-    "roiFront": "563,26,50,29",
-    "roiBack": "563,26,49,28",
+    "roiFront": "791,18,50,29",
+    "roiBack": "791,18,49,28",
     "mode": "DigitCounter",
     "method": "Default",
     "keyword": "",

+ 4 - 47
tasks/ActivityShikigami/script_task.py

@@ -211,7 +211,7 @@ class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikiga
             if self.start_battle():
                 continue
 
-        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=4.5)
 
     def _run_ap(self):
         """
@@ -244,7 +244,7 @@ class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikiga
             if self.start_battle():
                 continue
 
-        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=1)
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_MAIN, interval=4.5)
 
     def _run_boss(self):
         """
@@ -269,7 +269,7 @@ class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikiga
             if self.start_battle():
                 continue
 
-        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_BOSS, interval=1)
+        self.ui_click(self.I_UI_BACK_YELLOW, stop=self.I_TO_BATTLE_BOSS, interval=4.5)
 
     def _run_ap100(self):
         """
@@ -297,50 +297,7 @@ class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikiga
         # 运行战斗
         self.run_general_battle(config=self.get_general_battle_conf())
 
-    # def battle_wait(self, random_click_swipt_enable: bool) -> bool:
-    #     # 通用战斗结束判断
-    #     self.device.stuck_record_add("BATTLE_STATUS_S")
-    #     self.device.click_record_clear()
-    #     logger.info(f"Start {self.climb_type} battle process")
-    #     self.count_map[self.climb_type] = self.current_count
-    #     for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
-    #         btn.name = "BATTLE_RANDOM"
-    #     ok_cnt, max_retry = 0, 8
-    #     while 1:
-    #         sleep(random.uniform(0.5, 1.5))
-    #         self.screenshot()
-    #         # 达到最大重试次数则直接交给上层处理
-    #         if ok_cnt > max_retry:
-    #             break
-    #         # 识别到挑战说明已经退出战斗
-    #         if ok_cnt > 0 and self.ocr_appear(self.O_FIRE):
-    #             return True
-    #         # 战斗失败
-    #         if self.appear(self.I_FALSE):
-    #             logger.warning("Battle failed")
-    #             self.ui_click_until_smt_disappear(self.random_reward_click(click_now=False), self.I_FALSE, interval=1.5)
-    #             return False
-    #         # 战斗成功
-    #         if self.appear_then_click(self.I_WIN, interval=2):
-    #             continue
-    #         #  出现 “魂” 和 紫蛇皮
-    #         if self.appear(self.I_REWARD) or self.appear(self.I_REWARD_PURPLE_SNAKE_SKIN) or \
-    #                 self.appear(self.I_REWARD_GOLD) or self.appear(self.I_REWARD_GOLD_SNAKE_SKIN):
-    #             self.random_reward_click(exclude_click=[self.C_RANDOM_TOP, self.C_RANDOM_LEFT])
-    #             ok_cnt += 1
-    #             continue
-    #         # 已经不在战斗中了, 且奖励也识别过了, 则随机点击
-    #         if ok_cnt > 3 and not self.is_in_battle(False):
-    #             self.random_reward_click(exclude_click=[self.C_RANDOM_TOP, self.C_RANDOM_LEFT])
-    #             self.device.stuck_record_clear()
-    #             ok_cnt += 1
-    #             continue
-    #         # 战斗中随机滑动
-    #         if ok_cnt == 0 and random_click_swipt_enable:
-    #             self.random_click_swipt()
-    #     return True
-
-    @battle_wait_strategy('reserve_default', 'idle_default', failure='default', success='soul')
+    @battle_wait_strategy(success='activity')
     def battle_wait(self, *args, **kwargs):
         return self.battle_wait_with_strategy(*args, **kwargs)
 

+ 4 - 4
tasks/BondlingFairyland/general_invite.py

@@ -303,8 +303,8 @@ class GeneralInvite(BaseTask, BondlingFairylandAssets, GeneralInviteAssets):
         self.screenshot()
         self.O_FRIEND_NAME_1.keyword = name
         self.O_FRIEND_NAME_2.keyword = name
-        appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2)
-        appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2)
+        appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2, exact=True)
+        appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2, exact=True)
         if not appear_1 and not appear_2:
             logger.info('Current page no friend')
             return False
@@ -313,8 +313,8 @@ class GeneralInvite(BaseTask, BondlingFairylandAssets, GeneralInviteAssets):
             self.screenshot()
             if self.appear(self.I_SELECTED):
                 break
-            appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2)
-            appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2)
+            appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2, exact=True)
+            appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2, exact=True)
 
         return True
 

+ 1 - 1
tasks/BudokaiTournament/assets.py

@@ -11,7 +11,7 @@ class BudokaiTournamentAssets:
 
 
 	# Click Rule Assets
-	# Close cultivation drills boss detail
+	# Close cultivation drills boss detail 
 	C_BOSS_DETAIL_CLOSE = RuleClick(roi_front=(1182,73,47,43), roi_back=(1182,73,47,43), name="boss_detail_close")
 
 

+ 82 - 0
tasks/Component/GeneralBattle/assets.py

@@ -166,3 +166,85 @@ class GeneralBattleAssets:
 	S_BATTLE_RANDOM_RIGHT = RuleSwipe(roi_front=(719,138,417,392), roi_back=(237,163,387,394), mode="default", name="battle_random_right")
 
 
+	# Click Rule Assets
+	# 右上角的聊天信息 
+	C_END_MESSAGE_RIGHT_TOP = RuleClick(roi_front=(846,4,404,34), roi_back=(846,4,404,34), name="end_message_right_top")
+	# description 
+	C_END_BUFF_AREA_1 = RuleClick(roi_front=(150,638,295,41), roi_back=(150,638,295,41), name="end_buff_area_1")
+	# description 
+	C_END_BUFF_AREA_2 = RuleClick(roi_front=(457,635,273,43), roi_back=(457,635,273,43), name="end_buff_area_2")
+	# 給地鬼的 
+	C_END_AREA_BOSS = RuleClick(roi_front=(1093,550,127,120), roi_back=(1093,550,127,120), name="end_area_boss")
+	# description 
+	C_END_BUFF_AREA_3 = RuleClick(roi_front=(764,636,282,42), roi_back=(764,636,282,42), name="end_buff_area_3")
+	# 记录通关时间的按钮 
+	C_END_SOUL_RECORD = RuleClick(roi_front=(317,561,53,49), roi_back=(317,561,53,49), name="end_soul_record")
+	# 战斗数据详细 
+	C_END_SOUL_DETAILS = RuleClick(roi_front=(383,559,52,49), roi_back=(383,559,52,49), name="end_soul_details")
+	# 单人好友头像 
+	C_END_FRIENDS_1 = RuleClick(roi_front=(581,402,118,135), roi_back=(581,402,118,135), name="end_friends_1")
+	# 多人好友头像第一个 
+	C_END_FRIENDS_21 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_friends_21")
+	# description 
+	C_END_FRIENDS_22 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_friends_22")
+	# description 
+	C_END_FRIENDS_31 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_friends_31")
+	# description 
+	C_END_FRIENDS_32 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_friends_32")
+	# description 
+	C_END_FRIENDS_23 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_friends_23")
+
+
+	# Click Rule Assets
+	# description 
+	C_END_1_1 = RuleClick(roi_front=(266,175,100,100), roi_back=(266,175,100,100), name="end_1_1")
+	# description 
+	C_END_1_2 = RuleClick(roi_front=(400,174,100,100), roi_back=(400,174,100,100), name="end_1_2")
+	# description 
+	C_END_1_3 = RuleClick(roi_front=(536,173,100,100), roi_back=(536,173,100,100), name="end_1_3")
+	# description 
+	C_END_1_4 = RuleClick(roi_front=(671,173,100,100), roi_back=(671,173,100,100), name="end_1_4")
+	# description 
+	C_END_1_5 = RuleClick(roi_front=(805,174,100,100), roi_back=(805,174,100,100), name="end_1_5")
+	# description 
+	C_END_1_6 = RuleClick(roi_front=(942,175,100,100), roi_back=(942,175,100,100), name="end_1_6")
+	# description 
+	C_END_2_1 = RuleClick(roi_front=(266,310,100,100), roi_back=(266,310,100,100), name="end_2_1")
+	# description 
+	C_END_2_2 = RuleClick(roi_front=(401,310,100,100), roi_back=(401,310,100,100), name="end_2_2")
+	# description 
+	C_END_2_3 = RuleClick(roi_front=(536,309,100,100), roi_back=(536,309,100,100), name="end_2_3")
+	# description 
+	C_END_2_4 = RuleClick(roi_front=(671,311,100,100), roi_back=(671,311,100,100), name="end_2_4")
+	# description 
+	C_END_2_5 = RuleClick(roi_front=(806,310,100,100), roi_back=(806,310,100,100), name="end_2_5")
+	# description 
+	C_END_2_6 = RuleClick(roi_front=(942,312,100,100), roi_back=(942,312,100,100), name="end_2_6")
+	# description 
+	C_END_3_1 = RuleClick(roi_front=(266,444,100,100), roi_back=(266,444,100,100), name="end_3_1")
+	# description 
+	C_END_3_2 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_3_2")
+	# description 
+	C_END_3_3 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_3_3")
+	# description 
+	C_END_3_4 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_3_4")
+	# description 
+	C_END_3_5 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_3_5")
+	# description 
+	C_END_3_6 = RuleClick(roi_front=(0,0,100,100), roi_back=(0,0,100,100), name="end_3_6")
+	# 其实贪吃鬼这个点了也是没事儿 
+	C_END_GREED = RuleClick(roi_front=(138,16,512,93), roi_back=(138,16,512,93), name="end_greed")
+
+
+	# Click Rule Assets
+	# 获得奖励中间的区域 
+	C_END_ACTIVITY_REWARD = RuleClick(roi_front=(400,250,493,226), roi_back=(401,252,494,230), name="end_activity_reward")
+
+
+	# Image Rule Assets
+	# description 
+	I_END_FIX_1 = RuleImage(roi_front=(896,251,218,64), roi_back=(119,66,1136,620), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gw/gw_end_fix_1.png")
+	# description 
+	I_END_FIX_2 = RuleImage(roi_front=(800,251,100,33), roi_back=(32,90,1137,547), threshold=0.7, method="Template matching", file="./tasks/Component/GeneralBattle/gw/gw_end_fix_2.png")
+
+

+ 192 - 54
tasks/Component/GeneralBattle/battle_wait.py

@@ -1,16 +1,20 @@
 import random
 import time
+import copy
 
 
 from functools import wraps
 from dataclasses import dataclass
 from typing import TypeVar, ParamSpec, Callable
 from enum import Enum, auto
+from cached_property import cached_property
 
 from module.logger import logger
 from module.base.timer import Timer
+from module.atom.click import RuleClickExclude
 
 from tasks.base_task import BaseTask
+from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
 
 
 P = ParamSpec('P')
@@ -24,6 +28,7 @@ class HookSignal(Enum):
 
 @dataclass
 class BattleWaitContext:
+    options: dict[str: dict] = None
     completion = False
     success = False
 
@@ -190,9 +195,28 @@ class battle_wait_strategy:
     首次装饰 func 初始化 battle_wait_plan
     """
     battle_wait_plan: BattleWaitPlan = None
+    options: dict[str: dict] = {
+        'success': {
+            'reward_exclude_click_1': ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',],
+            'reward_exclude_click_2': ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
+                                       'C_END_1_1', 'C_END_1_2', 'C_END_1_3', 'C_END_1_4', 'C_END_1_5', 'C_END_1_6',
+                                       ]
+        }
+    }
 
 
     def __init__(self, *arg, **kwargs):
+        self._temp_options = kwargs.pop('options', None)
+        if self._temp_options is not None:
+            if not isinstance(self._temp_options, dict):
+                raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
+            for key, value in self._temp_options.items():
+                if not isinstance(key, str):
+                    raise
+                if not isinstance(value, dict):
+                    raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
+            battle_wait_strategy.options.update(self._temp_options)
+
         self._temp_battle_wait_plan = None
         if battle_wait_strategy.battle_wait_plan is None:
             # 首次装饰 func 初始化 battle_wait_plan
@@ -210,11 +234,14 @@ class battle_wait_strategy:
 
     def __exit__(self, *exc):
         battle_wait_strategy.battle_wait_plan = self._previous_plan
+        self._temp_options = None
         return False
 
     def __str__(self):
         temp_plan = getattr(self, '_temp_battle_wait_plan', None)
         default_plan = getattr(self, 'battle_wait_plan', None)
+        options = dict(battle_wait_strategy.options or {})
+        options.update(self._temp_options or {})
 
         if temp_plan is not None:
             plan = temp_plan
@@ -224,11 +251,12 @@ class battle_wait_strategy:
             scope = 'decorator'
 
         if plan is None:
-            return f'{type(self).__name__}(plan=None)'
+            return f'{type(self).__name__}(options={options}, plan=None)'
 
         return (
             f'{type(self).__name__}('
             f'scope={scope}, '
+            f'options={options}, '
             f'plan=\n{plan}'
             f')'
         )
@@ -251,19 +279,69 @@ class battle_wait_strategy:
                     if key == 'random_click_swipt_enable' and value:
                         override_kwargs['randomclick'] = 'default'
                         override_args.append('randomclick_default')
-                battle_wait_strategy.battle_wait_plan =\
-                    battle_wait_strategy.battle_wait_plan.override(*override_args)
+                current_plan = copy.deepcopy(battle_wait_strategy.battle_wait_plan)
+                current_plan = current_plan.override(*override_args)
+            else:
+                current_plan = battle_wait_strategy.battle_wait_plan
             # -----------------------------------------------------------------------
             # kwargs.setdefault(
             #     'battle_wait_plan',
             #     self.battle_wait_plan,
             # )
-            return func(owner, battle_wait_plan=battle_wait_strategy.battle_wait_plan)
+            options = dict(battle_wait_strategy.options or {})
+            options.update(self._temp_options or {})
+            return func(owner, battle_wait_plan=current_plan, options=options) \
+                if options else func(owner, battle_wait_plan=current_plan)
 
         return inner
 
+    def with_options(self, options: dict) -> "battle_wait_strategy":
+        if not isinstance(options, dict):
+            raise
+        for event, v in options.items():
+            if not isinstance(event, str):
+                raise TypeError()
+            if not isinstance(v, dict):
+                raise TypeError()
+        # 先装饰器, 后临时变量
+        if battle_wait_strategy.options is None:
+            battle_wait_strategy.options = options
+            self._temp_options = None
+        else:
+            self._temp_options = options
+        return self
+
+
+class BattleWait(BaseTask, GeneralBattleAssets):
+
+    # ------------------------------------------------------------------------------------------------------------------
+    @cached_property
+    def exclude_button_stage_1(self):
+        return ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2',
+                'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
+                ]
+
+    @cached_property
+    def exclude_button_stage_2(self):
+        return ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
+                'C_END_1_1', 'C_END_1_2', 'C_END_1_3', 'C_END_1_4', 'C_END_1_5', 'C_END_1_6',
+                ]
+
+    def reward_exclude_click(self, areas: list[str] = None, name: str = 'success_exclude_click') -> RuleClickExclude:
+        inputs = []
+        for area in areas:
+            click = getattr(self, area, None)
+            if click is None:
+                raise ValueError(f'Unknown success exclusion click: {area!r}')
+            inputs.append(click)
+        return RuleClickExclude(inputs, name=name)
+
+    def reward_exclude_click_1(self, areas: list[str] = None) -> RuleClickExclude:
+        return self.reward_exclude_click(areas, name='reward_exclude_click_1')
+
+    def reward_exclude_click_2(self, areas: list[str] = None) -> RuleClickExclude:
+        return self.reward_exclude_click(areas, name='reward_exclude_click_2')
 
-class BattleWait(BaseTask):
     # build in
     # ------------------------------------------------------------------------------------------------------------------
     def _bw_setup_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
@@ -273,6 +351,17 @@ class BattleWait(BaseTask):
         self.device.stuck_record_add('BATTLE_STATUS_S')
         self.device.click_record_clear()
         logger.info('Start battle process')
+        options: dict[str, dict] = getattr(bw_ctx, 'options', None) or {}
+        success_options = options.get('success') or {}
+        if not isinstance(success_options, dict):
+            raise TypeError("battle wait option 'success' must be a dict")
+        excludes = success_options.get('excludes')
+        exclude_stage_1 = excludes if excludes is not None else self.exclude_button_stage_1
+        exclude_stage_2 = excludes if excludes is not None else self.exclude_button_stage_2
+        self._reward_exclude_click_1 = self.reward_exclude_click_1(exclude_stage_1)
+        self._reward_exclude_click_2 = self.reward_exclude_click_2(exclude_stage_2)
+        # print(self._reward_exclude_click_1)
+        # print(self._reward_exclude_click_2)
         return HookSignal.DONE
 
     def _bw_completion_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
@@ -282,32 +371,44 @@ class BattleWait(BaseTask):
         return HookSignal.CONTINUE
 
     def _bw_interrupt_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
+        # 比如 御魂溢出
         return HookSignal.CONTINUE
 
     def _bw_success_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
         if self.appear_then_click(self.I_WIN, interval=0.8):
+            self.click(self._reward_exclude_click_1)
             return HookSignal.CONTINUE
-        appear_ghost, appear_reward, appear_gold = (
+        appear_ghost, appear_reward, appear_gold, appear_skin = (
             self.appear(self.I_GREED_GHOST),
             self.appear(self.I_REWARD),
-            self.appear(self.I_REWARD_GOLD)
+            self.appear(self.I_REWARD_GOLD),
+            self.appear(self.I_REWARD_GOLD_SNAKE_SKIN)
         )
-        if not any([appear_ghost, appear_reward, appear_gold]):
+        if not any([appear_ghost, appear_reward, appear_gold, appear_skin]):
             return HookSignal.CONTINUE
         logger.info('Win battle')
         timer = Timer(20).start()
         while 1:
             self.screenshot()
 
-            _appear_ghost, _appear_reward, _appear_gold = (
+            # 不小心点到了具体的奖励,他会弹出这个物品的详细描述 里面必定包含有“获取途径”
+            if self.appear(self.I_END_FIX_1) or self.appear(self.I_END_FIX_2):
+                self.click(self.C_REWARD_2, interval=1.5)
+
+            _appear_ghost, _appear_reward, _appear_gold, _appear_skin = (
                 self.appear(self.I_GREED_GHOST, threshold=0.6),
                 self.appear(self.I_REWARD),
-                self.appear(self.I_REWARD_GOLD)
+                self.appear(self.I_REWARD_GOLD),
+                self.appear(self.I_REWARD_GOLD_SNAKE_SKIN)
             )
-            # logger.info(f'_appear_ghost: {_appear_ghost} _appear_reward: {_appear_reward} _appear_gold: {_appear_gold}')
-            if any([_appear_ghost, _appear_reward, _appear_gold]):
-                action_click = random.choice([self.C_REWARD_1, self.C_REWARD_2, self.C_REWARD_3])
-                self.click(action_click, interval=1.5)
+            # logger.info(f'_appear_ghost: {_appear_ghost} _appear_reward: {_appear_reward} _appear_gold: {_appear_gold} _appear_skin: {_appear_skin}')
+            if any([_appear_ghost, _appear_reward, _appear_gold, _appear_skin]):
+                if random.random() < 0.02:
+                    # 有一定的概率专门点击具体的奖励物品
+                    x, y = self._reward_exclude_click_2.coord_in_excluded(None)
+                    self.device.click(x=x, y=y, control_name='reward_item')
+                    continue
+                self.click(self._reward_exclude_click_2, interval=1.5)
             else:
                 logger.info('Get all reward')
                 bw_ctx.success = True
@@ -324,8 +425,8 @@ class BattleWait(BaseTask):
             logger.warning('False battle')
             self.ui_click_until_disappear(self.I_FALSE)
             bw_ctx.completion = True
-            return True
-        return True
+            return HookSignal.CONTINUE
+        return HookSignal.CONTINUE
 
     def _bw_idle_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
         return HookSignal.CONTINUE
@@ -334,6 +435,8 @@ class BattleWait(BaseTask):
         return HookSignal.CONTINUE
 
     def _bw_randomclick_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
+        if not self.is_in_battle(is_screenshot=False):
+            return HookSignal.CONTINUE
         if 0 <= random.randint(0, 500) <= 20:  # 百分之4的概率
             rand_type = random.randint(0, 2)
             match rand_type:
@@ -352,6 +455,11 @@ class BattleWait(BaseTask):
     # custom
     # ------------------------------------------------------------------------------------------------------------------
     def _bw_success_soul(self, bw_ctx: BattleWaitContext) -> HookSignal:
+        options: dict[str, dict] = getattr(bw_ctx, 'options', None) or {}
+        success_options = options.get('success') or {}
+        if not isinstance(success_options, dict):
+            raise TypeError("battle wait option 'success' must be a dict")
+        action_click = self.reward_exclude_click(success_options.get('excludes'))
         if self.appear_then_click(self.I_WIN, interval=0.8):
             return HookSignal.CONTINUE
         appear_ghost, appear_reward, appear_gold, appear_skin = (
@@ -375,7 +483,6 @@ class BattleWait(BaseTask):
             )
             # logger.info(f'_appear_ghost: {_appear_ghost} _appear_reward: {_appear_reward} _appear_gold: {_appear_gold} _appear_skin: {_appear_skin}')
             if any([_appear_ghost, _appear_reward, _appear_gold, _appear_skin]):
-                action_click = random.choice([self.C_REWARD_1, self.C_REWARD_2, self.C_REWARD_3])
                 self.click(action_click, interval=1.5)
             else:
                 logger.info('Get all reward')
@@ -387,36 +494,56 @@ class BattleWait(BaseTask):
                 break
         return HookSignal.CONTINUE
 
+    @cached_property
+    def exclude_click_activity(self, areas: list[str] = None) -> RuleClickExclude:
+        inputs = []
+        for area in ['C_END_MESSAGE_RIGHT_TOP', 'C_END_ACTIVITY_REWARD']:
+            click = getattr(self, area, None)
+            if click is None:
+                raise ValueError(f'Unknown success exclusion click: {area!r}')
+            inputs.append(click)
+        return RuleClickExclude(inputs, name='exclude_click_activity', strategy='rejection', distribution='uniform')
+
+    def _bw_success_activity(self, bw_ctx: BattleWaitContext) -> HookSignal:
+        """
+        战斗结算是有 “获得奖励” 的适用
+        """
+        if not self.appear(self.I_UI_REWARD):
+            return HookSignal.CONTINUE
+        self.screenshot()
+        if not self.appear(self.I_UI_REWARD):
+            return HookSignal.CONTINUE
+
+        logger.info('Win battle')
+        timer = Timer(20).start()
+        while 1:
+            self.screenshot()
+
+            # 不小心点到了具体的奖励,他会弹出这个物品的详细描述 里面必定包含有“获取途径”
+            if self.appear(self.I_END_FIX_1) or self.appear(self.I_END_FIX_2):
+                self.click(self.C_REWARD_2, interval=1.5)
+
+            if self.appear(self.I_UI_REWARD):
+                if random.random() < 0.02:
+                    # 有一定的概率专门点击具体的奖励物品
+                    x, y = self.exclude_click_activity.coord_in_excluded(['C_END_ACTIVITY_REWARD'])
+                    self.device.click(x=x, y=y, control_name='reward_item')
+                    continue
+                self.click(self.exclude_click_activity, interval=1.5)
+            elif not self.appear(self.I_END_FIX_2):
+                self.screenshot()
+                if self.appear(self.I_UI_REWARD) or self.appear(self.I_END_FIX_2):
+                    continue
+                logger.info('Get all reward')
+                bw_ctx.success = True
+                bw_ctx.completion = True
+                return HookSignal.DONE
+
+            if timer.reached_and_reset():
+                logger.warning('battle ')
+                break
+        return HookSignal.CONTINUE
 
-    # def _bw_idle_random_click(self, bw_ctx: BattleWaitContext):
-    #     if 0 <= random.randint(0, 500) <= 3:  # 百分之4的概率
-    #         rand_type = random.randint(0, 2)
-    #         match rand_type:
-    #             case 0:
-    #                 self.click(self.C_RANDOM_CLICK, interval=20)
-    #             case 1:
-    #                 self.swipe(self.S_BATTLE_RANDOM_LEFT, interval=20)
-    #             case 2:
-    #                 self.swipe(self.S_BATTLE_RANDOM_RIGHT, interval=20)
-    #         # 重新设置为长战斗
-    #         # self.device.stuck_record_add('BATTLE_STATUS_S')
-    #     else:
-    #         time.sleep(0.4)  # 这样的好像不对
-    #
-    # def _bw_random_click(self, bw_ctx: BattleWaitContext):
-    #     if 0 <= random.randint(0, 500) <= 3:  # 百分之4的概率
-    #         rand_type = random.randint(0, 2)
-    #         match rand_type:
-    #             case 0:
-    #                 self.click(self.C_RANDOM_CLICK, interval=20)
-    #             case 1:
-    #                 self.swipe(self.S_BATTLE_RANDOM_LEFT, interval=20)
-    #             case 2:
-    #                 self.swipe(self.S_BATTLE_RANDOM_RIGHT, interval=20)
-    #         # 重新设置为长战斗
-    #         # self.device.stuck_record_add('BATTLE_STATUS_S')
-    #     else:
-    #         time.sleep(0.4)  # 这样的好像不对
 
     # ------------------------------------------------------------------------------------------------------------------
     def battle_wait_with_strategy(self, *args, **kwargs) -> bool:
@@ -443,15 +570,29 @@ class BattleWait(BaseTask):
         但是必须要实现对应的hook 上面的比如 _bw_yyy_default() 以及 _bw_abcd_edf()
 
         hook 可以自定义顺序,比如 battle_wait_strategy(sequence='completion > interrupt > success > failure > idle')
-        如果指定sequence, 新增的event会按照传参时候从左到右排序,左边高优先级,新增的会插入到 failure 和 idle 之间
+        如果没有指定sequence, 新增的event会按照传参时候从左到右排序,左边高优先级,新增的会插入到 failure 和 idle 之间
+
+        如果希望每一个hook带上参数:
+        1. 可以在装饰器定义 @battle_wait_strategy(options = options)
+        2. 上下文带上  with battle_wait_strategy(...).with_options(options)
+        options: dict[str: dict] = {
+            "setup": {...}
+            ...
+        }
+
         """
+        bw_ctx = BattleWaitContext()
+
         battle_wait_plan = kwargs.get('battle_wait_plan')
         if battle_wait_plan is None:
             battle_wait_plan = BattleWaitPlan()
         # print(battle_wait_plan)
         # print(battle_wait_plan.sequence_function_names())
+        options = kwargs.get('options', None)
+        if options is not None:
+            bw_ctx.options = options
+            # logger.info('options: {}'.format(options))
 
-        bw_ctx = BattleWaitContext()
         setup_func = getattr(self, battle_wait_plan.function_setup_name, self._bw_setup_default)
         setup_func(bw_ctx)
         handlers = [getattr(self, func_name, None) for func_name in battle_wait_plan.sequence_function_names()]
@@ -462,6 +603,8 @@ class BattleWait(BaseTask):
                 result = handler(bw_ctx)
                 if handler.__name__.startswith('_bw_completion') and result == HookSignal.DONE:
                     return True
+                if result == HookSignal.CONTINUE:
+                    continue
 
             # bw_ctx.completion = True
 
@@ -485,7 +628,7 @@ if __name__ == '__main__':
 
     test_battle_wait = TestBattleWait(c,d)
     test_battle_wait.battle_wait(random_click_swipt_enable=1)
-    with battle_wait_strategy(sequence='completion > interrupt > success > failure > idle'):
+    with battle_wait_strategy(sequence='completion > interrupt > success > failure > idle').with_options(options={"setup": {"11": "11"}}):
         test_battle_wait.battle_wait()
 
 
@@ -495,8 +638,3 @@ if __name__ == '__main__':
 
 
 
-
-
-
-
-

+ 1 - 1
tasks/Component/GeneralBattle/general_battle.py

@@ -20,7 +20,7 @@ from tasks.Component.GeneralBattle.battle_wait import BattleWait
 from module.logger import logger
 
 
-class GeneralBattle(BattleWait, GeneralBuff, GeneralBattleAssets):
+class GeneralBattle(BattleWait, GeneralBuff):
     """
     使用这个通用的战斗必须要求这个任务的config有config_general_battle
     """

+ 80 - 0
tasks/Component/GeneralBattle/gw/click.json

@@ -0,0 +1,80 @@
+[
+  {
+    "itemName": "end_message_right_top",
+    "roiFront": "846,4,404,34",
+    "roiBack": "846,4,404,34",
+    "description": "右上角的聊天信息"
+  },
+  {
+    "itemName": "end_buff_area_1",
+    "roiFront": "150,638,295,41",
+    "roiBack": "150,638,295,41",
+    "description": "description"
+  },
+  {
+    "itemName": "end_buff_area_2",
+    "roiFront": "457,635,273,43",
+    "roiBack": "457,635,273,43",
+    "description": "description"
+  },
+  {
+    "itemName": "end_area_boss",
+    "roiFront": "1093,550,127,120",
+    "roiBack": "1093,550,127,120",
+    "description": "給地鬼的"
+  },
+  {
+    "itemName": "end_buff_area_3",
+    "roiFront": "764,636,282,42",
+    "roiBack": "764,636,282,42",
+    "description": "description"
+  },
+  {
+    "itemName": "end_soul_record",
+    "roiFront": "317,561,53,49",
+    "roiBack": "317,561,53,49",
+    "description": "记录通关时间的按钮"
+  },
+  {
+    "itemName": "end_soul_details",
+    "roiFront": "383,559,52,49",
+    "roiBack": "383,559,52,49",
+    "description": "战斗数据详细"
+  },
+  {
+    "itemName": "end_friends_1",
+    "roiFront": "581,402,118,135",
+    "roiBack": "581,402,118,135",
+    "description": "单人好友头像"
+  },
+  {
+    "itemName": "end_friends_21",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "多人好友头像第一个"
+  },
+  {
+    "itemName": "end_friends_22",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_friends_31",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_friends_32",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_friends_23",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  }
+]

+ 116 - 0
tasks/Component/GeneralBattle/gw/click2.json

@@ -0,0 +1,116 @@
+[
+  {
+    "itemName": "end_1_1",
+    "roiFront": "266,175,100,100",
+    "roiBack": "266,175,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_1_2",
+    "roiFront": "400,174,100,100",
+    "roiBack": "400,174,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_1_3",
+    "roiFront": "536,173,100,100",
+    "roiBack": "536,173,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_1_4",
+    "roiFront": "671,173,100,100",
+    "roiBack": "671,173,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_1_5",
+    "roiFront": "805,174,100,100",
+    "roiBack": "805,174,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_1_6",
+    "roiFront": "942,175,100,100",
+    "roiBack": "942,175,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_2_1",
+    "roiFront": "266,310,100,100",
+    "roiBack": "266,310,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_2_2",
+    "roiFront": "401,310,100,100",
+    "roiBack": "401,310,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_2_3",
+    "roiFront": "536,309,100,100",
+    "roiBack": "536,309,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_2_4",
+    "roiFront": "671,311,100,100",
+    "roiBack": "671,311,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_2_5",
+    "roiFront": "806,310,100,100",
+    "roiBack": "806,310,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_2_6",
+    "roiFront": "942,312,100,100",
+    "roiBack": "942,312,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_3_1",
+    "roiFront": "266,444,100,100",
+    "roiBack": "266,444,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_3_2",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_3_3",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_3_4",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_3_5",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_3_6",
+    "roiFront": "0,0,100,100",
+    "roiBack": "0,0,100,100",
+    "description": "description"
+  },
+  {
+    "itemName": "end_greed",
+    "roiFront": "138,16,512,93",
+    "roiBack": "138,16,512,93",
+    "description": "其实贪吃鬼这个点了也是没事儿"
+  }
+]

+ 8 - 0
tasks/Component/GeneralBattle/gw/click_activity.json

@@ -0,0 +1,8 @@
+[
+  {
+    "itemName": "end_activity_reward",
+    "roiFront": "400,250,493,226",
+    "roiBack": "401,252,494,230",
+    "description": "获得奖励中间的区域"
+  }
+]

BIN
tasks/Component/GeneralBattle/gw/gw_end_fix_1.png


BIN
tasks/Component/GeneralBattle/gw/gw_end_fix_2.png


+ 20 - 0
tasks/Component/GeneralBattle/gw/image.json

@@ -0,0 +1,20 @@
+[
+  {
+    "itemName": "end_fix_1",
+    "imageName": "gw_end_fix_1.png",
+    "roiFront": "896,251,218,64",
+    "roiBack": "119,66,1136,620",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "end_fix_2",
+    "imageName": "gw_end_fix_2.png",
+    "roiFront": "800,251,100,33",
+    "roiBack": "32,90,1137,547",
+    "method": "Template matching",
+    "threshold": 0.7,
+    "description": "description"
+  }
+]

+ 4 - 5
tasks/Component/GeneralInvite/general_invite.py

@@ -316,8 +316,8 @@ class GeneralInvite(BaseTask, GeneralInviteAssets):
         self.screenshot()
         self.O_FRIEND_NAME_1.keyword = name
         self.O_FRIEND_NAME_2.keyword = name
-        appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2)
-        appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2)
+        appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2, exact=True)
+        appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2, exact=True)
         if not appear_1 and not appear_2:
             logger.info('Current page no friend')
             return False
@@ -326,8 +326,8 @@ class GeneralInvite(BaseTask, GeneralInviteAssets):
             self.screenshot()
             if self.appear(self.I_SELECTED):
                 break
-            appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2)
-            appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2)
+            appear_1 = self.ocr_appear_click(self.O_FRIEND_NAME_1, interval=2, exact=True)
+            appear_2 = self.ocr_appear_click(self.O_FRIEND_NAME_2, interval=2, exact=True)
 
         return True
 
@@ -652,4 +652,3 @@ if __name__ == '__main__':
     t.screenshot()
     print(t.appear(t.I_FIRE, threshold=0.8))
 
-

+ 2 - 0
tasks/DemonEncounter/assets.py

@@ -125,6 +125,8 @@ class DemonEncounterAssets:
 	# Ocr Rule Assets
 	# 计数已经开启多少的 
 	O_DE_COUNTER = RuleOcr(roi=(1204,685,48,34), area=(1204,685,48,34), mode="DigitCounter", method="Default", keyword="", name="de_counter")
+	# 现世逢魔顶部今日挑战次数X/1的最小识别区, 0/1表示已打过直接结束 
+	O_DE_CHALLENGE_COUNT = RuleOcr(roi=(680,68,75,36), area=(680,68,75,36), mode="Full", method="Default", keyword="", name="de_challenge_count")
 
 
 	# Click Rule Assets

+ 9 - 0
tasks/DemonEncounter/demon/ocr.json

@@ -7,5 +7,14 @@
     "method": "Default",
     "keyword": "",
     "description": "计数已经开启多少的"
+  },
+  {
+    "itemName": "de_challenge_count",
+    "roiFront": "680,68,75,36",
+    "roiBack": "680,68,75,36",
+    "mode": "Full",
+    "method": "Default",
+    "keyword": "",
+    "description": "现世逢魔顶部今日挑战次数X/1的最小识别区, 0/1表示已打过直接结束"
   }
 ]

+ 19 - 0
tasks/DemonEncounter/script_task.py

@@ -3,6 +3,7 @@
 # github https://github.com/runhey
 import time
 from time import sleep
+import re
 
 from enum import Enum
 from cached_property import cached_property
@@ -48,12 +49,30 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
             self.ui_goto(page_shikigami_records)
             self.checkout_soul()
         self.ui_goto(page_demon_encounter_realworld)
+        # 顶部"今日挑战次数:X/1"检测, 0/1表示今日已打过, 直接结束
+        if self.check_challenge_done():
+            logger.info('Challenge count 0/1, already challenged today')
+            self.set_next_run(task='DemonEncounter', success=True, finish=False)
+            raise TaskEnd('DemonEncounter')
         self.execute_lantern()
         self.execute_boss()
 
         self.set_next_run(task='DemonEncounter', success=True, finish=False)
         raise TaskEnd('DemonEncounter')
 
+    def check_challenge_done(self) -> bool:
+        """
+        OCR识别现世逢魔顶部"今日挑战次数:X/1"
+        :return: True表示0/1今日已打过
+        """
+        results = self.O_DE_CHALLENGE_COUNT.detect_and_ocr(self.device.image)
+        text = ''.join(r.ocr_text for r in results)
+        m = re.search(r'([01])\s*/\s*1', text)
+        if not m:
+            logger.warning(f'Challenge count not recognized: [{text}], continue by default')
+            return False
+        return m.group(1) == '0'
+
     def checkout_soul(self):
         """
         切换御魂

+ 8 - 0
tasks/EvoZone/script_task.py

@@ -13,6 +13,8 @@ from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.page import page_main, page_awake_zones, page_shikigami_records
 from tasks.EvoZone.assets import EvoZoneAssets
 from tasks.EvoZone.config import EvoZone, UserStatus, KirinType
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy
+
 from module.logger import logger
 from module.exception import TaskEnd
 
@@ -328,6 +330,12 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
         pass
 
 
+    @battle_wait_strategy()
+    def battle_wait(self, *args, **kwargs):
+        return self.battle_wait_with_strategy(*args, **kwargs)
+
+
+
 if __name__ == '__main__':
     from module.config.config import Config
     from module.device.device import Device

+ 2 - 3
tasks/GameUi/game_ui.py

@@ -289,9 +289,8 @@ class GameUi(BaseTask, GameUiAssets):
                     return False
                 if isinstance(button, list):
                     for idx, btn in enumerate(button):
-                        if attempts_list[idx] >= max_attempts_per_button:
-                            continue
-                        attempt =  self.appear_then_operate(btn, interval=0.8, skip_first_screenshot=False)
+                        click_interval = 2.5 if attempts_list[idx] >= max_attempts_per_button else 0.8
+                        attempt =  self.appear_then_operate(btn, interval=click_interval, skip_first_screenshot=False)
                         if attempt:
                             attempts_list[idx] += 1
                         # 只要第一个成功就跳出

+ 24 - 8
tasks/KekkaiActivation/script_task.py

@@ -398,14 +398,30 @@ class ScriptTask(KU, KekkaiActivationAssets):
         收卡的经验
         :return:
         """
-        self.appear_then_click(self.I_A_HARVEST_EXP)  # 如果到最后没有领的话有下面的一些图片
-        self.appear_then_click(self.I_A_HARVEST_FISH4)  # 斗鱼4/5区别不大 斗鱼的如果一直没有领的话
-        self.appear_then_click(self.I_A_HARVEST_KAIKO_4)  # 太鼓4
-        self.appear_then_click(self.I_A_HARVEST_KAIKO_3)  # 太鼓3
-        self.appear_then_click(self.I_A_HARVEST_KAIKO_6)  # 太鼓6
-        self.appear_then_click(self.I_A_HARVEST_FISH_6)  # 斗鱼6
-        self.appear_then_click(self.I_A_HARVEST_MOON_3)  # 太阴3
-        self.appear_then_click(self.I_A_HARVEST_FISH_3)  # 斗鱼三
+        cards = [
+            self.I_A_HARVEST_EXP,  # 如果到最后没有领的话有下面的一些图片
+            self.I_A_HARVEST_FISH4,  # 斗鱼4/5区别不大 斗鱼的如果一直没有领的话
+            self.I_A_HARVEST_KAIKO_4,  # 太鼓4
+            self.I_A_HARVEST_KAIKO_3,   # 太鼓3
+            self.I_A_HARVEST_KAIKO_6,  # 太鼓6
+            self.I_A_HARVEST_FISH_6,  # 斗鱼6
+            self.I_A_HARVEST_MOON_3,  # 太阴3
+            self.I_A_HARVEST_FISH_3,  # 斗鱼三
+        ]
+        for i in range(5):
+            self.screenshot()
+            appear = [ self.appear_then_click_multi_scale(card, threshold=0.7) for card in cards ]
+            if any(appear):
+                break
+        logger.info("")
+        # self.appear_then_click(self.I_A_HARVEST_EXP)  # 如果到最后没有领的话有下面的一些图片
+        # self.appear_then_click(self.I_A_HARVEST_FISH4)  # 斗鱼4/5区别不大 斗鱼的如果一直没有领的话
+        # self.appear_then_click(self.I_A_HARVEST_KAIKO_4)  # 太鼓4
+        # self.appear_then_click(self.I_A_HARVEST_KAIKO_3)  # 太鼓3
+        # self.appear_then_click(self.I_A_HARVEST_KAIKO_6)  # 太鼓6
+        # self.appear_then_click(self.I_A_HARVEST_FISH_6)  # 斗鱼6
+        # self.appear_then_click(self.I_A_HARVEST_MOON_3)  # 太阴3
+        # self.appear_then_click(self.I_A_HARVEST_FISH_3)  # 斗鱼三
 
 
 if __name__ == "__main__":

+ 1 - 1
tasks/Nian/assets.py

@@ -21,7 +21,7 @@ class NianAssets:
 	# 判断是否在年的界面 
 	I_N_CHECK = RuleImage(roi_front=(793,279,242,246), roi_back=(793,279,242,246), threshold=0.8, method="Template matching", file="./tasks/Nian/nian/nian_n_check.png")
 	# 等待进入,也是关闭按钮 
-	I_N_WAITING = RuleImage(roi_front=(735,28,54,51), roi_back=(735,28,54,51), threshold=0.7, method="Template matching", file="./tasks/Nian/nian/nian_n_waiting.png")
+	I_N_WAITING = RuleImage(roi_front=(825,34,54,51), roi_back=(735,12,202,99), threshold=0.7, method="Template matching", file="./tasks/Nian/nian/nian_n_waiting.png")
 
 
 	# Ocr Rule Assets

+ 2 - 2
tasks/Nian/nian/image.json

@@ -20,8 +20,8 @@
   {
     "itemName": "n_waiting",
     "imageName": "nian_n_waiting.png",
-    "roiFront": "735,28,54,51",
-    "roiBack": "735,28,54,51",
+    "roiFront": "825,34,54,51",
+    "roiBack": "735,12,202,99",
     "method": "Template matching",
     "threshold": 0.7,
     "description": "等待进入,也是关闭按钮"

+ 4 - 2
tasks/RealmRaid/script_task.py

@@ -12,6 +12,7 @@ from tasks.GameUi.page import page_realm_raid, page_main, page_shikigami_records
 from tasks.RealmRaid.assets import RealmRaidAssets
 from tasks.RealmRaid.config import RealmRaid, RaidMode, AttackNumber, WhenAttackFail
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy
 
 
 from module.logger import logger
@@ -557,8 +558,9 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RealmRaidAssets):
                          method="Template matching",
                          file="./tasks/RyouToppa/dev/loser_sign_1.png")
 
-    def battle_wait(self, random_click_swipt_enable: bool) -> bool:
-        return self.battle_wait_v2(random_click_swipt_enable=random_click_swipt_enable)
+    @battle_wait_strategy()
+    def battle_wait(self, *args, **kwargs):
+        return self.battle_wait_with_strategy(*args, **kwargs)
 
 
 if __name__ == "__main__":

+ 1 - 1
tasks/Restart/assets.py

@@ -139,7 +139,7 @@ class RestartAssets:
 	O_LOGIN_NETWORK = RuleOcr(roi=(534,649,189,39), area=(210,492,100,100), mode="Single", method="Default", keyword="正在连接服务器", name="login_network")
 	# Ocr-description 
 	O_LOGIN_ENTER_GAME = RuleOcr(roi=(589,544,101,107), area=(558,574,154,49), mode="Single", method="Default", keyword="进入", name="login_enter_game")
-	# Ocr-description 
+	# 兼容原先的进入游戏 
 	O_LOGIN_ENTER_GAME_ORIGIN = RuleOcr(roi=(550,567,176,56), area=(558,574,154,49), mode="Single", method="Default", keyword="进入游戏", name="login_enter_game_origin")
 	# 点击屏幕跳过 
 	O_LOGIN_SKIP_1 = RuleOcr(roi=(1046,35,130,37), area=(1046,35,130,37), mode="Single", method="Default", keyword="点击屏幕跳过", name="login_skip_1")

+ 4 - 2
tasks/Restart/login.py

@@ -39,10 +39,11 @@ class LoginHandler(BaseTask, RestartAssets, GameUiAssets, GeneralBuffAssets):
                 self.device.get_orientation()
                 orientation_timer.reset()
 
-            self.screenshot()
+            self.device.screenshot()
             # https://github.com/runhey/OnmyojiAutoScript/pull/1761
             if not self.device.check_screen_size_sample():
                 continue
+            self._burst()
 
             # 取消继续战斗
             if self.appear_then_click(self.I_CANCEL_BATTLE, interval=0.8):
@@ -174,10 +175,11 @@ class LoginHandler(BaseTask, RestartAssets, GameUiAssets, GeneralBuffAssets):
         skip_default = False
         courtyard_affairs_done = False  # 庭院事务只执行一次
         while 1:
-            self.screenshot()
+            self.device.screenshot()
             # https://github.com/runhey/OnmyojiAutoScript/pull/1761
             if not self.device.check_screen_size_sample():
                 continue
+            self._burst()
 
             # 点击'获得奖励'
             if self.ui_reward_appear_click():

+ 13 - 0
tasks/RichMan/guild.py

@@ -67,8 +67,10 @@ class Guild(Buy, GameUi, RichManAssets):
             *([(self.I_GUILD_SKIN, self._guild_skin_ticket)] if con.skin_ticket else []),
         ]
         items_all_done = False
+        swipe_no_progress = 0
         while 1:
             self.screenshot()
+            bought_this_round = False
             for item in items:
                 button, func = item
                 if not self.appear(button):
@@ -80,12 +82,23 @@ class Guild(Buy, GameUi, RichManAssets):
                     if item == items[-1]:
                         items_all_done = True
                     items.remove(item)
+                    bought_this_round = True
+                    swipe_no_progress = 0
                 except ButtonException as e:
                     logger.warning(f'Button {button.name} click failed')
                 break
             if items_all_done:
                 logger.info(f'All items have been purchased {items}')
                 break
+            # 刚购买成功: 先等待界面稳定并重新识别, 视野内还有商品就继续买, 不要急着滑动
+            if bought_this_round:
+                time.sleep(1)
+                continue
+            # 连续多次滑动都没有买到东西, 防止无限滑动触发点击保护
+            swipe_no_progress += 1
+            if swipe_no_progress >= 8:
+                logger.warning(f'Swipe {swipe_no_progress} times without buying, stop guild store')
+                break
             if self.swipe(self.S_GUILD_STORE, interval=1.5):
                 time.sleep(2)
                 continue

+ 5 - 0
tasks/RyouToppa/script_task.py

@@ -12,6 +12,7 @@ from tasks.Component.config_base import ConfigBase, Time
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.page import page_realm_raid, page_main, page_kekkai_toppa, page_shikigami_records
 from tasks.RealmRaid.assets import RealmRaidAssets
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy
 
 from module.logger import logger
 from module.exception import TaskEnd
@@ -327,6 +328,10 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RyouToppaAssets):
                 click_failure_count += 1
                 continue
 
+    @battle_wait_strategy()
+    def battle_wait(self, *args, **kwargs):
+        return self.battle_wait_with_strategy(*args, **kwargs)
+
 
 if __name__ == "__main__":
     from module.config.config import Config

+ 1 - 1
tasks/SoulsTidy/script_task.py

@@ -142,7 +142,7 @@ class ScriptTask(GameUi, SoulsTidyAssets):
                     if firvel is None or firvel == '':
                         logger.info('ocr result is Null')
                         continue
-                    if firvel != '古':
+                    if (firvel != '古') and (firvel != '+0'):
                         # 问就是 把 +0 识别成了 古
                         logger.info('No zero level, bongna done')
                         break

+ 8 - 5
tasks/base_task.py

@@ -513,11 +513,12 @@ class BaseTask(GlobalGameAssets, CostumeBase):
             return True
         return False
 
-    def ocr_appear(self, target: RuleOcr, interval: float = None) -> bool:
+    def ocr_appear(self, target: RuleOcr, interval: float = None, exact: bool = False) -> bool:
         """
         ocr识别目标
         :param interval:
         :param target:
+        :param exact: 是否只匹配完整的单个 OCR 文本, 加上这个参数是为了 https://github.com/runhey/OnmyojiAutoScript/issues/1782
         :return: 如果target有keyword或者是keyword存在,返回是True,否则返回False
                  但是没有指定keyword,返回的是匹配到的值,具体取决于target的mode
         """
@@ -536,7 +537,7 @@ class BaseTask(GlobalGameAssets, CostumeBase):
             if not self.interval_timer[target.name].reached():
                 return None
 
-        result = target.ocr(self.device.image)
+        result = target.ocr(self.device.image, exact=exact)
         appear = False
 
         if not target.keyword or target.keyword == '':
@@ -562,16 +563,18 @@ class BaseTask(GlobalGameAssets, CostumeBase):
                          target: RuleOcr,
                          action: Union[RuleClick, RuleLongClick] = None,
                          interval: float = None,
-                         duration: float = None) -> bool:
+                         duration: float = None,
+                         exact: bool = False) -> bool:
         """
         ocr识别目标,如果目标存在,则触发动作
         :param target:
         :param action:
         :param interval:
         :param duration:
+        :param exact: 是否只匹配完整的单个 OCR 文本 , 加上这个参数是为了 https://github.com/runhey/OnmyojiAutoScript/issues/1782
         :return:
         """
-        appear = self.ocr_appear(target, interval)
+        appear = self.ocr_appear(target, interval, exact=exact)
 
         if not appear:
             return False
@@ -826,4 +829,4 @@ class BaseTask(GlobalGameAssets, CostumeBase):
         logger.info(f'Push notify: {content}')
 
     def save_image(self, task_name=None, content=None, wait_time=2, image_type=False, push_flag=False, level=3):
-        logger.info(f'Save image: {task_name}')
+        logger.info(f'Save image: {task_name}')

+ 120 - 0
tests/module/atom/test_click.py

@@ -0,0 +1,120 @@
+import pytest
+
+from module.atom.click import RuleClick, RuleClickExclude
+
+
+def test_coord_in_excluded_selects_a_matching_click_and_uses_its_roi_front():
+    first = RuleClick((10, 20, 5, 6), (100, 100, 20, 20), name='first')
+    second = RuleClick((30, 40, 7, 8), (200, 200, 20, 20), name='second')
+    click = RuleClickExclude([first, second], strategy='complement', distribution='uniform')
+
+    for _ in range(100):
+        x, y = click.coord_in_excluded(['second'])
+        assert 30 <= x < 37
+        assert 40 <= y < 48
+
+
+def test_coord_in_excluded_matches_asset_attribute_name():
+    click = RuleClick((30, 40, 7, 8), (200, 200, 20, 20), name='end_1_1')
+    exclude = RuleClickExclude([click], strategy='complement', distribution='uniform')
+
+    x, y = exclude.coord_in_excluded(['C_END_1_1'])
+    assert 30 <= x < 37
+    assert 40 <= y < 48
+
+
+def test_coord_in_excluded_randomly_selects_from_multiple_matches(monkeypatch):
+    first = RuleClick((10, 20, 5, 6), (100, 100, 20, 20), name='area')
+    second = RuleClick((30, 40, 7, 8), (200, 200, 20, 20), name='area')
+    click = RuleClickExclude([first, second], strategy='complement', distribution='uniform')
+    monkeypatch.setattr('module.atom.click.random.choice', lambda values: values[1])
+
+    x, y = click.coord_in_excluded(['area'])
+    assert 30 <= x < 37
+    assert 40 <= y < 48
+
+
+def test_coord_in_excluded_rejects_unknown_area():
+    click = RuleClickExclude([], strategy='complement', distribution='uniform')
+
+    with pytest.raises(ValueError, match='No excluded click matches'):
+        click.coord_in_excluded(['unknown'])
+
+
+def test_exclude_click_string_contains_excluded_click_names():
+    first = RuleClick((0, 0, 1, 1), (100, 100, 20, 20), name='first')
+    second = RuleClick((0, 0, 1, 1), (200, 200, 20, 20), name='second')
+    click = RuleClickExclude([first, second], strategy='complement', distribution='uniform')
+
+    assert 'first' in str(click)
+    assert 'second' in str(click)
+    assert repr(click) == str(click)
+
+
+@pytest.mark.parametrize('strategy', ['rejection', 'complement'])
+@pytest.mark.parametrize('distribution', ['uniform', 'normal'])
+def test_exclude_click_strategies_and_distributions(strategy, distribution):
+    excluded = RuleClick((0, 0, 1, 1), (100, 100, 200, 150))
+    click = RuleClickExclude(excluded, strategy=strategy, distribution=distribution)
+
+    assert isinstance(click, RuleClick)
+    for _ in range(200):
+        x, y = click.coord()
+        assert 0 <= x < 1280
+        assert 0 <= y < 720
+        assert not (100 <= x < 300 and 100 <= y < 250)
+
+
+def test_exclude_click_uses_union_of_overlapping_roi_back_regions():
+    clicks = [
+        RuleClick((0, 0, 1, 1), (100, 100, 200, 150)),
+        RuleClick((0, 0, 1, 1), (250, 150, 200, 150)),
+    ]
+    click = RuleClickExclude(clicks, strategy='complement', distribution='uniform')
+
+    for _ in range(200):
+        x, y = click.coord()
+        assert not (
+            (100 <= x < 300 and 100 <= y < 250)
+            or (250 <= x < 450 and 150 <= y < 300)
+        )
+
+
+def test_exclude_click_clips_roi_back_to_screen():
+    excluded = RuleClick((0, 0, 1, 1), (-100, -100, 200, 200))
+    click = RuleClickExclude(excluded, strategy='complement', distribution='uniform')
+
+    for _ in range(100):
+        x, y = click.coord()
+        assert x >= 100 or y >= 100
+
+
+def test_rejection_sampling_falls_back_to_complement(monkeypatch):
+    excluded = RuleClick((0, 0, 1, 1), (0, 0, 1279, 720))
+    click = RuleClickExclude(excluded, strategy='rejection', distribution='uniform', max_attempts=1)
+    sample_point = click._sample_point
+    monkeypatch.setattr(
+        click,
+        '_sample_point',
+        lambda rect, distribution: (1, 1)
+        if rect == (0, 0, 1280, 720) else sample_point(rect, distribution),
+    )
+
+    x, y = click.coord()
+    assert x == 1279
+    assert 0 <= y < 720
+
+
+def test_strategy_and_distribution_are_selected_once_at_initialization(monkeypatch):
+    choices = iter(['rejection', 'normal'])
+    monkeypatch.setattr('module.atom.click.random.choice', lambda values: next(choices))
+    click = RuleClickExclude([])
+
+    assert click.strategy == 'rejection'
+    assert click.distribution == 'normal'
+
+
+def test_excluded_regions_covering_screen_are_rejected():
+    excluded = RuleClick((0, 0, 1, 1), (0, 0, 1280, 720))
+    with pytest.raises(ValueError, match='cover the whole screen'):
+        RuleClickExclude(excluded)

+ 233 - 0
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -0,0 +1,233 @@
+import pytest
+
+from tasks.Component.GeneralBattle.battle_wait import (
+    BattleWait,
+    BattleWaitPlan,
+    HookSignal,
+    battle_wait_strategy,
+)
+
+
+@pytest.fixture(autouse=True)
+def reset_battle_wait_plan(monkeypatch):
+    monkeypatch.setattr(battle_wait_strategy, 'battle_wait_plan', None)
+    monkeypatch.setattr(battle_wait_strategy, 'options', None)
+
+
+def test_default_plan_contains_default_hooks_and_sequence():
+    plan = BattleWaitPlan()
+
+    assert tuple(getattr(plan, hook) for hook in BattleWaitPlan.HOOKS_DEFAULT) == (
+        'default',
+        'default',
+        'default',
+        'default',
+        'default',
+        'default',
+    )
+    assert plan.sequence == 'completion>interrupt>success>failure>idle'
+    assert plan.function_setup_name == '_bw_setup_default'
+
+
+def test_decorator_passes_its_plan_to_the_wrapped_function():
+    strategy = battle_wait_strategy('reserve_default', 'idle_default', failure='custom')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    plan = battle_wait(object())
+
+    assert plan.reserve == 'default'
+    assert plan.idle == 'default'
+    assert plan.failure == 'custom'
+
+
+def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
+    strategy = battle_wait_strategy('success_default')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    default_plan = battle_wait_strategy.battle_wait_plan
+
+    with battle_wait_strategy('success_default', failure='custom'):
+        temporary_plan = battle_wait(object())
+        assert temporary_plan.failure == 'custom'
+
+    assert battle_wait_strategy.battle_wait_plan is default_plan
+    assert battle_wait(object()) is default_plan
+
+
+def test_event_and_strategy_can_be_configured_with_both_supported_forms():
+    plan = BattleWaitPlan('yyy_default', abcd='edf')
+
+    assert plan.yyy == 'default'
+    assert plan.abcd == 'edf'
+    assert plan.sequence_function_names()[4:6] == [
+        '_bw_yyy_default',
+        '_bw_abcd_edf',
+    ]
+
+
+def test_an_event_cannot_be_configured_with_two_strategies():
+    with pytest.raises(ValueError, match="configured more than once"):
+        BattleWaitPlan('success_default', success='custom')
+
+
+def test_setup_runs_before_the_wait_loop():
+    class OrderedBattleWait(BattleWait):
+        def __init__(self):
+            self.events = []
+
+        def screenshot(self):
+            self.events.append('screenshot')
+
+        def _bw_setup_record(self, bw_ctx):
+            self.events.append('setup')
+            return HookSignal.DONE
+
+        def _bw_completion_finish(self, bw_ctx):
+            self.events.append('completion')
+            return HookSignal.DONE
+
+    battle_wait = OrderedBattleWait()
+    plan = BattleWaitPlan('setup_record', 'completion_finish')
+
+    assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
+    assert battle_wait.events == ['setup', 'screenshot', 'completion']
+
+
+def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
+    class CustomBattleWait(BattleWait):
+        def __init__(self):
+            self.events = []
+
+        def screenshot(self):
+            pass
+
+        def _bw_setup_record(self, bw_ctx):
+            self.events.append('setup')
+            return HookSignal.DONE
+
+        def _bw_yyy_record(self, bw_ctx):
+            self.events.append('yyy')
+            return HookSignal.CONTINUE
+
+        def _bw_completion_finish(self, bw_ctx):
+            self.events.append('completion')
+            return HookSignal.DONE
+
+    battle_wait = CustomBattleWait()
+    plan = BattleWaitPlan(
+        'setup_record',
+        'yyy_record',
+        'completion_finish',
+        sequence='yyy > completion > interrupt > success > failure > idle',
+    )
+
+    assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
+    assert battle_wait.events == ['setup', 'yyy', 'completion']
+
+
+def test_custom_sequence_controls_hook_order():
+    plan = BattleWaitPlan(
+        'yyy_default',
+        sequence='failure > yyy > completion > interrupt > success > idle',
+    )
+
+    assert plan.sequence_function_names() == [
+        '_bw_failure_default',
+        '_bw_yyy_default',
+        '_bw_completion_default',
+        '_bw_interrupt_default',
+        '_bw_success_default',
+        '_bw_idle_default',
+    ]
+
+
+def test_custom_events_without_sequence_are_inserted_before_idle_in_argument_order():
+    plan = BattleWaitPlan('yyy_default', 'abcd_edf')
+
+    assert plan.sequence == 'completion>interrupt>success>failure>yyy>abcd>idle'
+
+
+def test_dynamic_override_does_not_modify_the_default_plan():
+    strategy = battle_wait_strategy('success_default')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    default_plan = battle_wait_strategy.battle_wait_plan
+
+    overridden_plan = battle_wait(object(), random_click_swipt_enable=True)
+
+    assert overridden_plan is not default_plan
+    assert overridden_plan.randomclick == 'default'
+    assert not hasattr(default_plan, 'randomclick')
+    assert battle_wait_strategy.battle_wait_plan is default_plan
+
+
+def test_dynamic_override_is_only_valid_for_the_current_call():
+    strategy = battle_wait_strategy('success_default')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    battle_wait(object(), random_click_swipt_enable=True)
+    plan_without_override = battle_wait(object(), random_click_swipt_enable=False)
+
+    assert not hasattr(plan_without_override, 'randomclick')
+
+
+# 验证单层装饰器保存自己的 options,with_options() 只在上下文内临时覆盖,退出后恢复。
+def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
+    received_options = []
+    decorator_options = {
+        'completion': {'source': 'decorator'},
+        'success': {'excludes': ['C_REWARD_1']},
+    }
+    context_options = {
+        'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
+    }
+
+    strategy = battle_wait_strategy(
+        'setup_record', 'completion_record', options=decorator_options
+    )
+
+    class OptionBattleWait(BattleWait):
+        def screenshot(self):
+            pass
+
+        def _bw_setup_record(self, bw_ctx):
+            return HookSignal.DONE
+
+        def _bw_completion_record(self, bw_ctx):
+            received_options.append(bw_ctx.options)
+            return HookSignal.DONE
+
+        @strategy
+        def battle_wait(self, *args, **kwargs):
+            return self.battle_wait_with_strategy(*args, **kwargs)
+
+    battle_wait = object.__new__(OptionBattleWait)
+
+    assert battle_wait.battle_wait() is True
+    assert received_options[-1] == decorator_options
+
+    with strategy.with_options(context_options):
+        assert battle_wait.battle_wait() is True
+        assert received_options[-1] == {
+            'completion': {'source': 'decorator'},
+            'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
+        }
+        strategy_text = str(strategy)
+        assert 'options=' in strategy_text
+        assert 'C_END_MESSAGE_RIGHT_TOP' in strategy_text
+
+    assert battle_wait.battle_wait() is True
+    assert received_options[-1] == decorator_options
+    assert 'C_REWARD_1' in str(strategy)

+ 21 - 0
tests/test_ocr_filter.py

@@ -0,0 +1,21 @@
+from types import SimpleNamespace
+
+from module.ocr.base_ocr import BaseCor
+
+
+def boxed_text(text: str):
+    return SimpleNamespace(ocr_text=text)
+
+
+def test_exact_filter_does_not_match_a_partial_nickname():
+    target = object.__new__(BaseCor)
+    results = [boxed_text('赈早见琥珀主'), boxed_text('龙鸣蚀心')]
+
+    assert target.filter(results, '你的心', exact=True) is None
+
+
+def test_exact_filter_matches_the_complete_nickname():
+    target = object.__new__(BaseCor)
+    results = [boxed_text('轻芋'), boxed_text('你的心')]
+
+    assert target.filter(results, '你的心', exact=True) == [1]