Quellcode durchsuchen

Merge upstream dev and fix integration regressions

Merge runhey/OnmyojiAutoScript dev at d1c1b85a. Preserve context-local battle strategies and the local login retry fix while adopting the new battle runtime.

Fix scoped battle options and hook parsing, soul mismatch prompts, animated-to-static costume switching, touch-fish popup/retry timeouts, and malformed FrogBoss prediction responses.

Migrate battle tests and add integration regressions. Validation: 82 pytest tests passed; changed Python/JSON syntax, asset references, and git diff checks passed.
unknown vor 1 Monat
Ursprung
Commit
7811325112
80 geänderte Dateien mit 3123 neuen und 490 gelöschten Zeilen
  1. 3 0
      .gitignore
  2. 5 2
      assets/i18n/zh-CN.json
  3. 46 3
      module/atom/gif.py
  4. 4 4
      tasks/ActivityShikigami/config.py
  5. 20 10
      tasks/ActivityShikigami/script_task.py
  6. 33 1
      tasks/Component/Costume/assets.py
  7. 1 0
      tasks/Component/Costume/config.py
  8. 36 4
      tasks/Component/Costume/costume_base.py
  9. 1 1
      tasks/Component/Costume/costume_test.py
  10. 137 0
      tasks/Component/Costume/main17/image.json
  11. BIN
      tasks/Component/Costume/main17/main17_check_main_17_a.png
  12. BIN
      tasks/Component/Costume/main17/main17_check_main_17_b.png
  13. BIN
      tasks/Component/Costume/main17/main17_check_main_17_c.png
  14. BIN
      tasks/Component/Costume/main17/main17_main_goto_exploration_17_a.png
  15. BIN
      tasks/Component/Costume/main17/main17_main_goto_exploration_17_b.png
  16. BIN
      tasks/Component/Costume/main17/main17_main_goto_exploration_17_c.png
  17. BIN
      tasks/Component/Costume/main17/main17_main_goto_summon_17_a.png
  18. BIN
      tasks/Component/Costume/main17/main17_main_goto_summon_17_b.png
  19. BIN
      tasks/Component/Costume/main17/main17_main_goto_summon_17_c.png
  20. BIN
      tasks/Component/Costume/main17/main17_main_goto_town_17_a.png
  21. BIN
      tasks/Component/Costume/main17/main17_main_goto_town_17_b.png
  22. BIN
      tasks/Component/Costume/main17/main17_main_goto_town_17_c.png
  23. BIN
      tasks/Component/Costume/main17/main17_pet_house_17_a.png
  24. BIN
      tasks/Component/Costume/main17/main17_pet_house_17_b.png
  25. BIN
      tasks/Component/Costume/main17/main17_pet_house_17_c.png
  26. 196 0
      tasks/Component/GeneralBattle/battle.py
  27. 883 107
      tasks/Component/GeneralBattle/battle_wait.py
  28. 3 5
      tasks/Component/GeneralBattle/general_battle.py
  29. 18 0
      tasks/Component/SwitchOnmyoji/switch_onmyoji.py
  30. 1 1
      tasks/DailyTrifles/script_task.py
  31. 1 1
      tasks/DemonEncounter/assets.py
  32. 2 2
      tasks/DemonEncounter/demon/ocr.json
  33. 12 3
      tasks/Exploration/solo.py
  34. 19 17
      tasks/FrogBoss/assets.py
  35. 1 0
      tasks/FrogBoss/config.py
  36. BIN
      tasks/FrogBoss/fb/fb_bet_left.png
  37. BIN
      tasks/FrogBoss/fb/fb_bet_right.png
  38. BIN
      tasks/FrogBoss/fb/fb_bet_success.png
  39. BIN
      tasks/FrogBoss/fb/fb_bet_success_box.png
  40. BIN
      tasks/FrogBoss/fb/fb_betted.png
  41. BIN
      tasks/FrogBoss/fb/fb_failure_left.png
  42. BIN
      tasks/FrogBoss/fb/fb_frog_boss_enter.png
  43. BIN
      tasks/FrogBoss/fb/fb_frog_check.png
  44. BIN
      tasks/FrogBoss/fb/fb_next_competition.png
  45. BIN
      tasks/FrogBoss/fb/fb_success_right.png
  46. 39 25
      tasks/FrogBoss/fb/image.json
  47. 14 2
      tasks/FrogBoss/fb/image2.json
  48. 6 6
      tasks/FrogBoss/fb/ocr.json
  49. 184 0
      tasks/FrogBoss/frog_oas.py
  50. 2 0
      tasks/FrogBoss/oas_sources.py
  51. 45 3
      tasks/FrogBoss/script_task.py
  52. 106 0
      tasks/FrogBoss/test_frog_oas.py
  53. 6 0
      tasks/GameUi/page.py
  54. BIN
      tasks/GameUi/page/page_main_goto_summon.png
  55. 5 2
      tasks/RichMan/assets.py
  56. 77 18
      tasks/RichMan/mall/medal.py
  57. 11 0
      tasks/RichMan/mall/medal/ocr.json
  58. 3 2
      tasks/RichMan/mall/navbar.py
  59. 28 0
      tasks/WeeklyTrifles/assets.py
  60. 12 4
      tasks/WeeklyTrifles/config.py
  61. 101 14
      tasks/WeeklyTrifles/script_task.py
  62. 92 0
      tasks/WeeklyTrifles/touch_fish/image.json
  63. 20 0
      tasks/WeeklyTrifles/touch_fish/ocr.json
  64. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_check_touch_fish.png
  65. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_guild_goto_tf.png
  66. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_fold_window.png
  67. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_happy_get.png
  68. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_last_save.png
  69. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_open_fold_window.png
  70. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_save_all.png
  71. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_confirm.png
  72. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_goto_main.png
  73. BIN
      tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_save_success.png
  74. 3 3
      tasks/base_task.py
  75. 91 0
      tests/tasks/ActivityShikigami/test_battle_integration.py
  76. 56 0
      tests/tasks/Component/Costume/test_costume.py
  77. 323 250
      tests/tasks/Component/GeneralBattle/test_battle_wait.py
  78. 196 0
      tests/tasks/Component/GeneralBattle/test_randomclick_gate.py
  79. 160 0
      tests/tasks/WeeklyTrifles/test_touch_fish.py
  80. 121 0
      tests/test_switch_onmyoji.py

+ 3 - 0
.gitignore

@@ -274,3 +274,6 @@ console.bat
 .vscode/*
 .vscode/*
 tasks/AutoCheckinBigGod/frida-server-17.6.2-android-x86_64
 tasks/AutoCheckinBigGod/frida-server-17.6.2-android-x86_64
 oas.bat
 oas.bat
+
+# Per-instance FrogBoss prediction and result history
+data/frog_oas/

+ 5 - 2
assets/i18n/zh-CN.json

@@ -43,6 +43,7 @@
   "exit_four_help": "支持打九退四,保证稳定57级,要求设置好战斗主题,即 脚本->全局配置->游戏装饰自定义->战斗主题",
   "exit_four_help": "支持打九退四,保证稳定57级,要求设置好战斗主题,即 脚本->全局配置->游戏装饰自定义->战斗主题",
   "costume_main_15": "茨心乐园",
   "costume_main_15": "茨心乐园",
   "costume_main_16": "狐栖归处",
   "costume_main_16": "狐栖归处",
+  "costume_main_17": "玉岚狐庭",
   "check_true_orochi_enable": "是否在结束后检测真蛇",
   "check_true_orochi_enable": "是否在结束后检测真蛇",
   "check_true_orochi_enable_help": "开启后会在任务结束后检测是否出现真蛇, 若出现则自动拉起真蛇",
   "check_true_orochi_enable_help": "开启后会在任务结束后检测是否出现真蛇, 若出现则自动拉起真蛇",
   "enable_book_auto": "自动选择",
   "enable_book_auto": "自动选择",
@@ -137,5 +138,7 @@
   "enable_ap100_anti_detect": "100体爬塔防检测",
   "enable_ap100_anti_detect": "100体爬塔防检测",
   "enable_ap100_anti_detect_help": "100体爬塔战斗过程是否随机点击或滑动",
   "enable_ap100_anti_detect_help": "100体爬塔战斗过程是否随机点击或滑动",
   "costume_battle_15": "灵狐寄愿",
   "costume_battle_15": "灵狐寄愿",
-  "costume_shikigami_12": "拾光之窗"
-}
+  "costume_shikigami_12": "拾光之窗",
+  "save_touch_fish": "惠比寿的摸鱼行动",
+  "save_touch_fish_help": "默认使用全部存储按钮,主要目的是为了配合真蛇每周打一次即可获得俩次奖励(并不会节省体力)"
+}

+ 46 - 3
module/atom/gif.py

@@ -1,6 +1,8 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
+import types
+
 import numpy as np
 import numpy as np
 
 
 from module.atom.image import RuleImage
 from module.atom.image import RuleImage
@@ -10,13 +12,51 @@ from module.atom.image import RuleImage
 class RuleGif:
 class RuleGif:
     # 大部分实现同RuleImage 的接口
     # 大部分实现同RuleImage 的接口
 
 
+    @staticmethod
+    def attach_to(image_obj: RuleImage, targets: list[RuleImage]) -> None:
+        """
+        把GIF的多帧匹配行为原地挂载到一个RuleImage实例上
+
+        与replace_img的原地换属性同思路: 不换对象、不换引用,
+        持有该对象引用的Page/寻路会立即生效
+        :param image_obj: 被挂载的RuleImage实例
+        :param targets: 多帧RuleImage, 顺序即匹配优先级
+        """
+        # GIF状态
+        image_obj.targets = targets
+        image_obj.roi_front = [0, 0, 0, 0]
+        image_obj.roi_back = targets[0].roi_back
+        image_obj.appear_target = targets[0]
+        image_obj.name = targets[0].name
+        image_obj._match_init = False
+        # 方法级替换: 把RuleGif的所有公开方法绑定到该实例上
+        for name, attr in RuleGif.__dict__.items():
+            if name.startswith('_'):
+                continue
+            if isinstance(attr, types.FunctionType):
+                setattr(image_obj, name, types.MethodType(attr, image_obj))
+
+    @staticmethod
+    def detach_from(image_obj: RuleImage) -> None:
+        """Remove attached GIF behavior while preserving the image object's identity."""
+        if 'targets' not in image_obj.__dict__:
+            return
+        for name, attr in RuleGif.__dict__.items():
+            method = image_obj.__dict__.get(name)
+            if isinstance(method, types.MethodType) and method.__func__ is attr:
+                delattr(image_obj, name)
+        for name in ('targets', 'appear_target', 'name'):
+            image_obj.__dict__.pop(name, None)
+
     @property
     @property
     def name(self) -> str:
     def name(self) -> str:
-        return self.appear_target.name
+        return self.targets[0].name
 
 
     def __init__(self, targets: list[RuleImage]):
     def __init__(self, targets: list[RuleImage]):
         self.targets = targets
         self.targets = targets
         self.roi_front: list = [0, 0, 0, 0]
         self.roi_front: list = [0, 0, 0, 0]
+        self.roi_back: list = targets[0].roi_back
+        self._match_init = False
         self.appear_target = targets[0]
         self.appear_target = targets[0]
 
 
     def pre_process(self, image):
     def pre_process(self, image):
@@ -44,18 +84,21 @@ class RuleGif:
                 return True, target
                 return True, target
         return False, None
         return False, None
 
 
-    def search_with_multi_scale(self, image, roi=None, threshold=None, scale_range=(0.8, 1.1, 0.05)):
+    def search_with_multi_scale(self, image, roi=None, threshold=None, scales=None, scale_range=(0.8, 1.1, 0.05)):
         image = self.pre_process(image)
         image = self.pre_process(image)
         threshold = self.targets[0].threshold if threshold is None else threshold
         threshold = self.targets[0].threshold if threshold is None else threshold
         roi = self.targets[0].roi_back if roi is None else roi
         roi = self.targets[0].roi_back if roi is None else roi
         for target in self.targets:
         for target in self.targets:
             target.roi_back = roi
             target.roi_back = roi
-            if target.match_multi_scale(image, threshold=threshold, scale_range=scale_range):
+            if target.match_multi_scale(image, threshold=threshold, scales=scales, scale_range=scale_range):
                 self.roi_front = target.roi_front
                 self.roi_front = target.roi_front
                 self.appear_target = target
                 self.appear_target = target
                 return True, target
                 return True, target
         return False, None
         return False, None
 
 
+    def match_multi_scale(self, image, threshold: float = None, scales: list = None, scale_range: tuple = None) -> bool:
+        return self.search_with_multi_scale(image, threshold=threshold, scales=scales, scale_range=scale_range)[0]
+
     def match(self, image, threshold: float = None) -> bool:
     def match(self, image, threshold: float = None) -> bool:
         return self.search(image, threshold=threshold)[0]
         return self.search(image, threshold=threshold)[0]
 
 

+ 4 - 4
tasks/ActivityShikigami/config.py

@@ -78,22 +78,22 @@ class GeneralBattleConfig(BaseModel):
     enable_pass_preset: bool = Field(default=False, description='enable_pass_preset_help')
     enable_pass_preset: bool = Field(default=False, description='enable_pass_preset_help')
     enable_pass_green: bool = Field(default=False, description='enable_pass_green_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')
     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_pass_anti_detect: bool = Field(default=True, description='enable_pass_anti_detect_help')
 
 
     enable_ap_preset: bool = Field(default=False, description='enable_ap_preset_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')
     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')
     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_ap_anti_detect: bool = Field(default=True, description='enable_ap_anti_detect_help')
 
 
     enable_boss_preset: bool = Field(default=False, description='enable_boss_preset_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')
     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')
     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_boss_anti_detect: bool = Field(default=True, description='enable_boss_anti_detect_help')
 
 
     enable_ap100_preset: bool = Field(default=False, description='enable_ap100_preset_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')
     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')
     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')
+    enable_ap100_anti_detect: bool = Field(default=True, description='enable_ap100_anti_detect_help')
 
 
 
 
 class ActivityShikigami(ConfigBase):
 class ActivityShikigami(ConfigBase):

+ 20 - 10
tasks/ActivityShikigami/script_task.py

@@ -19,8 +19,8 @@ from module.exception import TaskEnd
 from module.logger import logger
 from module.logger import logger
 
 
 from tasks.base_task import BaseTask
 from tasks.base_task import BaseTask
-from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy
-from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy, battle_wait_options
+from tasks.Component.GeneralBattle.battle import Battle
 from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
 from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
 from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig, ActivityShikigami
 from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig, ActivityShikigami
 from tasks.Component.BaseActivity.base_activity import BaseActivity
 from tasks.Component.BaseActivity.base_activity import BaseActivity
@@ -137,13 +137,13 @@ class StateMachine(BaseTask):
         if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
         if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
             logger.info('All climbing activities have been completed')
             logger.info('All climbing activities have been completed')
             return False
             return False
-        # 切换爬塔类型了, 恢复所有状态
-        self.current_count = 0
+        # 切换爬塔类型, count_map 按类型独立统计无需重置;但战斗框架状态需要清掉上一类型的残留
+        self.battle_state_reset()
         logger.hr(f'Climb switch to {self.climb_type}', 2)
         logger.hr(f'Climb switch to {self.climb_type}', 2)
         return True
         return True
 
 
 
 
-class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
+class ScriptTask(StateMachine, GameUi, Battle, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
     """
     """
     更新前请先看 ./README.md
     更新前请先看 ./README.md
     """
     """
@@ -295,11 +295,21 @@ class ScriptTask(StateMachine, GameUi, BaseActivity, SwitchSoul, ActivityShikiga
                 logger.info(f'Try click fire, remain times[{max_times - click_times}]')
                 logger.info(f'Try click fire, remain times[{max_times - click_times}]')
                 continue
                 continue
         # 运行战斗
         # 运行战斗
-        self.run_general_battle(config=self.get_general_battle_conf())
-
-    @battle_wait_strategy(success='activity')
-    def battle_wait(self, *args, **kwargs):
-        return self.battle_wait_with_strategy(*args, **kwargs)
+        strategies, options = self.loadout_from_config(self.get_general_battle_conf())
+        strategies['success'] = 'activity'
+        self.loadout_show((strategies, options))
+        self.state_show()
+        with battle_wait_strategy(**strategies), battle_wait_options(**options):
+            win = self.battle_wait()
+        # 对齐历史语义: 战斗成功结束后记为一次
+        if win:
+            self.count_map[self.climb_type] += 1
+            logger.info(f'Count {self.climb_type}: {self.count_map[self.climb_type]}')
+        return win
+
+    # @battle_wait_strategy(success='activity')
+    # def battle_wait(self, *args, **kwargs):
+    #     return self.battle_wait_with_strategy(*args, **kwargs)
 
 
     def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
     def switch_soul(self, enter_button: RuleImage, cur_img: RuleImage):
         conf = self.conf.switch_soul_config
         conf = self.conf.switch_soul_config

+ 33 - 1
tasks/Component/Costume/assets.py

@@ -114,6 +114,39 @@ class CostumeAssets:
 	I_PET_HOUSE_16 = RuleImage(roi_front=(1256,402,20,58), roi_back=(1210,340,70,140), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main16/main16_pet_house_16.png")
 	I_PET_HOUSE_16 = RuleImage(roi_front=(1256,402,20,58), roi_back=(1210,340,70,140), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main16/main16_pet_house_16.png")
 
 
 
 
+	# Image Rule Assets
+	# 庭院判定 a
+	I_CHECK_MAIN_17_A = RuleImage(roi_front=(260,168,80,54), roi_back=(180,100,240,180), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_check_main_17_a.png")
+	# 庭院判定 b
+	I_CHECK_MAIN_17_B = RuleImage(roi_front=(260,168,80,54), roi_back=(180,100,240,180), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_check_main_17_b.png")
+	# 庭院判定 c
+	I_CHECK_MAIN_17_C = RuleImage(roi_front=(260,168,80,54), roi_back=(180,100,240,180), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_check_main_17_c.png")
+	# 探索 a
+	I_MAIN_GOTO_EXPLORATION_17_A = RuleImage(roi_front=(714,224,43,40), roi_back=(680,180,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_exploration_17_a.png")
+	# 探索 b
+	I_MAIN_GOTO_EXPLORATION_17_B = RuleImage(roi_front=(719,216,41,42), roi_back=(667,180,143,106), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_exploration_17_b.png")
+	# 探索 c
+	I_MAIN_GOTO_EXPLORATION_17_C = RuleImage(roi_front=(717,222,43,42), roi_back=(680,180,125,110), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_exploration_17_c.png")
+	# 召唤屋 a
+	I_MAIN_GOTO_SUMMON_17_A = RuleImage(roi_front=(981,218,40,41), roi_back=(930,170,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_summon_17_a.png")
+	# 召唤屋 b
+	I_MAIN_GOTO_SUMMON_17_B = RuleImage(roi_front=(981,218,39,38), roi_back=(930,170,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_summon_17_b.png")
+	# 召唤屋 c
+	I_MAIN_GOTO_SUMMON_17_C = RuleImage(roi_front=(981,218,39,37), roi_back=(930,170,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_summon_17_c.png")
+	# 町中 a
+	I_MAIN_GOTO_TOWN_17_A = RuleImage(roi_front=(1004,336,35,49), roi_back=(960,300,100,120), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_town_17_a.png")
+	# 町中 b
+	I_MAIN_GOTO_TOWN_17_B = RuleImage(roi_front=(1007,346,26,31), roi_back=(960,300,100,120), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_town_17_b.png")
+	# 町中 c
+	I_MAIN_GOTO_TOWN_17_C = RuleImage(roi_front=(1008,343,29,43), roi_back=(960,300,100,120), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_main_goto_town_17_c.png")
+	# 宠物屋 a
+	I_PET_HOUSE_17_A = RuleImage(roi_front=(1249,404,23,56), roi_back=(1231,340,49,154), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_pet_house_17_a.png")
+	# 宠物屋 b
+	I_PET_HOUSE_17_B = RuleImage(roi_front=(1251,417,19,45), roi_back=(1231,366,49,124), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_pet_house_17_b.png")
+	# 宠物屋 c
+	I_PET_HOUSE_17_C = RuleImage(roi_front=(1248,406,19,59), roi_back=(1228,340,52,176), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main17/main17_pet_house_17_c.png")
+
+
 	# Image Rule Assets
 	# Image Rule Assets
 	# description 
 	# description 
 	I_CHECK_MAIN_2 = RuleImage(roi_front=(1090,146,48,55), roi_back=(880,108,271,100), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main2/main2_check_main_2.png")
 	I_CHECK_MAIN_2 = RuleImage(roi_front=(1090,146,48,55), roi_back=(880,108,271,100), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main2/main2_check_main_2.png")
@@ -216,4 +249,3 @@ class CostumeAssets:
 	I_MAIN_GOTO_TOWN_9 = RuleImage(roi_front=(684,342,41,42), roi_back=(276,321,999,78), threshold=0.7, method="Template matching", file="./tasks/Component/Costume/main9/main9_main_goto_town_9.png")
 	I_MAIN_GOTO_TOWN_9 = RuleImage(roi_front=(684,342,41,42), roi_back=(276,321,999,78), threshold=0.7, method="Template matching", file="./tasks/Component/Costume/main9/main9_main_goto_town_9.png")
 	# description 
 	# description 
 	I_PET_HOUSE_9 = RuleImage(roi_front=(888,327,40,35), roi_back=(730,316,440,57), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main9/main9_pet_house_9.png")
 	I_PET_HOUSE_9 = RuleImage(roi_front=(888,327,40,35), roi_back=(730,316,440,57), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main9/main9_pet_house_9.png")
-

+ 1 - 0
tasks/Component/Costume/config.py

@@ -23,6 +23,7 @@ class MainType(str, Enum):
     COSTUME_MAIN_14 = 'costume_main_14'  # 雪月华庭
     COSTUME_MAIN_14 = 'costume_main_14'  # 雪月华庭
     COSTUME_MAIN_15 = 'costume_main_15'  # 茨心乐园
     COSTUME_MAIN_15 = 'costume_main_15'  # 茨心乐园
     COSTUME_MAIN_16 = 'costume_main_16'  # 狐栖归处
     COSTUME_MAIN_16 = 'costume_main_16'  # 狐栖归处
+    COSTUME_MAIN_17 = 'costume_main_17'  # 玉岚狐庭
 
 
 # 结界皮肤
 # 结界皮肤
 class RealmType(str, Enum):
 class RealmType(str, Enum):

+ 36 - 4
tasks/Component/Costume/costume_base.py

@@ -3,6 +3,7 @@
 # github https://github.com/runhey
 # github https://github.com/runhey
 
 
 from module.atom.image import RuleImage
 from module.atom.image import RuleImage
+from module.atom.gif import RuleGif
 from module.logger import logger
 from module.logger import logger
 
 
 from tasks.Component.Costume.config import (MainType, CostumeConfig, RealmType,
 from tasks.Component.Costume.config import (MainType, CostumeConfig, RealmType,
@@ -23,6 +24,22 @@ main_costume_model = {
         'I_PET_HOUSE': f'I_PET_HOUSE_{i}'
         'I_PET_HOUSE': f'I_PET_HOUSE_{i}'
     } for i in range(1, 17)
     } for i in range(1, 17)
 }
 }
+# 玉岚狐庭(issue #1824)
+main_costume_model[getattr(MainType, "COSTUME_MAIN_17")] = {
+    'I_CHECK_MAIN': ['I_CHECK_MAIN_17_A', 'I_CHECK_MAIN_17_B', 'I_CHECK_MAIN_17_C'],
+    'I_MAIN_GOTO_EXPLORATION': ['I_MAIN_GOTO_EXPLORATION_17_A', 'I_MAIN_GOTO_EXPLORATION_17_B', 'I_MAIN_GOTO_EXPLORATION_17_C'],
+    'I_MAIN_GOTO_SUMMON': ['I_MAIN_GOTO_SUMMON_17_A', 'I_MAIN_GOTO_SUMMON_17_B', 'I_MAIN_GOTO_SUMMON_17_C'],
+    'I_MAIN_GOTO_TOWN': ['I_MAIN_GOTO_TOWN_17_A', 'I_MAIN_GOTO_TOWN_17_B', 'I_MAIN_GOTO_TOWN_17_C'],
+    'I_PET_HOUSE': ['I_PET_HOUSE_17_A', 'I_PET_HOUSE_17_B', 'I_PET_HOUSE_17_C'],
+}
+main_costume_model[getattr(MainType, "COSTUME_MAIN_13")] = {
+    'I_CHECK_MAIN': ['I_CHECK_MAIN_13',],
+    'I_MAIN_GOTO_EXPLORATION': ['I_MAIN_GOTO_EXPLORATION_13', ],
+    'I_MAIN_GOTO_SUMMON': ['I_MAIN_GOTO_SUMMON_13',],
+    'I_MAIN_GOTO_TOWN': ['I_MAIN_GOTO_TOWN_13',],
+    'I_PET_HOUSE': ['I_PET_HOUSE_13',],
+}
+
 
 
 
 
 # 鲤鱼旗皮肤
 # 鲤鱼旗皮肤
@@ -89,11 +106,20 @@ class CostumeBase:
             return
             return
         # setattr(self, asset_before, asset_after)
         # setattr(self, asset_before, asset_after)
         asset_before_object: RuleImage = getattr(self, asset_before)
         asset_before_object: RuleImage = getattr(self, asset_before)
-        asset_before_object.roi_front = asset_after.roi_front
+        RuleGif.detach_from(asset_before_object)
+        asset_before_object.roi_front = list(asset_after.roi_front)
         if rp_roi_back:
         if rp_roi_back:
             asset_before_object.roi_back = asset_after.roi_back
             asset_before_object.roi_back = asset_after.roi_back
         asset_before_object.threshold = asset_after.threshold
         asset_before_object.threshold = asset_after.threshold
+        asset_before_object.method = asset_after.method
         asset_before_object.file = asset_after.file
         asset_before_object.file = asset_after.file
+        # Assets are shared across tasks; discard caches from the previous costume.
+        asset_before_object._image = None
+        asset_before_object._kp = None
+        asset_before_object._des = None
+        asset_before_object._match_init = False
+        for name in ('name', 'kp', 'des', 'is_template_match', 'is_sift_flann'):
+            asset_before_object.__dict__.pop(name, None)
 
 
     def check_costume_main(self, main_type: MainType):
     def check_costume_main(self, main_type: MainType):
         if main_type == MainType.COSTUME_MAIN:
         if main_type == MainType.COSTUME_MAIN:
@@ -101,8 +127,14 @@ class CostumeBase:
         logger.info(f'Switch main costume to {main_type}')
         logger.info(f'Switch main costume to {main_type}')
         costume_assets = CostumeAssets()
         costume_assets = CostumeAssets()
         for key, value in main_costume_model[main_type].items():
         for key, value in main_costume_model[main_type].items():
-            assert_value: RuleImage = getattr(costume_assets, value)
-            self.replace_img(key, assert_value)
+            if isinstance(value, list):
+                if not hasattr(self, key):
+                    continue
+                rules: list[RuleImage] = [getattr(costume_assets, item) for item in value]
+                RuleGif.attach_to(getattr(self, key), rules)
+            else:
+                assert_value: RuleImage = getattr(costume_assets, value)
+                self.replace_img(key, assert_value)
 
 
     def check_costume_carpbanner(self, carpbanner_type: CarpBannerType):
     def check_costume_carpbanner(self, carpbanner_type: CarpBannerType):
         if carpbanner_type == CarpBannerType.COSTUME_CARPBANNER_DEFAULT:
         if carpbanner_type == CarpBannerType.COSTUME_CARPBANNER_DEFAULT:
@@ -151,4 +183,4 @@ class CostumeBase:
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     c = CostumeBase()
     c = CostumeBase()
-    c.check_costume_main(MainType.COSTUME_MAIN_2)
+    c.check_costume_main(MainType.COSTUME_MAIN_13)

+ 1 - 1
tasks/Component/Costume/costume_test.py

@@ -20,7 +20,7 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, PetsAssets, ):
         self.ui_click(self.I_TOWN_GOTO_MAIN, self.I_CHECK_MAIN)
         self.ui_click(self.I_TOWN_GOTO_MAIN, self.I_CHECK_MAIN)
         # 探索测试
         # 探索测试
         self.ui_click(self.I_MAIN_GOTO_EXPLORATION, self.I_CHECK_EXPLORATION)
         self.ui_click(self.I_MAIN_GOTO_EXPLORATION, self.I_CHECK_EXPLORATION)
-        self.ui_click(self.I_UI_BACK_BLUE, self.I_CHECK_MAIN)
+        self.ui_click(self.I_UI_BACK_YELLOW, self.I_CHECK_MAIN)
         # 召唤测试
         # 召唤测试
         self.ui_click(self.I_MAIN_GOTO_SUMMON, self.I_CHECK_SUMMON)
         self.ui_click(self.I_MAIN_GOTO_SUMMON, self.I_CHECK_SUMMON)
         self.ui_click(self.I_SUMMON_GOTO_MAIN, self.I_CHECK_MAIN)
         self.ui_click(self.I_SUMMON_GOTO_MAIN, self.I_CHECK_MAIN)

+ 137 - 0
tasks/Component/Costume/main17/image.json

@@ -0,0 +1,137 @@
+[
+  {
+    "itemName": "check_main_17_a",
+    "imageName": "main17_check_main_17_a.png",
+    "roiFront": "260,168,80,54",
+    "roiBack": "180,100,240,180",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "庭院判定 a"
+  },
+  {
+    "itemName": "check_main_17_b",
+    "imageName": "main17_check_main_17_b.png",
+    "roiFront": "260,168,80,54",
+    "roiBack": "180,100,240,180",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "庭院判定 b"
+  },
+  {
+    "itemName": "check_main_17_c",
+    "imageName": "main17_check_main_17_c.png",
+    "roiFront": "260,168,80,54",
+    "roiBack": "180,100,240,180",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "庭院判定 c"
+  },
+  {
+    "itemName": "main_goto_exploration_17_a",
+    "imageName": "main17_main_goto_exploration_17_a.png",
+    "roiFront": "714,224,43,40",
+    "roiBack": "680,180,130,150",
+    "method": "Template matching",
+    "threshold": 0.55,
+    "description": "探索 a"
+  },
+  {
+    "itemName": "main_goto_exploration_17_b",
+    "imageName": "main17_main_goto_exploration_17_b.png",
+    "roiFront": "719,216,41,42",
+    "roiBack": "667,180,143,106",
+    "method": "Template matching",
+    "threshold": 0.55,
+    "description": "探索 b"
+  },
+  {
+    "itemName": "main_goto_exploration_17_c",
+    "imageName": "main17_main_goto_exploration_17_c.png",
+    "roiFront": "717,222,43,42",
+    "roiBack": "680,180,125,110",
+    "method": "Template matching",
+    "threshold": 0.55,
+    "description": "探索 c"
+  },
+  {
+    "itemName": "main_goto_summon_17_a",
+    "imageName": "main17_main_goto_summon_17_a.png",
+    "roiFront": "981,218,40,41",
+    "roiBack": "930,170,130,150",
+    "method": "Template matching",
+    "threshold": 0.55,
+    "description": "召唤屋 a"
+  },
+  {
+    "itemName": "main_goto_summon_17_b",
+    "imageName": "main17_main_goto_summon_17_b.png",
+    "roiFront": "981,218,39,38",
+    "roiBack": "930,170,130,150",
+    "method": "Template matching",
+    "threshold": 0.55,
+    "description": "召唤屋 b"
+  },
+  {
+    "itemName": "main_goto_summon_17_c",
+    "imageName": "main17_main_goto_summon_17_c.png",
+    "roiFront": "981,218,39,37",
+    "roiBack": "930,170,130,150",
+    "method": "Template matching",
+    "threshold": 0.55,
+    "description": "召唤屋 c"
+  },
+  {
+    "itemName": "main_goto_town_17_a",
+    "imageName": "main17_main_goto_town_17_a.png",
+    "roiFront": "1004,336,35,49",
+    "roiBack": "960,300,100,120",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "町中 a"
+  },
+  {
+    "itemName": "main_goto_town_17_b",
+    "imageName": "main17_main_goto_town_17_b.png",
+    "roiFront": "1007,346,26,31",
+    "roiBack": "960,300,100,120",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "町中 b"
+  },
+  {
+    "itemName": "main_goto_town_17_c",
+    "imageName": "main17_main_goto_town_17_c.png",
+    "roiFront": "1008,343,29,43",
+    "roiBack": "960,300,100,120",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "町中 c"
+  },
+  {
+    "itemName": "pet_house_17_a",
+    "imageName": "main17_pet_house_17_a.png",
+    "roiFront": "1249,404,23,56",
+    "roiBack": "1231,340,49,154",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "宠物屋 a"
+  },
+  {
+    "itemName": "pet_house_17_b",
+    "imageName": "main17_pet_house_17_b.png",
+    "roiFront": "1251,417,19,45",
+    "roiBack": "1231,366,49,124",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "宠物屋 b"
+  },
+  {
+    "itemName": "pet_house_17_c",
+    "imageName": "main17_pet_house_17_c.png",
+    "roiFront": "1248,406,19,59",
+    "roiBack": "1228,340,52,176",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "宠物屋 c"
+  }
+]

BIN
tasks/Component/Costume/main17/main17_check_main_17_a.png


BIN
tasks/Component/Costume/main17/main17_check_main_17_b.png


BIN
tasks/Component/Costume/main17/main17_check_main_17_c.png


BIN
tasks/Component/Costume/main17/main17_main_goto_exploration_17_a.png


BIN
tasks/Component/Costume/main17/main17_main_goto_exploration_17_b.png


BIN
tasks/Component/Costume/main17/main17_main_goto_exploration_17_c.png


BIN
tasks/Component/Costume/main17/main17_main_goto_summon_17_a.png


BIN
tasks/Component/Costume/main17/main17_main_goto_summon_17_b.png


BIN
tasks/Component/Costume/main17/main17_main_goto_summon_17_c.png


BIN
tasks/Component/Costume/main17/main17_main_goto_town_17_a.png


BIN
tasks/Component/Costume/main17/main17_main_goto_town_17_b.png


BIN
tasks/Component/Costume/main17/main17_main_goto_town_17_c.png


BIN
tasks/Component/Costume/main17/main17_pet_house_17_a.png


BIN
tasks/Component/Costume/main17/main17_pet_house_17_b.png


BIN
tasks/Component/Costume/main17/main17_pet_house_17_c.png


+ 196 - 0
tasks/Component/GeneralBattle/battle.py

@@ -0,0 +1,196 @@
+import random
+
+from module.logger import logger
+from module.atom.image import RuleImage
+from module.atom.ocr import RuleOcr
+
+from tasks.Component.GeneralBattle.battle_wait import (
+    BattleWait, battle_wait_strategy, battle_wait_options,
+    OptionPrepareDefault, OptionPresetDefault, OptionGreenDefault, OptionRandomclickDefault,
+    runtime,
+)
+from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig, GreenMarkType
+
+
+class Battle(BattleWait):
+
+    def start_fire(self, buttons: list[RuleOcr | RuleImage], checks: list[RuleImage]) -> bool:
+        """
+        感觉这种适配要很难
+        Args:
+            buttons: 出现就点击
+            checks: 必须在当前界面
+
+        Returns:
+            在战斗中就返回
+        """
+        click_times, max_times = 0, random.randint(4, 8)
+        while 1:
+            self.screenshot()
+            if self.is_in_battle(False):
+                break
+            if click_times >= max_times:
+                logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
+                return False
+            if (self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
+                    self.appear_then_click(self.I_UI_CONFIRM, interval=1)):
+                continue
+            if any([self.appear(check, interval=1) for check in checks]):
+                for button in buttons:
+                    if isinstance(button, RuleOcr) and self.ocr_appear_click(button, interval=2):
+                        click_times += 1
+                        logger.info(f'Try click fire, remain times[{max_times - click_times}]')
+                        continue
+                    if isinstance(button, RuleImage) and self.appear_then_click(button, interval=2):
+                        click_times += 1
+                        logger.info(f'Try click fire, remain times[{max_times - click_times}]')
+                        continue
+        return True
+
+    @battle_wait_strategy()
+    def battle_wait(self, *args, **kwargs):
+        return self.battle_wait_with_strategy(*args, **kwargs)
+
+
+    def battle_run(self):
+        with battle_wait_strategy(), battle_wait_options():
+            return self.battle_wait()
+
+    @classmethod
+    def battle_count_reached(cls, limit: int) -> bool:
+        """
+        判断当前任务累计战斗次数是否已达到上限。
+        对比的是新流程的任务级计数 per_task.count(每完成一场结算 +1)。
+
+        Args:
+            limit: 上限对比值,如 FallenSun 的 limit_count。
+
+        Returns:
+            达到或超过上限返回 True,否则 False。
+        """
+        count = runtime.pub_ctx.per_task.count if runtime.pub_ctx else 0
+        return count >= limit
+
+    @classmethod
+    def battle_state_reset(cls):
+        runtime.reset_per_task()
+        runtime.reset_per_battle()
+
+    def battle_setup(self):
+        pass
+
+    def loadout_from_config(self, conf: GeneralBattleConfig) -> tuple[dict, dict]:
+        """
+        与 loadout_default 相同格式,但由 GeneralBattleConfig 驱动:。
+        """
+        strategies, options = self.loadout_default()
+        options['prepare'] = OptionPrepareDefault(lock_team=conf.lock_team_enable)
+        if conf.preset_enable:
+            options['preset'] = OptionPresetDefault(
+                preset_enable=True, preset_group=conf.preset_group, preset_team=conf.preset_team,
+            )
+        if conf.green_enable:
+            options['green'] = OptionGreenDefault(green_enable=True, green_mark=conf.green_mark)
+        if conf.random_click_swipt_enable:
+            strategies['randomclick'] = 'default'
+            options['randomclick'] = OptionRandomclickDefault()
+        return strategies, options
+
+
+from tasks.Component.GeneralBattle.general_battle import GeneralBattle
+from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
+class BattleTest(Battle, GeneralBattle, ActivityShikigamiAssets):
+
+    def my_test_activity_prepare(self):
+        """
+        活动里面测试,需要先点击战斗准备阶段
+        """
+        strategies, options = self.loadout_default()
+        strategies['prepare'] = 'default'
+        strategies['success'] = 'activity'
+        options['prepare'] = OptionPrepareDefault(lock_team=False)
+        self.loadout_show((strategies, options))
+        with battle_wait_strategy(**strategies), battle_wait_options(**options):
+            self.battle_wait()
+            self.state_show()
+
+    def my_test_activity_preset(self, preset_group: int = 5, preset_team: int = 3):
+        """
+        活动里面测试,准备阶段开启切阵容(预设)
+        """
+        strategies, options = self.loadout_default()
+        strategies['preset'] = 'default'
+        strategies['success'] = 'activity'
+        options['preset'] = OptionPresetDefault(preset_enable=True, preset_group=preset_group, preset_team=preset_team)
+        self.loadout_show((strategies, options))
+        with battle_wait_strategy(**strategies), battle_wait_options(**options):
+            self.battle_wait()
+            self.state_show()
+
+    def my_test_activity_green(self, green_mark: GreenMarkType = GreenMarkType.GREEN_LEFT1):
+        """
+        活动里面测试,绿标标记
+        """
+        strategies, options = self.loadout_default()
+        strategies['green'] = 'default'
+        strategies['success'] = 'activity'
+        options['green'] = OptionGreenDefault(green_enable=True, green_mark=green_mark)
+        self.loadout_show((strategies, options))
+        with battle_wait_strategy(**strategies), battle_wait_options(**options):
+            self.battle_wait()
+            self.state_show()
+
+    def my_test_activity_randomclick(
+            self,
+            start_delay: tuple[float, float] = (5.0, 10.0),
+            cooldown: tuple[float, float] = (15.0, 30.0),
+            trigger_probability: float = 0.6,
+            execution_limit: tuple[int, int] = (1, 2),
+    ):
+        """
+        活动里面测试,随机点击
+        """
+        strategies, options = self.loadout_default()
+        strategies['randomclick'] = 'default'
+        strategies['success'] = 'activity'
+        options['randomclick'] = OptionRandomclickDefault(
+            start_delay=start_delay,
+            cooldown=cooldown,
+            trigger_probability=trigger_probability,
+            execution_limit=execution_limit,
+        )
+        self.loadout_show((strategies, options))
+        with battle_wait_strategy(**strategies), battle_wait_options(**options):
+            self.battle_wait()
+            self.state_show()
+
+    def my_test_activity_continuous(self):
+        """
+        活动里面测试,连续执行
+        """
+        strategies, options = self.loadout_default()
+        strategies['prepare'] = 'default'
+        strategies['success'] = 'activity'
+        options['prepare'] = OptionPrepareDefault(lock_team=False)
+        self.loadout_show((strategies, options))
+        for i in range(5):
+            with battle_wait_strategy(**strategies), battle_wait_options(**options):
+                self.start_fire(buttons=[self.O_FIRE], checks=[self.I_CHECK_BATTLE_MAIN, self.I_CHECK_BATTLE_BOSS])
+                self.battle_wait()
+                self.state_show()
+
+
+
+if __name__ == '__main__':
+    from module.config.config import Config
+    from module.device.device import Device
+    from tasks.Component.GeneralBattle.general_battle import GeneralBattle
+    c = Config('oas1')
+    d = Device(c)
+    t = BattleTest(c, d)
+
+    # t.my_test_activity_prepare()
+    # t.my_test_activity_preset()
+    # t.my_test_activity_green()
+    # t.my_test_activity_randomclick()
+    t.my_test_activity_continuous()

Datei-Diff unterdrückt, da er zu groß ist
+ 883 - 107
tasks/Component/GeneralBattle/battle_wait.py


+ 3 - 5
tasks/Component/GeneralBattle/general_battle.py

@@ -69,9 +69,9 @@ class GeneralBattle(BattleWait, GeneralBuff):
                         self.switch_preset_team(config.preset_enable, config.preset_group, config.preset_team)
                         self.switch_preset_team(config.preset_enable, config.preset_group, config.preset_team)
                         self.check_and_open_buff(buff)
                         self.check_and_open_buff(buff)
                         confed = True
                         confed = True
-                # 点击准备(锁定阵容自动点准备,不锁定阵容前面也已经配置完毕需要点准备)
-                if self.appear_then_click(self.I_PREPARE_HIGHLIGHT, interval=0.8):
-                    continue
+                    # 点击准备(锁定阵容自动点准备,不锁定阵容前面也已经配置完毕需要点准备)
+                    if self.appear_then_click(self.I_PREPARE_HIGHLIGHT, interval=0.8):
+                        continue
                 continue
                 continue
             # 未知界面, 既不是准备界面也不是战斗界面
             # 未知界面, 既不是准备界面也不是战斗界面
             # logger.info('Wait for preparation page')  # 这玩意刷屏
             # logger.info('Wait for preparation page')  # 这玩意刷屏
@@ -666,9 +666,7 @@ if __name__ == '__main__':
                   self.C_PRESET_GROUP_1.roi_back[3]]
                   self.C_PRESET_GROUP_1.roi_back[3]]
     unselected_color = get_unselect_color(self.C_PRESET_GROUP_1, self.C_PRESET_GROUP_2, self.C_PRESET_GROUP_3,
     unselected_color = get_unselect_color(self.C_PRESET_GROUP_1, self.C_PRESET_GROUP_2, self.C_PRESET_GROUP_3,
                                           size=color_size)
                                           size=color_size)
-    print("")
     color_size = [5, 5]
     color_size = [5, 5]
     unselected_color = get_unselect_color(self.C_PRESET_TEAM_1, self.C_PRESET_TEAM_2, self.C_PRESET_TEAM_3,
     unselected_color = get_unselect_color(self.C_PRESET_TEAM_1, self.C_PRESET_TEAM_2, self.C_PRESET_TEAM_3,
                                           size=color_size
                                           size=color_size
                                           )
                                           )
-    print("")

+ 18 - 0
tasks/Component/SwitchOnmyoji/switch_onmyoji.py

@@ -1,4 +1,6 @@
 from module.atom.image import RuleImage
 from module.atom.image import RuleImage
+from module.base.timer import Timer
+from module.exception import ScriptError
 from tasks.Component.SwitchOnmyoji.assets import SwitchOnmyojiAssets
 from tasks.Component.SwitchOnmyoji.assets import SwitchOnmyojiAssets
 from tasks.Component.SwitchOnmyoji.config import Onmyoji
 from tasks.Component.SwitchOnmyoji.config import Onmyoji
 from tasks.base_task import BaseTask
 from tasks.base_task import BaseTask
@@ -6,6 +8,10 @@ from module.logger import logger
 
 
 
 
 class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
 class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
+    # 上限用来给两个 while 循环兜底:资源坐标过期或页面不对时不再无限点,
+    # 改为抛出带上下文的 ScriptError,让上层决定重启还是人工接管。
+    SWITCH_TAB_TIMEOUT = 20
+    SWITCH_BATTLE_TIMEOUT = 20
 
 
     def switch_onmyoji(self, onmyoji: Onmyoji):
     def switch_onmyoji(self, onmyoji: Onmyoji):
         """
         """
@@ -29,7 +35,14 @@ class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
         :param battle_dict: 角色与战斗图标的映射
         :param battle_dict: 角色与战斗图标的映射
         :param check_img: 检查是否回到主界面的图标
         :param check_img: 检查是否回到主界面的图标
         """
         """
+        # 两个循环都必须在超时后抛出,而不是继续点击
+        tab_timer = Timer(self.SWITCH_TAB_TIMEOUT).start()
         while True:
         while True:
+            if tab_timer.reached():
+                raise ScriptError('Switch onmyoji: cannot reach the role list, '
+                                  'the onmyoji tab was not opened after '
+                                  f'{self.SWITCH_TAB_TIMEOUT}s. '
+                                  'Check whether the onmyoji/hero assets still match the game UI')
             self.screenshot()
             self.screenshot()
             if any(self.appear(battle_icon) for battle_icon in battle_dict.values()):
             if any(self.appear(battle_icon) for battle_icon in battle_dict.values()):
                 break
                 break
@@ -37,7 +50,12 @@ class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
         battle_img = battle_dict.get(role, None)
         battle_img = battle_dict.get(role, None)
         if not battle_img:
         if not battle_img:
             raise ValueError('Incorrect role type')
             raise ValueError('Incorrect role type')
+        battle_timer = Timer(self.SWITCH_BATTLE_TIMEOUT).start()
         while True:
         while True:
+            if battle_timer.reached():
+                raise ScriptError(f'Switch onmyoji: cannot select {role}, '
+                                  'the role list stayed unconfirmed after '
+                                  f'{self.SWITCH_BATTLE_TIMEOUT}s')
             self.screenshot()
             self.screenshot()
             if self.appear(check_img, interval=0.8):
             if self.appear(check_img, interval=0.8):
                 break
                 break

+ 1 - 1
tasks/DailyTrifles/script_task.py

@@ -222,7 +222,7 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
         if self.config.daily_trifles.trifles_config.buy_sushi_count > 0:
         if self.config.daily_trifles.trifles_config.buy_sushi_count > 0:
             self.run_buy_sushi()
             self.run_buy_sushi()
 
 
-        self.ui_click(self.I_UI_BACK_YELLOW, self.I_CHECK_MALL)
+        self.ui_click(self.I_UI_BACK_YELLOW, self.I_CHECK_MALL, interval=2.4, timeout=8)
         self.ui_get_current_page()
         self.ui_get_current_page()
         self.ui_goto(page_main)
         self.ui_goto(page_main)
 
 

+ 1 - 1
tasks/DemonEncounter/assets.py

@@ -126,7 +126,7 @@ class DemonEncounterAssets:
 	# 计数已经开启多少的 
 	# 计数已经开启多少的 
 	O_DE_COUNTER = RuleOcr(roi=(1204,685,48,34), area=(1204,685,48,34), mode="DigitCounter", method="Default", keyword="", name="de_counter")
 	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表示已打过直接结束 
 	# 现世逢魔顶部今日挑战次数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")
+	O_DE_CHALLENGE_COUNT = RuleOcr(roi=(705,68,45,36), area=(705,68,45,36), mode="Full", method="Default", keyword="", name="de_challenge_count")
 
 
 
 
 	# Click Rule Assets
 	# Click Rule Assets

+ 2 - 2
tasks/DemonEncounter/demon/ocr.json

@@ -10,8 +10,8 @@
   },
   },
   {
   {
     "itemName": "de_challenge_count",
     "itemName": "de_challenge_count",
-    "roiFront": "680,68,75,36",
-    "roiBack": "680,68,75,36",
+    "roiFront": "705,68,45,36",
+    "roiBack": "705,68,45,36",
     "mode": "Full",
     "mode": "Full",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",

+ 12 - 3
tasks/Exploration/solo.py

@@ -2,6 +2,7 @@
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
 from time import sleep
 from time import sleep
+from copy import deepcopy
 from cached_property import cached_property
 from cached_property import cached_property
 
 
 from module.logger import logger
 from module.logger import logger
@@ -134,7 +135,6 @@ class SoloExploration(BaseExploration):
         while 1:
         while 1:
             self.screenshot()
             self.screenshot()
             scene = self.get_current_scene()
             scene = self.get_current_scene()
-            logger.info(f'[run_leader] Current scene: {scene.name}')  # TODO 2026.06.22 之后删掉这个刷屏的
             # 探索大世界
             # 探索大世界
             if scene == Scene.WORLD:
             if scene == Scene.WORLD:
                 # 打开右边箭头
                 # 打开右边箭头
@@ -337,6 +337,15 @@ class SoloExploration(BaseExploration):
                 friend_class[i] = '跨区'
                 friend_class[i] = '跨区'
         logger.info(f'Friend class: {friend_class}')
         logger.info(f'Friend class: {friend_class}')
 
 
+        # 76e2a874(#1509) 把 I_FLAG_2_ON 的 roi 改到了 tab 标签栏上方的空白区
+        # (472,82,32,11) / (454,74,56,26),导致第 2 个 tab 的选中态永远匹配不上,
+        # while index == 1 死循环点满 10 次触发 GameTooManyClickError。
+        # 这里深拷贝一份并还原成 439be142(#1443) 的 roi,不改动原资源。
+        # https://github.com/runhey/OnmyojiAutoScript/issues/1844
+        flag_2_on = deepcopy(self.I_FLAG_2_ON)
+        flag_2_on.roi_front = [471, 128, 54, 18]
+        flag_2_on.roi_back = (471, 128, 54, 18)
+
         is_select: bool = False  # 是否选中了好友
         is_select: bool = False  # 是否选中了好友
         if find_mode == FindMode.RECENT_FRIEND:
         if find_mode == FindMode.RECENT_FRIEND:
             logger.info('Find recent friend')
             logger.info('Find recent friend')
@@ -347,7 +356,7 @@ class SoloExploration(BaseExploration):
             recent_index = friend_class.index('最近')
             recent_index = friend_class.index('最近')
             while recent_index == 1:
             while recent_index == 1:
                 self.screenshot()
                 self.screenshot()
-                if self.appear(self.I_FLAG_2_ON):
+                if self.appear(flag_2_on):
                     break
                     break
                 if self.appear_then_click(self.I_FLAG_2_OFF, interval=1):
                 if self.appear_then_click(self.I_FLAG_2_OFF, interval=1):
                     continue
                     continue
@@ -378,7 +387,7 @@ class SoloExploration(BaseExploration):
                     continue
                     continue
             while index == 1:
             while index == 1:
                 self.screenshot()
                 self.screenshot()
-                if self.I_FLAG_2_ON.match_mean_color(self.device.image, self.INVITE_FLAG_ON, 10):
+                if flag_2_on.match_mean_color(self.device.image, self.INVITE_FLAG_ON, 10):
                     break
                     break
                 if self.click(self.I_FLAG_2_OFF, interval=1):
                 if self.click(self.I_FLAG_2_OFF, interval=1):
                     continue
                     continue

+ 19 - 17
tasks/FrogBoss/assets.py

@@ -12,48 +12,50 @@ class FrogBossAssets:
 
 
 	# Image Rule Assets
 	# Image Rule Assets
 	# 左边竞猜 
 	# 左边竞猜 
-	I_BET_LEFT = RuleImage(roi_front=(95,308,145,100), roi_back=(58,248,245,195), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_left.png")
+	I_BET_LEFT = RuleImage(roi_front=(271,303,145,100), roi_back=(222,251,245,195), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_left.png")
 	# 右边竞猜 
 	# 右边竞猜 
-	I_BET_RIGHT = RuleImage(roi_front=(1038,303,146,100), roi_back=(1012,268,187,208), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_right.png")
+	I_BET_RIGHT = RuleImage(roi_front=(1070,302,146,100), roi_back=(1048,248,187,208), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_right.png")
 	# description 
 	# description 
-	I_BET_SUCCESS_BOX = RuleImage(roi_front=(593,419,87,50), roi_back=(564,378,140,133), threshold=0.75, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success_box.png")
+	I_BET_SUCCESS_BOX = RuleImage(roi_front=(708,394,87,50), roi_back=(661,331,193,182), threshold=0.75, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success_box.png")
 	# 左边赢了 
 	# 左边赢了 
-	I_SUCCESS_LEFT = RuleImage(roi_front=(123,316,100,100), roi_back=(91,254,202,221), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_left.png")
+	I_SUCCESS_LEFT = RuleImage(roi_front=(292,306,100,100), roi_back=(238,243,202,221), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_left.png")
 	# 右边输了 
 	# 右边输了 
-	I_FAILURE_RIGHT = RuleImage(roi_front=(1063,291,100,100), roi_back=(993,242,224,199), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_right.png")
+	I_FAILURE_RIGHT = RuleImage(roi_front=(1097,303,100,100), roi_back=(1029,256,224,199), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_right.png")
 	# description 
 	# description 
-	I_NEXT_COMPETITION = RuleImage(roi_front=(673,510,42,36), roi_back=(658,488,91,98), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.png")
+	I_NEXT_COMPETITION = RuleImage(roi_front=(775,485,42,36), roi_back=(692,437,157,147), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.png")
 	# 30万金币 
 	# 30万金币 
-	I_GOLD_30 = RuleImage(roi_front=(858,494,78,76), roi_back=(809,427,147,187), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30.png")
+	I_GOLD_30 = RuleImage(roi_front=(862,499,78,76), roi_back=(831,441,147,187), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30.png")
 	# 确认竞猜 
 	# 确认竞猜 
-	I_BET_SURE = RuleImage(roi_front=(1025,402,100,100), roi_back=(1000,297,200,226), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_sure.png")
+	I_BET_SURE = RuleImage(roi_front=(1025,402,100,100), roi_back=(972,340,200,226), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_sure.png")
 	# description 
 	# description 
 	I_GOLD_30_CHECK = RuleImage(roi_front=(513,196,58,53), roi_back=(402,141,459,489), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30_check.png")
 	I_GOLD_30_CHECK = RuleImage(roi_front=(513,196,58,53), roi_back=(402,141,459,489), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30_check.png")
 	# description 
 	# description 
-	I_BETTED = RuleImage(roi_front=(93,352,125,54), roi_back=(49,283,1192,161), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_betted.png")
+	I_BETTED = RuleImage(roi_front=(1093,313,125,54), roi_back=(207,240,1058,312), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_betted.png")
 	# description 
 	# description 
-	I_SUCCESS_RIGHT = RuleImage(roi_front=(1048,341,122,116), roi_back=(999,243,201,260), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_right.png")
+	I_SUCCESS_RIGHT = RuleImage(roi_front=(1098,289,122,116), roi_back=(1040,250,201,260), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_right.png")
 	# description 
 	# description 
-	I_FAILURE_LEFT = RuleImage(roi_front=(116,307,100,100), roi_back=(76,256,193,219), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_left.png")
+	I_FAILURE_LEFT = RuleImage(roi_front=(296,303,100,100), roi_back=(243,245,212,259), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_left.png")
 	# description 
 	# description 
-	I_BET_FAILURE = RuleImage(roi_front=(496,252,269,72), roi_back=(439,220,400,152), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_failure.png")
+	I_BET_FAILURE = RuleImage(roi_front=(591,290,269,72), roi_back=(496,222,447,211), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_failure.png")
 	# description 
 	# description 
-	I_BET_SUCCESS = RuleImage(roi_front=(512,264,260,73), roi_back=(433,214,418,151), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success.png")
+	I_BET_SUCCESS = RuleImage(roi_front=(625,278,260,73), roi_back=(482,243,521,225), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success.png")
 
 
 
 
 	# Image Rule Assets
 	# Image Rule Assets
 	# description 
 	# description 
-	I_FROG_BOSS_ENTER = RuleImage(roi_front=(1191,391,36,38), roi_back=(1174,135,78,320), threshold=0.7, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_enter.png")
+	I_FROG_BOSS_ENTER = RuleImage(roi_front=(1188,303,36,38), roi_back=(1169,203,78,320), threshold=0.7, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_enter.png")
 	# 休息中 
 	# 休息中 
 	I_FROG_BOSS_REST = RuleImage(roi_front=(510,274,169,64), roi_back=(492,260,220,113), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_rest.png")
 	I_FROG_BOSS_REST = RuleImage(roi_front=(510,274,169,64), roi_back=(492,260,220,113), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_rest.png")
+	# 竞猜主页面
+	I_FROG_CHECK = RuleImage(roi_front=(664,31,148,65), roi_back=(551,4,371,145), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_check.png")
 
 
 
 
 	# Ocr Rule Assets
 	# Ocr Rule Assets
 	# Ocr-description 
 	# Ocr-description 
-	O_LEFT_COUNT = RuleOcr(roi=(143,496,69,31), area=(143,496,69,31), mode="Digit", method="Default", keyword="", name="left_count")
+	O_LEFT_COUNT = RuleOcr(roi=(326,469,69,31), area=(326,469,69,31), mode="Digit", method="Default", keyword="", name="left_count")
 	# Ocr-description 
 	# Ocr-description 
-	O_RIGHT_COUNT = RuleOcr(roi=(1105,497,77,32), area=(1105,497,77,32), mode="Digit", method="Default", keyword="", name="right_count")
+	O_RIGHT_COUNT = RuleOcr(roi=(1139,472,77,32), area=(1139,472,77,32), mode="Digit", method="Default", keyword="", name="right_count")
 	# Ocr-description 
 	# Ocr-description 
-	O_TIME_REMAIN = RuleOcr(roi=(594,564,91,35), area=(594,564,91,35), mode="Duration", method="Default", keyword="", name="time_remain")
+	O_TIME_REMAIN = RuleOcr(roi=(705,533,91,35), area=(705,533,91,35), mode="Duration", method="Default", keyword="", name="time_remain")
 
 
 
 

+ 1 - 0
tasks/FrogBoss/config.py

@@ -14,6 +14,7 @@ class Strategy(str, Enum):
     Minority = 'frog_minority'
     Minority = 'frog_minority'
     Bilibili = 'frog_bilibili'
     Bilibili = 'frog_bilibili'
     Dashen = 'frog_dashen'
     Dashen = 'frog_dashen'
+    Oas = 'frog_oas'
     AlwaysRed = 'frog_always_red'
     AlwaysRed = 'frog_always_red'
     AlwaysBlue = 'frog_always_blue'
     AlwaysBlue = 'frog_always_blue'
 
 

BIN
tasks/FrogBoss/fb/fb_bet_left.png


BIN
tasks/FrogBoss/fb/fb_bet_right.png


BIN
tasks/FrogBoss/fb/fb_bet_success.png


BIN
tasks/FrogBoss/fb/fb_bet_success_box.png


BIN
tasks/FrogBoss/fb/fb_betted.png


BIN
tasks/FrogBoss/fb/fb_failure_left.png


BIN
tasks/FrogBoss/fb/fb_frog_boss_enter.png


BIN
tasks/FrogBoss/fb/fb_frog_check.png


BIN
tasks/FrogBoss/fb/fb_next_competition.png


BIN
tasks/FrogBoss/fb/fb_success_right.png


+ 39 - 25
tasks/FrogBoss/fb/image.json

@@ -2,73 +2,81 @@
   {
   {
     "itemName": "bet_left",
     "itemName": "bet_left",
     "imageName": "fb_bet_left.png",
     "imageName": "fb_bet_left.png",
-    "roiFront": "95,308,145,100",
-    "roiBack": "58,248,245,195",
+    "roiFront": "271,303,145,100",
+    "roiBack": "222,251,245,195",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "左边竞猜"
     "description": "左边竞猜"
   },
   },
   {
   {
     "itemName": "bet_right",
     "itemName": "bet_right",
     "imageName": "fb_bet_right.png",
     "imageName": "fb_bet_right.png",
-    "roiFront": "1038,303,146,100",
-    "roiBack": "1012,268,187,208",
+    "roiFront": "1070,302,146,100",
+    "roiBack": "1048,248,187,208",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "右边竞猜"
     "description": "右边竞猜"
   },
   },
   {
   {
     "itemName": "bet_success_box",
     "itemName": "bet_success_box",
     "imageName": "fb_bet_success_box.png",
     "imageName": "fb_bet_success_box.png",
-    "roiFront": "593,419,87,50",
-    "roiBack": "564,378,140,133",
+    "roiFront": "708,394,87,50",
+    "roiBack": "661,331,193,182",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.75,
     "threshold": 0.75,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "success_left",
     "itemName": "success_left",
     "imageName": "fb_success_left.png",
     "imageName": "fb_success_left.png",
-    "roiFront": "123,316,100,100",
-    "roiBack": "91,254,202,221",
+    "roiFront": "292,306,100,100",
+    "roiBack": "238,243,202,221",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "左边赢了"
     "description": "左边赢了"
   },
   },
   {
   {
     "itemName": "failure_right",
     "itemName": "failure_right",
     "imageName": "fb_failure_right.png",
     "imageName": "fb_failure_right.png",
-    "roiFront": "1063,291,100,100",
-    "roiBack": "993,242,224,199",
+    "roiFront": "1097,303,100,100",
+    "roiBack": "1029,256,224,199",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "右边输了"
     "description": "右边输了"
   },
   },
   {
   {
     "itemName": "next_competition",
     "itemName": "next_competition",
     "imageName": "fb_next_competition.png",
     "imageName": "fb_next_competition.png",
-    "roiFront": "673,510,42,36",
-    "roiBack": "658,488,91,98",
+    "roiFront": "775,485,42,36",
+    "roiBack": "692,437,157,147",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "gold_30",
     "itemName": "gold_30",
     "imageName": "fb_gold_30.png",
     "imageName": "fb_gold_30.png",
-    "roiFront": "858,494,78,76",
-    "roiBack": "809,427,147,187",
+    "roiFront": "862,499,78,76",
+    "roiBack": "831,441,147,187",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "30万金币"
     "description": "30万金币"
   },
   },
   {
   {
     "itemName": "bet_sure",
     "itemName": "bet_sure",
     "imageName": "fb_bet_sure.png",
     "imageName": "fb_bet_sure.png",
     "roiFront": "1025,402,100,100",
     "roiFront": "1025,402,100,100",
-    "roiBack": "1000,297,200,226",
+    "roiBack": "972,340,200,226",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "确认竞猜"
     "description": "确认竞猜"
   },
   },
   {
   {
@@ -78,51 +86,57 @@
     "roiBack": "402,141,459,489",
     "roiBack": "402,141,459,489",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "betted",
     "itemName": "betted",
     "imageName": "fb_betted.png",
     "imageName": "fb_betted.png",
-    "roiFront": "93,352,125,54",
-    "roiBack": "49,283,1192,161",
+    "roiFront": "1093,313,125,54",
+    "roiBack": "207,240,1058,312",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "success_right",
     "itemName": "success_right",
     "imageName": "fb_success_right.png",
     "imageName": "fb_success_right.png",
-    "roiFront": "1048,341,122,116",
-    "roiBack": "999,243,201,260",
+    "roiFront": "1098,289,122,116",
+    "roiBack": "1040,250,201,260",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "failure_left",
     "itemName": "failure_left",
     "imageName": "fb_failure_left.png",
     "imageName": "fb_failure_left.png",
-    "roiFront": "116,307,100,100",
-    "roiBack": "76,256,193,219",
+    "roiFront": "296,303,100,100",
+    "roiBack": "243,245,212,259",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "bet_failure",
     "itemName": "bet_failure",
     "imageName": "fb_bet_failure.png",
     "imageName": "fb_bet_failure.png",
-    "roiFront": "496,252,269,72",
-    "roiBack": "439,220,400,152",
+    "roiFront": "591,290,269,72",
+    "roiBack": "496,222,447,211",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
     "itemName": "bet_success",
     "itemName": "bet_success",
     "imageName": "fb_bet_success.png",
     "imageName": "fb_bet_success.png",
-    "roiFront": "512,264,260,73",
-    "roiBack": "433,214,418,151",
+    "roiFront": "625,278,260,73",
+    "roiBack": "482,243,521,225",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   }
   }
 ]
 ]

+ 14 - 2
tasks/FrogBoss/fb/image2.json

@@ -2,10 +2,11 @@
   {
   {
     "itemName": "frog_boss_enter",
     "itemName": "frog_boss_enter",
     "imageName": "fb_frog_boss_enter.png",
     "imageName": "fb_frog_boss_enter.png",
-    "roiFront": "1191,391,36,38",
-    "roiBack": "1174,135,78,320",
+    "roiFront": "1188,303,36,38",
+    "roiBack": "1169,203,78,320",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.7,
     "threshold": 0.7,
+    "profile": "Default",
     "description": "description"
     "description": "description"
   },
   },
   {
   {
@@ -15,6 +16,17 @@
     "roiBack": "492,260,220,113",
     "roiBack": "492,260,220,113",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
+    "profile": "Default",
     "description": "休息中"
     "description": "休息中"
+  },
+  {
+    "itemName": "frog_check",
+    "imageName": "fb_frog_check.png",
+    "roiFront": "664,31,148,65",
+    "roiBack": "551,4,371,145",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "profile": "Default",
+    "description": "竞猜主页面"
   }
   }
 ]
 ]

+ 6 - 6
tasks/FrogBoss/fb/ocr.json

@@ -1,8 +1,8 @@
 [
 [
   {
   {
     "itemName": "left_count",
     "itemName": "left_count",
-    "roiFront": "143,496,69,31",
-    "roiBack": "143,496,69,31",
+    "roiFront": "326,469,69,31",
+    "roiBack": "326,469,69,31",
     "mode": "Digit",
     "mode": "Digit",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",
@@ -10,8 +10,8 @@
   },
   },
   {
   {
     "itemName": "right_count",
     "itemName": "right_count",
-    "roiFront": "1105,497,77,32",
-    "roiBack": "1105,497,77,32",
+    "roiFront": "1139,472,77,32",
+    "roiBack": "1139,472,77,32",
     "mode": "Digit",
     "mode": "Digit",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",
@@ -19,8 +19,8 @@
   },
   },
   {
   {
     "itemName": "time_remain",
     "itemName": "time_remain",
-    "roiFront": "594,564,91,35",
-    "roiBack": "594,564,91,35",
+    "roiFront": "705,533,91,35",
+    "roiBack": "705,533,91,35",
     "mode": "Duration",
     "mode": "Duration",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",

+ 184 - 0
tasks/FrogBoss/frog_oas.py

@@ -0,0 +1,184 @@
+"""Persistent, outcome-verified weighted voting. Scores are not win probabilities."""
+import json
+import re
+import random
+from datetime import datetime
+from pathlib import Path
+from uuid import uuid4
+
+import cv2
+import requests
+
+from tasks.FrogBoss.oas_sources import DASHEN_UIDS
+
+
+def fingerprint(image):
+    # Only the two lineups: excludes countdown, votes, chest and result text.
+    bits = []
+    for x in (300, 807):
+        crop = image[112:233, x:x + 398]
+        gray = cv2.cvtColor(crop, cv2.COLOR_RGB2GRAY)
+        small = cv2.resize(gray, (33, 8))
+        bits.extend((small[:, 1:] > small[:, :-1]).flatten())
+    return ''.join('1' if bit else '0' for bit in bits)
+
+
+def same_lineup(a, b):
+    return len(a) == len(b) == 512 and sum(x != y for x, y in zip(a, b)) <= 20
+
+
+def parse_side(text):
+    # Ambiguous text is deliberately excluded rather than guessed by word order.
+    red = bool(re.search(r'押红|押左|压红|压左|我红|我左|红优|红方胜|红色胜', text))
+    blue = bool(re.search(r'押蓝|押右|压蓝|压右|我蓝|我右|蓝优|蓝方胜|蓝色胜', text))
+    if re.search(r'不押|不压|别押|别压|不要押|不要压', text):
+        return None
+    return ('LEFT' if red else 'RIGHT') if red != blue else None
+
+
+class OasHistory:
+    def __init__(self, path):
+        self.path = Path(path)
+        self.events = []
+        if self.path.exists():
+            for line in self.path.read_text(encoding='utf-8').splitlines():
+                try:
+                    event = json.loads(line)
+                except ValueError:
+                    continue  # Ignore a truncated final record after interruption.
+                if isinstance(event, dict):
+                    self.events.append(event)
+
+    def append(self, kind, **data):
+        event = dict(version=1, kind=kind, recorded_at=datetime.now().isoformat(), **data)
+        self.path.parent.mkdir(parents=True, exist_ok=True)
+        # Leading newline separates a possible truncated tail from the new event.
+        with self.path.open('a', encoding='utf-8') as stream:
+            stream.write('\n' + json.dumps(event, ensure_ascii=False) + '\n')
+            stream.flush()
+        self.events.append(event)
+        return event
+
+    def reliability(self, source):
+        decisions = {e['id']: e for e in self.events if e.get('kind') == 'decision'}
+        correct = total = 0
+        seen = set()
+        for result in self.events:
+            if result.get('kind') != 'result' or result['id'] in seen:
+                continue
+            seen.add(result['id'])
+            vote = decisions.get(result['id'], {}).get('votes', {}).get(source)
+            if vote in ('LEFT', 'RIGHT'):
+                total += 1
+                correct += vote == result['winner']
+        # Unverified newcomers start neutral; verified sources use raw win rate.
+        return correct / total if total else 0.5
+
+    def settle(self, signature, winner):
+        if winner not in ('LEFT', 'RIGHT'):
+            return None
+        # Include already settled records when checking ambiguity: never transfer
+        # an old result to a newer decision with an identical lineup.
+        matches = [e for e in self.events if e.get('kind') == 'decision'
+                   and same_lineup(e['signature'], signature)]
+        if len(matches) != 1:
+            self.append('unverified_result', signature=signature, winner=winner,
+                        reason='missing_or_ambiguous_decision')
+            return None
+        decision = matches[0]
+        if any(e.get('kind') == 'result' and e['id'] == decision['id'] for e in self.events):
+            return None
+        return self.append('result', id=decision['id'], winner=winner,
+                           outcomes={s: v == winner for s, v in decision['votes'].items()})
+
+    def choose(self, signature, left, right, predictions):
+        now = datetime.now()
+        # Re-entry in the same slot reuses the original frozen decision.
+        slot = f'{now.date()}:{now.hour // 2}'
+        for e in reversed(self.events):
+            if e.get('kind') == 'decision' and e['slot'] == slot and same_lineup(e['signature'], signature):
+                return e
+        crowd = ('LEFT' if left > right else 'RIGHT') if left != right and left + right > 0 else None
+        votes = {p['uid']: p['side'] for p in predictions if p.get('side') in ('LEFT', 'RIGHT')}
+        expert_left = sum(v == 'LEFT' for v in votes.values())
+        expert_right = sum(v == 'RIGHT' for v in votes.values())
+        expert_side = ('LEFT' if expert_left > expert_right else 'RIGHT') if expert_left != expert_right else None
+        if crowd:
+            votes['crowd'] = crowd
+        cold_start = not any(e.get('kind') == 'result' for e in self.events)
+        weights = {} if cold_start else {uid: self.reliability(uid) for uid in votes}
+        scores = {'LEFT': 0.0, 'RIGHT': 0.0}
+        if cold_start:
+            # Two equal votes: the expert majority as a whole and the crowd.
+            for vote in (expert_side, crowd):
+                if vote:
+                    scores[vote] += 1
+        else:
+            for uid, vote in votes.items():
+                scores[vote] += weights[uid]
+        tied = abs(scores['LEFT'] - scores['RIGHT']) < 1e-12
+        side = random.choice(('LEFT', 'RIGHT')) if tied else max(scores, key=scores.get)
+        return self.append('decision', id=uuid4().hex, slot=slot, signature=signature,
+                           left=left, right=right, votes=votes, weights=weights,
+                           scores=scores, side=side, strategy_version=2,
+                           mode='cold_start' if cold_start else 'win_rate',
+                           expert_counts={'LEFT': expert_left, 'RIGHT': expert_right},
+                           expert_side=expert_side, crowd_side=crowd, random_tiebreak=tied)
+
+
+def _response_result(response):
+    payload = response.json()
+    if not isinstance(payload, dict) or not isinstance(payload.get('result'), dict):
+        raise ValueError('Dashen response must contain a result object')
+    return payload['result']
+
+
+def fetch_predictions(history):
+    now = datetime.now()
+    used = {(e.get('uid'), e.get('feed_id')) for e in history.events
+            if e.get('kind') == 'fetch' and e.get('accepted')}
+    predictions = []
+    with requests.Session() as session:
+        for uid in DASHEN_UIDS:
+            feed_id = None
+            try:
+                response = session.get('https://inf.ds.163.com/v1/web/feed/basic/getSomeOneFeeds',
+                                       params={'feedTypes': '1,2,3,4,6,7,10,11', 'someOneUid': uid}, timeout=(3, 5))
+                response.raise_for_status()
+                feeds = _response_result(response).get('feeds', [])
+                if not isinstance(feeds, list):
+                    raise ValueError('Dashen feeds must be a list')
+                if not feeds:
+                    history.append('fetch', uid=uid, accepted=False, reason='no_feed')
+                    continue
+                if not isinstance(feeds[0], dict) or not feeds[0].get('id'):
+                    raise ValueError('Dashen feed entry must contain an id')
+                feed_id = feeds[0]['id']
+                response = session.get('https://inf.ds.163.com/v1/web/feed/basic/facade',
+                                       params={'feedId': feed_id}, timeout=(3, 5))
+                response.raise_for_status()
+                feed = _response_result(response)['feed']
+                if not isinstance(feed, dict):
+                    raise ValueError('Dashen feed must be an object')
+                content = feed['content']
+                if isinstance(content, str):
+                    content = json.loads(content)
+                body = content['body']['text']
+                raw_time = feed.get('createTime')
+                published = None
+                try:
+                    published = datetime.fromtimestamp(float(raw_time) / 1000)
+                except (TypeError, ValueError, OverflowError, OSError):
+                    pass
+                side = parse_side(body)
+                fresh = published is not None and published.date() == now.date() and published.hour // 2 == now.hour // 2 and published <= now
+                accepted = fresh and side is not None and (uid, feed_id) not in used
+                history.append('fetch', uid=uid, feed_id=feed_id, create_time=raw_time,
+                               body=body, side=side, accepted=accepted,
+                               reason='accepted' if accepted else 'stale_unknown_ambiguous_or_duplicate')
+                if accepted:
+                    predictions.append(dict(uid=uid, side=side, feed_id=feed_id))
+            except (requests.RequestException, ValueError, KeyError, IndexError, TypeError) as exc:
+                history.append('fetch', uid=uid, feed_id=feed_id, accepted=False,
+                               reason='request_or_parse_error', error=str(exc))
+    return predictions

+ 2 - 0
tasks/FrogBoss/oas_sources.py

@@ -0,0 +1,2 @@
+"""UIDs shared with the legacy Dashen strategy; deduplicated for frog_oas."""
+DASHEN_UIDS = ["462382f1127b46c5add1185d88f0ea40","54399446d5084a0e8878dac8f6ff56d0","840742d60e4a43208605ae68ca8c3f64","c3c989fae4074d04b478b8ba47ae4120","aaa923436aa440df9ac1ee3f47387b99","72584a679e2f45b6859566b5523400d5","3d4726d99f2642a485729695b798cb8c","1d2dcbbd7e3d481c8d0f27ba4ff0dc71","21657a558bdd4ddfb6501298350336e7","0e4e0c5a1e494a1fa9a58ac55de689c1","30e383c884f844a18a7a76fe3c1e888f","d9dc2a75497c4a91b2db1e909a36544d","e7107cd3010e418da26672669d8eeb5e","74adeb1bfb2b4cf382edbbb430da2149","e87f855f36f24b34b9d8f8a4fb2d62b2","82de68c7672e4b6da65493fb829b57b6","f6d6bb15d6024200a985752e2ab4c373","06e2bba14a914012bc8064601cfa19ea","8982241de1844638b4bb455139b8dcc0","a9724e98c1cb4a4e931ebc3f467ea73d","e9b0a16325af46628e8dfb9e7942cf1d","b6b5bc8277e34f69aeca018db0081397","74db771d92a54c28ae3e98d19aa565a3","e498e524252041e29999b38e57c4df1d","30b0c2923faa483f95572c324a5bc910","e32aedbdd8da46a5b5b497a16c4b7658"]

+ 45 - 3
tasks/FrogBoss/script_task.py

@@ -6,8 +6,9 @@ from datetime import datetime
 import requests
 import requests
 import re
 import re
 import json
 import json
+from pathlib import Path
 
 
-from module.exception import TaskEnd
+from module.exception import GameStuckError, TaskEnd
 from module.logger import logger
 from module.logger import logger
 from module.atom.image import RuleImage
 from module.atom.image import RuleImage
 from module.base.timer import Timer
 from module.base.timer import Timer
@@ -19,11 +20,34 @@ from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
 from tasks.Component.config_base import TimeDelta
 from tasks.Component.config_base import TimeDelta
 from tasks.FrogBoss.assets import FrogBossAssets
 from tasks.FrogBoss.assets import FrogBossAssets
 from tasks.FrogBoss.config import Strategy
 from tasks.FrogBoss.config import Strategy
+from tasks.FrogBoss.frog_oas import OasHistory, fetch_predictions, fingerprint
 
 
 
 
 class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
 class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
-    def run(self):
+    @cached_property
+    def oas_history(self):
+        instance = re.sub(r'[^\w.-]', '_', self.config.config_name)
+        return OasHistory(Path('data/frog_oas') / f'{instance}.jsonl')
+
+    def record_oas_result(self):
+        if self.config.model.frog_boss.frog_boss_config.strategy_frog != Strategy.Oas:
+            return
+        winner = self.detect()
+        if winner is not None:
+            result = self.oas_history.settle(
+                fingerprint(self.device.image), 'LEFT' if winner else 'RIGHT')
+            logger.info(f'frog_oas result: {result}')
+
+    def enter_frog_boss(self):
+        self.screenshot()
+        if self.appear(self.I_FROG_CHECK):
+            return
         self.enter(self.I_FROG_BOSS_ENTER)
         self.enter(self.I_FROG_BOSS_ENTER)
+        if not self.wait_until_appear(self.I_FROG_CHECK, wait_time=10):
+            raise GameStuckError('FrogBoss page not detected after entering activity')
+
+    def run(self):
+        self.enter_frog_boss()
         # 进入主界面
         # 进入主界面
         while 1:
         while 1:
             self.screenshot()
             self.screenshot()
@@ -39,6 +63,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             # 竞猜成功
             # 竞猜成功
             if self.appear(self.I_BET_SUCCESS):
             if self.appear(self.I_BET_SUCCESS):
                 logger.info('You bet win')
                 logger.info('You bet win')
+                self.record_oas_result()
                 self.detect()
                 self.detect()
                 while 1:
                 while 1:
                     self.screenshot()
                     self.screenshot()
@@ -54,6 +79,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             # 竞猜失败
             # 竞猜失败
             if self.appear(self.I_BET_FAILURE):
             if self.appear(self.I_BET_FAILURE):
                 logger.info('You bet lose')
                 logger.info('You bet lose')
+                self.record_oas_result()
                 self.ui_click_until_disappear(self.I_NEXT_COMPETITION)
                 self.ui_click_until_disappear(self.I_NEXT_COMPETITION)
                 self.detect()
                 self.detect()
                 continue
                 continue
@@ -105,6 +131,22 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
                 click_image = self.I_BET_LEFT if count_left > count_right else self.I_BET_RIGHT
                 click_image = self.I_BET_LEFT if count_left > count_right else self.I_BET_RIGHT
             case Strategy.Dashen:
             case Strategy.Dashen:
                 click_image = self.get_dashen(count_left, count_right)
                 click_image = self.get_dashen(count_left, count_right)
+            case Strategy.Oas:
+                signature = fingerprint(self.device.image)
+                predictions = fetch_predictions(self.oas_history)
+                try:
+                    decision = self.oas_history.choose(signature, count_left, count_right, predictions)
+                except ValueError as exc:
+                    raise GameStuckError(str(exc)) from exc
+                logger.info(f'frog_oas decision: {decision}')
+                # Fetching may span a round transition; never click a stale frame.
+                self.screenshot()
+                from tasks.FrogBoss.frog_oas import same_lineup
+                if not same_lineup(signature, fingerprint(self.device.image)):
+                    raise GameStuckError('FrogBoss lineup changed while fetching predictions')
+                if not (self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT)):
+                    raise GameStuckError('FrogBoss betting closed while fetching predictions')
+                click_image = self.I_BET_LEFT if decision['side'] == 'LEFT' else self.I_BET_RIGHT
             case Strategy.AlwaysRed:
             case Strategy.AlwaysRed:
                 click_image = self.I_BET_LEFT
                 click_image = self.I_BET_LEFT
             case Strategy.AlwaysBlue:
             case Strategy.AlwaysBlue:
@@ -152,7 +194,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             result = False
             result = False
             logger.info('Right win')
             logger.info('Right win')
         else:
         else:
-            result = True
+            result = None
         return result
         return result
 
 
     def get_bilibili(self) -> RuleImage:
     def get_bilibili(self) -> RuleImage:

+ 106 - 0
tasks/FrogBoss/test_frog_oas.py

@@ -0,0 +1,106 @@
+import tempfile
+import unittest
+from datetime import datetime, timedelta
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from tasks.FrogBoss.frog_oas import OasHistory, fetch_predictions, parse_side, same_lineup
+
+
+class OasTests(unittest.TestCase):
+    def test_persistence_rewards_and_dedup(self):
+        with tempfile.TemporaryDirectory() as directory:
+            path = Path(directory) / 'history.jsonl'
+            store = OasHistory(path)
+            decision = store.choose('0' * 512, 20, 10, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'RIGHT'}])
+            self.assertEqual(store.reliability('a'), .5)
+            self.assertEqual(store.choose('0' * 512, 10, 20, [])['id'], decision['id'])
+            self.assertIsNone(store.settle('1' * 512, 'LEFT'))
+            store.settle('0' * 512, 'LEFT')
+            self.assertIsNone(store.settle('0' * 512, 'LEFT'))
+            reloaded = OasHistory(path)
+            self.assertEqual(reloaded.reliability('a'), 1)
+            self.assertEqual(reloaded.reliability('b'), 0)
+            self.assertEqual(reloaded.reliability('crowd'), 1)
+            second = reloaded.choose('1' * 512, 10, 20, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'LEFT'}])
+            self.assertEqual(second['scores'], {'LEFT': 1, 'RIGHT': 1})
+            self.assertEqual(second['mode'], 'win_rate')
+            reloaded.settle('1' * 512, 'RIGHT')
+            self.assertEqual(reloaded.reliability('a'), .5)
+            self.assertEqual(reloaded.reliability('b'), 0)
+            self.assertEqual(reloaded.reliability('crowd'), 1)
+
+    def test_fallback_and_missing_data(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            self.assertEqual(store.choose('0' * 512, 1, 2, [])['side'], 'RIGHT')
+            self.assertEqual(store.reliability('crowd'), .5)
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='LEFT'):
+                self.assertEqual(store.choose('1' * 512, 0, 0, [])['side'], 'LEFT')
+
+    def test_cold_start_two_equal_groups(self):
+        predictions = [{'uid': str(i), 'side': 'LEFT' if i < 6 else 'RIGHT'} for i in range(9)]
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            agreed = store.choose('0' * 512, 20, 10, predictions)
+            self.assertEqual(agreed['side'], 'LEFT')
+            self.assertEqual(agreed['scores'], {'LEFT': 2, 'RIGHT': 0})
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='RIGHT') as choose:
+                opposed = store.choose('1' * 512, 10, 20, predictions)
+                self.assertEqual(opposed['scores'], {'LEFT': 1, 'RIGHT': 1})
+                self.assertEqual(opposed['side'], 'RIGHT')
+                choose.assert_called_once_with(('LEFT', 'RIGHT'))
+
+    def test_ambiguous_text_and_signature(self):
+        self.assertEqual(parse_side('本场押红'), 'LEFT')
+        self.assertIsNone(parse_side('不押红,押蓝'))
+        self.assertIsNone(parse_side('押红还是押蓝'))
+        self.assertTrue(same_lineup('0' * 512, '1' * 10 + '0' * 502))
+        self.assertFalse(same_lineup('0' * 512, '1' * 512))
+
+    def test_invalid_api_responses_do_not_block_other_sources(self):
+        now = datetime(2026, 10, 1, 11, 45)
+        valid_feed = {'result': {'feed': {
+            'content': {'body': {'text': '本场押红'}},
+            'createTime': (now - timedelta(minutes=5)).timestamp() * 1000,
+        }}}
+        invalid_responses = [None, [], 'invalid', {}, {'result': None},
+                             {'result': []}, {'result': {'feeds': {}}},
+                             {'result': {'feeds': [None]}},
+                             {'result': {'feeds': [{'id': None}]}},
+                             {'result': {'feed': None}}]
+
+        def response(payload):
+            return Mock(json=Mock(return_value=payload))
+
+        for endpoint in ('listing', 'detail'):
+            for invalid in invalid_responses:
+                with self.subTest(endpoint=endpoint, payload=invalid):
+                    with tempfile.TemporaryDirectory() as directory:
+                        store = OasHistory(Path(directory) / 'history.jsonl')
+                        responses = []
+                        if endpoint == 'detail':
+                            responses.append(response({'result': {'feeds': [{'id': 'bad'}]}}))
+                        responses.extend([
+                            response(invalid),
+                            response({'result': {'feeds': [{'id': 'good'}]}}),
+                            response(valid_feed),
+                        ])
+                        with patch('tasks.FrogBoss.frog_oas.DASHEN_UIDS', ['bad', 'good']), \
+                                patch('tasks.FrogBoss.frog_oas.requests.Session') as session, \
+                                patch('tasks.FrogBoss.frog_oas.datetime') as clock:
+                            clock.now.return_value = now
+                            clock.fromtimestamp.side_effect = datetime.fromtimestamp
+                            session.return_value.__enter__.return_value.get.side_effect = responses
+
+                            predictions = fetch_predictions(store)
+
+                        self.assertEqual(predictions, [{'uid': 'good', 'side': 'LEFT', 'feed_id': 'good'}])
+                        self.assertFalse(store.events[0]['accepted'])
+                        self.assertEqual(store.events[-1]['uid'], 'good')
+
+
+if __name__ == '__main__':
+    unittest.main()

+ 6 - 0
tasks/GameUi/page.py

@@ -209,6 +209,12 @@ page_dokan = Page(DokanAssets.I_RYOU_DOKAN_CHECK)
 page_dokan.additional = [GeneralBattleAssets.I_EXIT, DokanAssets.I_RYOU_DOKAN_EXIT_ENSURE, G.I_BACK_BLUE]
 page_dokan.additional = [GeneralBattleAssets.I_EXIT, DokanAssets.I_RYOU_DOKAN_EXIT_ENSURE, G.I_BACK_BLUE]
 page_dokan.link(button=G.I_BACK_Y, destination=page_main)
 page_dokan.link(button=G.I_BACK_Y, destination=page_main)
 
 
+# 摸鱼行动页面
+from tasks.WeeklyTrifles.assets import WeeklyTriflesAssets
+page_touch_fish = Page(WeeklyTriflesAssets.I_CHECK_TOUCH_FISH)
+page_guild.link(button=WeeklyTriflesAssets.I_GUILD_GOTO_TF,destination=page_touch_fish)
+page_touch_fish.link(button=WeeklyTriflesAssets.I_WT_TF_GOTO_MAIN,destination=page_main)
+
 
 
 # ************************************* 战斗部分 *****************************************#
 # ************************************* 战斗部分 *****************************************#
 # 战斗界面
 # 战斗界面

BIN
tasks/GameUi/page/page_main_goto_summon.png


+ 5 - 2
tasks/RichMan/assets.py

@@ -150,6 +150,11 @@ class RichManAssets:
 	I_ME_CHECK_SOULS = RuleImage(roi_front=(611,225,100,100), roi_back=(507,199,272,175), threshold=0.8, method="Template matching", file="./tasks/RichMan/mall/medal/medal_me_check_souls.png")
 	I_ME_CHECK_SOULS = RuleImage(roi_front=(611,225,100,100), roi_back=(507,199,272,175), threshold=0.8, method="Template matching", file="./tasks/RichMan/mall/medal/medal_me_check_souls.png")
 
 
 
 
+	# Ocr Rule Assets
+	# Count sold-out labels in medal shop page
+	O_SOLD_OUT = RuleOcr(roi=(0,100,1280,500), area=(0,100,1280,500), mode="Full", method="Default", keyword="售", name="sold_out")
+
+
 	# Image Rule Assets
 	# Image Rule Assets
 	# 寄售屋 
 	# 寄售屋 
 	I_MALL_CONSIGNMENT = RuleImage(roi_front=(207,639,56,59), roi_back=(175,610,120,103), threshold=0.8, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_mall_consignment.png")
 	I_MALL_CONSIGNMENT = RuleImage(roi_front=(207,639,56,59), roi_back=(175,610,120,103), threshold=0.8, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_mall_consignment.png")
@@ -424,5 +429,3 @@ class RichManAssets:
 	O_TT_BUY = RuleOcr(roi=(602,509,104,61), area=(602,509,104,61), mode="Full", method="Default", keyword="", name="tt_buy")
 	O_TT_BUY = RuleOcr(roi=(602,509,104,61), area=(602,509,104,61), mode="Full", method="Default", keyword="", name="tt_buy")
 	# Ocr-description 
 	# Ocr-description 
 	O_TT_NUMBER = RuleOcr(roi=(576,415,58,49), area=(576,415,58,49), mode="Digit", method="Default", keyword="", name="tt_number")
 	O_TT_NUMBER = RuleOcr(roi=(576,415,58,49), area=(576,415,58,49), mode="Digit", method="Default", keyword="", name="tt_number")
-
-

+ 77 - 18
tasks/RichMan/mall/medal.py

@@ -23,43 +23,102 @@ class Medal(FriendshipPoints):
             return
             return
         self._enter_medal()
         self._enter_medal()
 
 
+        # 记录识别失败的商品,用于事后核对是否为售罄
+        not_found = []
+
         # 黑蛋
         # 黑蛋
         if con.black_daruma:
         if con.black_daruma:
-            self.buy_mall_one(buy_button=self.I_ME_BLACK, buy_check=self.I_ME_CHECK_BLACK,
-                              money_ocr=self.O_MALL_RESOURCE_3, buy_money=480)
+            self.screenshot()
+            if self.appear(self.I_ME_BLACK):
+                self.buy_mall_one(buy_button=self.I_ME_BLACK, buy_check=self.I_ME_CHECK_BLACK,
+                                  money_ocr=self.O_MALL_RESOURCE_3, buy_money=480)
+            else:
+                not_found.append('black_daruma')
         # 蓝票
         # 蓝票
         if con.mystery_amulet:
         if con.mystery_amulet:
-            self.buy_mall_one(buy_button=self.I_ME_BLUE, buy_check=self.I_ME_CHECK_BLUE,
-                              money_ocr=self.O_MALL_RESOURCE_3, buy_money=180)
+            self.screenshot()
+            if self.appear(self.I_ME_BLUE):
+                self.buy_mall_one(buy_button=self.I_ME_BLUE, buy_check=self.I_ME_CHECK_BLUE,
+                                  money_ocr=self.O_MALL_RESOURCE_3, buy_money=180)
+            else:
+                not_found.append('mystery_amulet')
         # 体力100
         # 体力100
         if con.ap_100:
         if con.ap_100:
-            self.buy_mall_one(buy_button=self.I_ME_AP, buy_check=self.I_ME_CHECK_AP,
-                              money_ocr=self.O_MALL_RESOURCE_3, buy_money=120)
+            self.screenshot()
+            if self.appear(self.I_ME_AP):
+                self.buy_mall_one(buy_button=self.I_ME_AP, buy_check=self.I_ME_CHECK_AP,
+                                  money_ocr=self.O_MALL_RESOURCE_3, buy_money=120)
+            else:
+                not_found.append('ap_100')
         # 随机御魂
         # 随机御魂
         if con.random_soul:
         if con.random_soul:
-            self.buy_mall_one(buy_button=self.I_ME_SOULS, buy_check=self.I_ME_CHECK_SOULS,
-                              money_ocr=self.O_MALL_RESOURCE_3, buy_money=320)
+            self.screenshot()
+            if self.appear(self.I_ME_SOULS):
+                self.buy_mall_one(buy_button=self.I_ME_SOULS, buy_check=self.I_ME_CHECK_SOULS,
+                                  money_ocr=self.O_MALL_RESOURCE_3, buy_money=320)
+            else:
+                not_found.append('random_soul')
         # 两颗白蛋
         # 两颗白蛋
         if con.white_daruma:
         if con.white_daruma:
-            self.buy_mall_more(buy_button=self.I_ME_WHITE, remain_number=True, money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
-                               buy_number=2, buy_max=2, buy_money=100)
+            self.screenshot()
+            if self.appear(self.I_ME_WHITE):
+                self.buy_mall_more(buy_button=self.I_ME_WHITE, remain_number=True, money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
+                                   buy_number=2, buy_max=2, buy_money=100)
+            else:
+                not_found.append('white_daruma')
         # 十张挑战券
         # 十张挑战券
         if con.challenge_pass:
         if con.challenge_pass:
-            self.buy_mall_more(buy_button=self.I_ME_CHALLENGE_PASS, remain_number=True, money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
-                               buy_number=con.challenge_pass, buy_max=10, buy_money=30)
+            self.screenshot()
+            if self.appear(self.I_ME_CHALLENGE_PASS):
+                self.buy_mall_more(buy_button=self.I_ME_CHALLENGE_PASS, remain_number=True, money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
+                                   buy_number=con.challenge_pass, buy_max=10, buy_money=30)
+            else:
+                not_found.append('challenge_pass')
         # 红蛋
         # 红蛋
         if con.red_daruma:
         if con.red_daruma:
-            self.buy_mall_more(buy_button=self.I_ME_RED, remain_number=False,
-                               money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
-                               buy_number=con.red_daruma, buy_max=99, buy_money=30)
+            self.screenshot()
+            if self.appear(self.I_ME_RED):
+                self.buy_mall_more(buy_button=self.I_ME_RED, remain_number=False,
+                                   money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
+                                   buy_number=con.red_daruma, buy_max=99, buy_money=30)
+            else:
+                not_found.append('red_daruma')
         # 破碎的咒符
         # 破碎的咒符
         if con.broken_amulet:
         if con.broken_amulet:
-            self.buy_mall_more(buy_button=self.I_ME_BROKEN, remain_number=False,
-                               money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
-                               buy_number=con.broken_amulet, buy_max=99, buy_money=20)
+            self.screenshot()
+            if self.appear(self.I_ME_BROKEN):
+                self.buy_mall_more(buy_button=self.I_ME_BROKEN, remain_number=False,
+                                   money_ocr=self.I_MALL_RESOURCE_MEDAL.build_mall_resource_ocr(self.device.image),
+                                   buy_number=con.broken_amulet, buy_max=99, buy_money=20)
+            else:
+                not_found.append('broken_amulet')
+
+        # 有识别失败的商品:核对售罄数量,确认失败是否为"商品售罄"(正常情况),而非页面异常。
+        # 注意:页面上的售罄标签可能包含未配置购买的商品,因此用 >= 而非 ==,避免误报。
+        if not_found:
+            self.screenshot()
+            soldout_count = self.count_soldout()
+            if soldout_count >= len(not_found):
+                logger.info(f'Medal: {len(not_found)} item(s) not detected, sold out count is {soldout_count}, '
+                            f'the not-detected items are sold out, skip normally')
+            else:
+                logger.warning(f'Medal: {len(not_found)} item(s) not detected, but sold out count is only {soldout_count}, '
+                               f'some items may not be sold out, page may be abnormal, please check manually')
 
 
         time.sleep(1)
         time.sleep(1)
 
 
+    def count_soldout(self) -> int:
+        """
+        统计勋章商店页面中"售罄"标签的数量。
+        通过 OCR 检测商品区域内含"售"字的文本块(售罄标签),用于核对识别失败的商品是否均为售罄。
+        需要先调用 screenshot 保证 self.device.image 为最新画面。
+        :return: 售罄标签数量
+        """
+        results = self.O_SOLD_OUT.detect_and_ocr(self.device.image, logDisplay=False)
+        count = sum(1 for r in results if '售' in r.ocr_text)
+        logger.info(f'Medal sold out count: {count}')
+        return count
+
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     from module.config.config import Config
     from module.config.config import Config

+ 11 - 0
tasks/RichMan/mall/medal/ocr.json

@@ -0,0 +1,11 @@
+[
+  {
+    "itemName": "sold_out",
+    "roiFront": "0,100,1280,500",
+    "roiBack": "0,100,1280,500",
+    "mode": "Full",
+    "method": "Default",
+    "keyword": "售",
+    "description": "Count sold-out labels in medal shop page"
+  }
+]

+ 3 - 2
tasks/RichMan/mall/navbar.py

@@ -74,7 +74,7 @@ class MallNavbar(GameUi, RichManAssets):
         :return:
         :return:
         """
         """
         self._enter_sundry()
         self._enter_sundry()
-        self.ui_click(self.I_SIDE_SURE_MEDAL, self.I_SIDE_CHECK_MEDAL)
+        self.ui_click(self.I_SIDE_SURE_MEDAL, self.I_SIDE_CHECK_MEDAL, interval=3, timeout=15)
 
 
     def _enter_charisma(self):
     def _enter_charisma(self):
         """
         """
@@ -89,7 +89,8 @@ class MallNavbar(GameUi, RichManAssets):
         返回商城
         返回商城
         :return:
         :return:
         """
         """
-        self.ui_click(self.I_UI_BACK_YELLOW, self.I_CHECK_MALL)
+        self.ui_click(self.I_UI_BACK_YELLOW, self.I_CHECK_MALL, interval=3, timeout=6)
+
 
 
     def mall_resource(self, index: int) -> int:
     def mall_resource(self, index: int) -> int:
         """
         """

+ 28 - 0
tasks/WeeklyTrifles/assets.py

@@ -79,3 +79,31 @@ class WeeklyTriflesAssets:
 	I_WT_SE_RANK = RuleImage(roi_front=(1017,572,45,44), roi_back=(989,556,103,81), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/secret/secret_wt_se_rank.png")
 	I_WT_SE_RANK = RuleImage(roi_front=(1017,572,45,44), roi_back=(989,556,103,81), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/secret/secret_wt_se_rank.png")
 
 
 
 
+	# Image Rule Assets
+	# 前往摸鱼页面
+	I_GUILD_GOTO_TF = RuleImage(roi_front=(30,433,88,30), roi_back=(7,153,227,329), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_guild_goto_tf.png")
+	# 关闭首次进入弹窗
+	I_WT_HAPPY_GET = RuleImage(roi_front=(736,461,119,35), roi_back=(736,461,119,35), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_happy_get.png")
+	# 全部保存本周次数
+	I_WT_SAVE_ALL = RuleImage(roi_front=(1115,598,79,74), roi_back=(1115,598,79,74), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_save_all.png")
+	# 摸鱼行动页面标志
+	I_CHECK_TOUCH_FISH = RuleImage(roi_front=(1082,20,27,27), roi_back=(1082,20,27,27), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_check_touch_fish.png")
+	# 返回庭院
+	I_WT_TF_GOTO_MAIN = RuleImage(roi_front=(93,17,42,39), roi_back=(0,0,198,82), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_goto_main.png")
+	# 打开折叠窗口
+	I_WT_OPEN_FOLD_WINDOW = RuleImage(roi_front=(28,155,21,21), roi_back=(28,155,21,21), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_open_fold_window.png")
+	# 已经打开的折叠窗口
+	I_WT_FOLD_WINDOW = RuleImage(roi_front=(261,155,21,21), roi_back=(261,155,21,21), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_fold_window.png")
+	# 确认储存的按钮
+	I_WT_TF_CONFIRM = RuleImage(roi_front=(672,588,139,56), roi_back=(672,588,139,56), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_confirm.png")
+	# 储存成功的标志
+	I_WT_TF_SAVE_SUCCESS = RuleImage(roi_front=(942,243,62,25), roi_back=(871,212,219,70), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_save_success.png")
+	# 上周存储界面
+	I_WT_LAST_SAVE = RuleImage(roi_front=(590,78,99,24), roi_back=(540,58,213,59), threshold=0.8, method="Template matching", file="./tasks/WeeklyTrifles/touch_fish/touch_fish_wt_last_save.png")
+
+
+	# Ocr Rule Assets
+	# 现有福运御守数量
+	O_WT_LUCKY_TICKETS = RuleOcr(roi=(1145,16,95,32), area=(1145,16,95,32), mode="DigitCounter", method="Default", keyword="", name="wt_lucky_tickets")
+	# 全部储存需要的御守数量
+	O_WT_SAVE_COST = RuleOcr(roi=(1162,676,35,24), area=(1156,670,52,40), mode="Digit", method="Default", keyword="", name="wt_save_cost")

+ 12 - 4
tasks/WeeklyTrifles/config.py

@@ -7,18 +7,26 @@ from pydantic import BaseModel, Field
 from tasks.Component.config_scheduler import Scheduler as BaseScheduler
 from tasks.Component.config_scheduler import Scheduler as BaseScheduler
 from tasks.Component.config_base import ConfigBase, TimeDelta
 from tasks.Component.config_base import ConfigBase, TimeDelta
 
 
+
 class Scheduler(BaseScheduler):
 class Scheduler(BaseScheduler):
-    success_interval: TimeDelta = Field(default=TimeDelta(days=7), description='success_interval_help')
-    failure_interval: TimeDelta = Field(default=TimeDelta(days=7), description='failure_interval_help')
+    success_interval: TimeDelta = Field(
+        default=TimeDelta(days=7), description='success_interval_help'
+    )
+    failure_interval: TimeDelta = Field(
+        default=TimeDelta(days=7), description='failure_interval_help'
+    )
+
 
 
 class Trifles(BaseModel):
 class Trifles(BaseModel):
     share_collect: bool = Field(default=True, description='share_collect_help')
     share_collect: bool = Field(default=True, description='share_collect_help')
     share_area_boss: bool = Field(default=True, description='share_area_boss_help')
     share_area_boss: bool = Field(default=True, description='share_area_boss_help')
     share_secret: bool = Field(default=True, description='share_secret_help')
     share_secret: bool = Field(default=True, description='share_secret_help')
-    broken_amulet: int = Field(title='Broken Amulet', default=100, description='trifles_broken_amulet_help')
+    save_touch_fish: bool = Field(default=False, description='save_touch_fish_help')
+    broken_amulet: int = Field(
+        title='Broken Amulet', default=100, description='trifles_broken_amulet_help'
+    )
 
 
 
 
 class WeeklyTrifles(ConfigBase):
 class WeeklyTrifles(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     scheduler: Scheduler = Field(default_factory=Scheduler)
     trifles: Trifles = Field(default_factory=Trifles)
     trifles: Trifles = Field(default_factory=Trifles)
-

+ 101 - 14
tasks/WeeklyTrifles/script_task.py

@@ -4,15 +4,24 @@
 import time
 import time
 from time import sleep
 from time import sleep
 
 
-from module.exception import TaskEnd
+from module.exception import GameStuckError, TaskEnd
 from module.logger import logger
 from module.logger import logger
 from module.base.timer import Timer
 from module.base.timer import Timer
 
 
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.game_ui import GameUi
-from tasks.GameUi.page import page_main, page_collection, page_area_boss, page_secret_zones, page_summon, random_click
-from tasks.WeeklyTrifles.config import Trifles
+from tasks.GameUi.page import (
+    page_main,
+    page_collection,
+    page_area_boss,
+    page_secret_zones,
+    page_summon,
+    page_guild,
+    page_touch_fish,
+    random_click,
+)
 from tasks.WeeklyTrifles.assets import WeeklyTriflesAssets
 from tasks.WeeklyTrifles.assets import WeeklyTriflesAssets
 
 
+
 class ScriptTask(GameUi, WeeklyTriflesAssets):
 class ScriptTask(GameUi, WeeklyTriflesAssets):
 
 
     def run(self):
     def run(self):
@@ -23,13 +32,14 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
             self._share_area_boss()
             self._share_area_boss()
         if con.share_secret:
         if con.share_secret:
             self._share_secret()
             self._share_secret()
+        if con.save_touch_fish:
+            self._save_touch_fish()
         if con.broken_amulet:
         if con.broken_amulet:
             self._broken_amulet(con.broken_amulet)
             self._broken_amulet(con.broken_amulet)
 
 
         self.set_next_run(task='WeeklyTrifles', success=True, finish=True)
         self.set_next_run(task='WeeklyTrifles', success=True, finish=True)
         raise TaskEnd('WeeklyTrifles')
         raise TaskEnd('WeeklyTrifles')
 
 
-
     def click_share(self, wechat) -> bool:
     def click_share(self, wechat) -> bool:
         """
         """
         点击分享
         点击分享
@@ -52,12 +62,69 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
             if self.ui_reward_appear_click():
             if self.ui_reward_appear_click():
                 logger.info('Get reward')
                 logger.info('Get reward')
                 return True
                 return True
-            if self.appear_then_click(self.I_WT_QR_CODE, self.C_WT_WECHAT, interval=4.8):
+            if self.appear_then_click(
+                self.I_WT_QR_CODE, self.C_WT_WECHAT, interval=4.8
+            ):
                 continue
                 continue
             if get_timer.reached():
             if get_timer.reached():
                 logger.warning('Share timeout. The reward may have been obtained')
                 logger.warning('Share timeout. The reward may have been obtained')
                 return False
                 return False
 
 
+    def _save_touch_fish(self):
+        """
+        惠比寿的摸鱼行动
+        :return:
+        """
+        logger.hr('Touch fish start')
+        self.ui_get_current_page()
+        self.ui_goto(page_guild)
+        # 防止入口被折叠
+        unfold_timer = Timer(10).start()
+        while not unfold_timer.reached():
+            # 等个折叠窗口展开动画
+            sleep(1)
+            self.screenshot()
+            if self.appear_then_click(self.I_WT_OPEN_FOLD_WINDOW):
+                continue
+            if self.appear(self.I_WT_FOLD_WINDOW):
+                break
+        else:
+            raise GameStuckError('Touch fish guild menu did not open')
+        # 保存次数,后续做了也会邮件返还福运御守
+        self.ui_goto(page_touch_fish)
+        save_requested = False
+        get_timer = Timer(20).start()
+        while not get_timer.reached():
+            sleep(0.5)
+            self.screenshot()
+            # 弹窗可能遮住保存按钮,先关闭弹窗再读取主页上的御守数量。
+            if self.appear(self.I_WT_LAST_SAVE):
+                self.click(
+                    random_click(ltrb=(True, False, False, False)), interval=1.5
+                )
+                continue
+            if self.appear_then_click(self.I_WT_HAPPY_GET, interval=1):
+                continue
+            if self.appear_then_click(self.I_WT_TF_CONFIRM, interval=1):
+                continue
+            save_available = self.appear(self.I_WT_SAVE_ALL)
+            if self.appear(self.I_WT_TF_SAVE_SUCCESS) and not save_available:
+                logger.info('Touch fish save success')
+                break
+            if save_available and not save_requested:
+                cu_tickts, _, _ = self.O_WT_LUCKY_TICKETS.ocr(self.device.image)
+                logger.info(f"当前的福运御守数量:{cu_tickts}")
+                cost_tickts = self.O_WT_SAVE_COST.ocr(self.device.image)
+                logger.info(f"全部存储需要花费的福运御守数量:{cost_tickts}")
+                if cu_tickts < cost_tickts:
+                    logger.warning('Touch fish tickts not enough, exit!')
+                    break
+                save_requested = self.appear_then_click(self.I_WT_SAVE_ALL, interval=1)
+        else:
+            raise GameStuckError('Touch fish save did not complete before timeout')
+        logger.hr('Touch fish finished')
+        self.ui_goto(page_main)
+
     def _share_collect(self):
     def _share_collect(self):
         """
         """
         图鉴分享
         图鉴分享
@@ -92,7 +159,9 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
                 logger.info('Get reward')
                 logger.info('Get reward')
                 break
                 break
 
 
-            if self.appear_then_click(self.I_WT_QR_CODE, self.C_WT_WECHAT, interval=2.8):
+            if self.appear_then_click(
+                self.I_WT_QR_CODE, self.C_WT_WECHAT, interval=2.8
+            ):
                 continue
                 continue
             if get_timer.reached():
             if get_timer.reached():
                 logger.warning('Share timeout. The reward may have been obtained')
                 logger.warning('Share timeout. The reward may have been obtained')
@@ -112,10 +181,13 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
         地鬼分享
         地鬼分享
         :return:
         :return:
         """
         """
+
         def back_boss():
         def back_boss():
             while 1:
             while 1:
                 self.screenshot()
                 self.screenshot()
-                if self.appear(self.I_WT_DAY_BATTLE) or self.appear(self.I_CHECK_EXPLORATION):
+                if self.appear(self.I_WT_DAY_BATTLE) or self.appear(
+                    self.I_CHECK_EXPLORATION
+                ):
                     break
                     break
                 if self.appear_then_click(self.I_UI_BACK_RED, interval=1):
                 if self.appear_then_click(self.I_UI_BACK_RED, interval=1):
                     continue
                     continue
@@ -124,6 +196,7 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
                 if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=1):
                 if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=1):
                     continue
                     continue
             logger.info('Back to boss')
             logger.info('Back to boss')
+
         logger.hr('Share area boss')
         logger.hr('Share area boss')
         self.ui_get_current_page()
         self.ui_get_current_page()
         self.ui_goto(page_area_boss)
         self.ui_goto(page_area_boss)
@@ -205,6 +278,7 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
         :param dest_num:
         :param dest_num:
         :return:
         :return:
         """
         """
+
         def exit_amulet():
         def exit_amulet():
             self.wait_until_appear(self.I_BM_CONFIRM, wait_time=3)
             self.wait_until_appear(self.I_BM_CONFIRM, wait_time=3)
             while 1:
             while 1:
@@ -233,7 +307,9 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
             if real_num <= 0:
             if real_num <= 0:
                 exit_amulet()
                 exit_amulet()
                 return
                 return
-            if self.appear_then_click(self.I_BM_ENTER, interval=1) or self.appear_then_click(self.I_BM_AGAIN, interval=1):
+            if self.appear_then_click(
+                self.I_BM_ENTER, interval=1
+            ) or self.appear_then_click(self.I_BM_AGAIN, interval=1):
                 sleep(0.4)  # 等待动画开始
                 sleep(0.4)  # 等待动画开始
                 timeout_timer = Timer(5).start()
                 timeout_timer = Timer(5).start()
                 # 随机点击直到再次召唤出现或者超时
                 # 随机点击直到再次召唤出现或者超时
@@ -244,7 +320,9 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
                     if self.appear(self.I_BM_AGAIN, interval=0.8):
                     if self.appear(self.I_BM_AGAIN, interval=0.8):
                         break
                         break
                 else:
                 else:
-                    logger.warning(f'Wait for again timeout:Count[{count}], Remain[{real_num}]')
+                    logger.warning(
+                        f'Wait for again timeout:Count[{count}], Remain[{real_num}]'
+                    )
                     exit_amulet()
                     exit_amulet()
                     return
                     return
             else:
             else:
@@ -255,19 +333,29 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
             x_50, _, _, _ = self.O_BA_TIMES.ocr(self.device.image, '50次')
             x_50, _, _, _ = self.O_BA_TIMES.ocr(self.device.image, '50次')
             self.I_BMT_CHECK.match(self.device.image)
             self.I_BMT_CHECK.match(self.device.image)
             x_check, y_check, width_check, height_check = self.I_BMT_CHECK.roi_front
             x_check, y_check, width_check, height_check = self.I_BMT_CHECK.roi_front
-            selected_10 = min(abs(x_10 - x_check), abs(x_50 - x_check)) == abs(x_10 - x_check)
+            selected_10 = min(abs(x_10 - x_check), abs(x_50 - x_check)) == abs(
+                x_10 - x_check
+            )
             logger.info(f'Current selected {"10" if selected_10 else "50"} amulet')
             logger.info(f'Current selected {"10" if selected_10 else "50"} amulet')
             count += 10 if selected_10 else 50
             count += 10 if selected_10 else 50
             logger.info(f'Broken amulet:Count[{count}], Remain[{real_num}]')
             logger.info(f'Broken amulet:Count[{count}], Remain[{real_num}]')
             # 一次50票不超过限制且当前选择的是10票则切换50票
             # 一次50票不超过限制且当前选择的是10票则切换50票
             if count + 50 < dest_num and selected_10:
             if count + 50 < dest_num and selected_10:
                 logger.hr('Switch to 50 amulet')
                 logger.hr('Switch to 50 amulet')
-                self.device.click(x=x_50 - width_check // 2, y=y_check + height_check // 2, control_name='Click_50')
+                self.device.click(
+                    x=x_50 - width_check // 2,
+                    y=y_check + height_check // 2,
+                    control_name='Click_50',
+                )
                 self.device.click_record_clear()
                 self.device.click_record_clear()
             # 一次50票会超过限制且当前选择的是50票则切换10票
             # 一次50票会超过限制且当前选择的是50票则切换10票
             if count + 50 >= dest_num and not selected_10:
             if count + 50 >= dest_num and not selected_10:
                 logger.hr('Switch to 10 amulet')
                 logger.hr('Switch to 10 amulet')
-                self.device.click(x=x_10 - width_check // 2, y=y_check + height_check // 2, control_name='Click_10')
+                self.device.click(
+                    x=x_10 - width_check // 2,
+                    y=y_check + height_check // 2,
+                    control_name='Click_10',
+                )
                 self.device.click_record_clear()
                 self.device.click_record_clear()
         # 正常结束且还有票, 则执行一次退出
         # 正常结束且还有票, 则执行一次退出
         exit_amulet()
         exit_amulet()
@@ -276,6 +364,7 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
 if __name__ == '__main__':
 if __name__ == '__main__':
     from module.config.config import Config
     from module.config.config import Config
     from module.device.device import Device
     from module.device.device import Device
+
     c = Config('oas1')
     c = Config('oas1')
     d = Device(c)
     d = Device(c)
     t = ScriptTask(c, d)
     t = ScriptTask(c, d)
@@ -284,5 +373,3 @@ if __name__ == '__main__':
     # t._share_collect()
     # t._share_collect()
     t._share_area_boss()
     t._share_area_boss()
     # t.click_share(t.I_WT_SE_WECHAT)
     # t.click_share(t.I_WT_SE_WECHAT)
-
-

+ 92 - 0
tasks/WeeklyTrifles/touch_fish/image.json

@@ -0,0 +1,92 @@
+[
+  {
+    "itemName": "guild_goto_tf",
+    "imageName": "touch_fish_guild_goto_tf.png",
+    "roiFront": "30,433,88,30",
+    "roiBack": "7,153,227,329",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "前往摸鱼页面"
+  },
+  {
+    "itemName": "wt_happy_get",
+    "imageName": "touch_fish_wt_happy_get.png",
+    "roiFront": "736,461,119,35",
+    "roiBack": "736,461,119,35",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "关闭首次进入弹窗"
+  },
+  {
+    "itemName": "wt_save_all",
+    "imageName": "touch_fish_wt_save_all.png",
+    "roiFront": "1115,598,79,74",
+    "roiBack": "1115,598,79,74",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "全部保存本周次数"
+  },
+  {
+    "itemName": "check_touch_fish",
+    "imageName": "touch_fish_check_touch_fish.png",
+    "roiFront": "1082,20,27,27",
+    "roiBack": "1082,20,27,27",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "摸鱼行动页面标志"
+  },
+  {
+    "itemName": "wt_tf_goto_main",
+    "imageName": "touch_fish_wt_tf_goto_main.png",
+    "roiFront": "93,17,42,39",
+    "roiBack": "0,0,198,82",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "返回庭院"
+  },
+  {
+    "itemName": "wt_open_fold_window",
+    "imageName": "touch_fish_wt_open_fold_window.png",
+    "roiFront": "28,155,21,21",
+    "roiBack": "28,155,21,21",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "打开折叠窗口"
+  },
+  {
+    "itemName": "wt_fold_window",
+    "imageName": "touch_fish_wt_fold_window.png",
+    "roiFront": "261,155,21,21",
+    "roiBack": "261,155,21,21",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "已经打开的折叠窗口"
+  },
+  {
+    "itemName": "wt_tf_confirm",
+    "imageName": "touch_fish_wt_tf_confirm.png",
+    "roiFront": "672,588,139,56",
+    "roiBack": "672,588,139,56",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "确认储存的按钮"
+  },
+  {
+    "itemName": "wt_tf_save_success",
+    "imageName": "touch_fish_wt_tf_save_success.png",
+    "roiFront": "942,243,62,25",
+    "roiBack": "871,212,219,70",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "储存成功的标志"
+  },
+  {
+    "itemName": "wt_last_save",
+    "imageName": "touch_fish_wt_last_save.png",
+    "roiFront": "590,78,99,24",
+    "roiBack": "540,58,213,59",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "上周存储界面"
+  }
+]

+ 20 - 0
tasks/WeeklyTrifles/touch_fish/ocr.json

@@ -0,0 +1,20 @@
+[
+  {
+    "itemName": "wt_lucky_tickets",
+    "roiFront": "1145,16,95,32",
+    "roiBack": "1145,16,95,32",
+    "mode": "DigitCounter",
+    "method": "Default",
+    "keyword": "",
+    "description": "现有福运御守数量"
+  },
+  {
+    "itemName": "wt_save_cost",
+    "roiFront": "1162,676,35,24",
+    "roiBack": "1156,670,52,40",
+    "mode": "Digit",
+    "method": "Default",
+    "keyword": "",
+    "description": "全部储存需要的御守数量"
+  }
+]

BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_check_touch_fish.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_guild_goto_tf.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_fold_window.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_happy_get.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_last_save.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_open_fold_window.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_save_all.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_confirm.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_goto_main.png


BIN
tasks/WeeklyTrifles/touch_fish/touch_fish_wt_tf_save_success.png


+ 3 - 3
tasks/base_task.py

@@ -283,7 +283,7 @@ class BaseTask(GlobalGameAssets, CostumeBase):
         return appear
         return appear
 
 
     def wait_until_appear(self,
     def wait_until_appear(self,
-                          target: RuleImage | RuleOcr,
+                          target: RuleImage | RuleGif | RuleOcr,
                           skip_first_screenshot=False,
                           skip_first_screenshot=False,
                           wait_time: int = None) -> bool:
                           wait_time: int = None) -> bool:
         """
         """
@@ -305,13 +305,13 @@ class BaseTask(GlobalGameAssets, CostumeBase):
             if wait_timer and wait_timer.reached():
             if wait_timer and wait_timer.reached():
                 logger.warning(f"Wait until appear {target.name} timeout")
                 logger.warning(f"Wait until appear {target.name} timeout")
                 return False
                 return False
-            if isinstance(target, RuleImage) and self.appear(target):
+            if isinstance(target, (RuleImage, RuleGif)) and self.appear(target):
                 return True
                 return True
             if isinstance(target, RuleOcr) and self.ocr_appear(target):
             if isinstance(target, RuleOcr) and self.ocr_appear(target):
                 return True
                 return True
 
 
     def wait_until_appear_then_click(self,
     def wait_until_appear_then_click(self,
-                                     target: RuleImage,
+                                     target: RuleImage | RuleGif,
                                      action: Union[RuleClick, RuleLongClick] = None,
                                      action: Union[RuleClick, RuleLongClick] = None,
                                      wait_time: int = None) -> bool:
                                      wait_time: int = None) -> bool:
         """
         """

+ 91 - 0
tests/tasks/ActivityShikigami/test_battle_integration.py

@@ -0,0 +1,91 @@
+from types import SimpleNamespace
+
+import pytest
+
+from tasks.ActivityShikigami.config import ActivityShikigami
+from tasks.ActivityShikigami.script_task import ScriptTask
+from tasks.Component.GeneralBattle.battle import Battle
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy, runtime
+
+
+@pytest.fixture(autouse=True)
+def isolated_runtime(monkeypatch):
+    monkeypatch.setattr(runtime, 'task_owner', None)
+    monkeypatch.setattr(runtime, 'pub_ctx', None)
+    monkeypatch.setattr(runtime, 'pri_ctx', {})
+    monkeypatch.setattr('tasks.Component.GeneralBattle.battle_wait.random.random', lambda: 1)
+
+
+class ActivityReplay(ScriptTask):
+    """Exercise the real activity entry point and battle hooks without a device."""
+
+    def __init__(self):
+        self.conf = ActivityShikigami()
+        self.conf.general_climb.run_sequence = 'pass,ap'
+        self.run_idx = 0
+        self.frames = 0
+        self.result_visible = True
+        self.win = True
+        self.clicks = []
+        self.device = SimpleNamespace(
+            stuck_record_add=lambda name: None,
+            click_record_clear=lambda: None,
+        )
+
+    def screenshot(self):
+        self.frames += 1
+        assert self.frames < 40, 'Activity battle did not settle'
+
+    def is_in_battle(self, is_screenshot=True):
+        return True
+
+    def is_in_real_battle(self, is_screenshot=True):
+        return False
+
+    def appear(self, asset, **kwargs):
+        result = self.I_UI_REWARD if self.win else self.I_FALSE
+        return self.result_visible and asset is result
+
+    def appear_then_click(self, asset, **kwargs):
+        return False
+
+    def click(self, asset, **kwargs):
+        self.clicks.append(asset.name)
+        self.result_visible = False
+
+    def ui_click_until_disappear(self, asset, **kwargs):
+        self.click(asset)
+
+    def loadout_show(self, *args):
+        pass
+
+    def state_show(self):
+        pass
+
+
+@pytest.mark.parametrize('win', [True, False])
+def test_activity_entry_uses_its_reward_strategy_and_counts_success_only(win):
+    task = ActivityReplay()
+    task.win = win
+    # Decorating another task later must not replace Activity's selected hooks.
+    battle_wait_strategy(success='default')(lambda owner, **kwargs: None)
+
+    assert ScriptTask.battle_wait is Battle.battle_wait
+    assert task.start_battle() is win
+    assert task.count_map == {'pass': int(win), 'ap': 0}
+    assert task.battle_count_reached(1)
+    assert task.clicks == ['exclude_click_activity' if win else task.I_FALSE.name]
+    assert battle_wait_strategy._context.get() is None
+
+
+def test_switching_climb_type_preserves_counts_and_resets_battle_state():
+    task = ActivityReplay()
+    assert task.start_battle() is True
+    assert task.switch_next() is True
+    assert task.count_map == {'pass': 1, 'ap': 0}
+    assert not task.battle_count_reached(1)
+
+    task.result_visible = True
+    assert task.start_battle() is True
+    assert task.count_map == {'pass': 1, 'ap': 1}
+    assert task.switch_next() is False

+ 56 - 0
tests/tasks/Component/Costume/test_costume.py

@@ -0,0 +1,56 @@
+from copy import deepcopy
+from types import SimpleNamespace
+
+import numpy as np
+import pytest
+
+from module.atom.image import RuleImage
+from tasks.Component.Costume import costume_base
+from tasks.Component.Costume.assets import CostumeAssets
+from tasks.Component.Costume.config import MainType
+
+
+def screenshot_for(asset):
+    image = asset.image
+    x, y = asset.roi_front[:2]
+    height, width = image.shape[:2]
+    screenshot = np.zeros((720, 1280, 3), dtype=np.uint8)
+    screenshot[y:y + height, x:x + width] = image
+    return screenshot
+
+
+@pytest.mark.parametrize('animated_type', [MainType.COSTUME_MAIN_13, MainType.COSTUME_MAIN_17])
+def test_switch_animated_to_static_and_back_preserves_shared_reference(monkeypatch, animated_type):
+    # Match real costume templates without mutating the process-wide asset objects.
+    assets = SimpleNamespace(**{
+        name: deepcopy(value)
+        for name, value in vars(CostumeAssets).items()
+        if isinstance(value, RuleImage)
+    })
+    monkeypatch.setattr(costume_base, 'CostumeAssets', lambda: assets)
+    host = costume_base.CostumeBase()
+    host.I_CHECK_MAIN = deepcopy(assets.I_CHECK_MAIN_2)
+    page_reference = host.I_CHECK_MAIN
+
+    # Prime the static image cache before changing to a GIF costume.
+    assert page_reference.match(screenshot_for(assets.I_CHECK_MAIN_2))
+    host.check_costume_main(animated_type)
+    frame_names = costume_base.main_costume_model[animated_type]['I_CHECK_MAIN']
+    animated_screen = screenshot_for(getattr(assets, frame_names[-1]))
+    assert page_reference.match(animated_screen)
+
+    host.check_costume_main(MainType.COSTUME_MAIN_1)
+    assert host.I_CHECK_MAIN is page_reference
+    assert page_reference.match(screenshot_for(assets.I_CHECK_MAIN_1))
+    assert not page_reference.match(animated_screen)
+    assert not hasattr(page_reference, 'targets')
+    assert page_reference.name == assets.I_CHECK_MAIN_1.name
+
+    # A second static costume must not reuse the first static template's cache.
+    host.check_costume_main(MainType.COSTUME_MAIN_2)
+    assert page_reference.match(screenshot_for(assets.I_CHECK_MAIN_2))
+
+    host.check_costume_main(animated_type)
+    assert host.I_CHECK_MAIN is page_reference
+    assert page_reference.match(animated_screen)
+    assert page_reference.name == getattr(assets, frame_names[0]).name

+ 323 - 250
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -1,45 +1,63 @@
+from contextvars import copy_context
+from types import SimpleNamespace
+
 import pytest
 import pytest
 
 
 from tasks.Component.GeneralBattle.battle_wait import (
 from tasks.Component.GeneralBattle.battle_wait import (
+    BattleResult,
     BattleWait,
     BattleWait,
     BattleWaitPlan,
     BattleWaitPlan,
     HookSignal,
     HookSignal,
+    OptionCompletionDefault,
+    OptionPrepareDefault,
+    OptionSetupDefault,
+    OptionSuccessDefault,
+    PerBattlePrepare,
+    PerBattleState,
+    PerTaskPreset,
+    PerTaskState,
+    battle_wait_options,
     battle_wait_strategy,
     battle_wait_strategy,
+    runtime,
+    _OPTION_CLASSES,
 )
 )
 
 
 
 
 @pytest.fixture(autouse=True)
 @pytest.fixture(autouse=True)
 def reset_battle_wait_plan(monkeypatch):
 def reset_battle_wait_plan(monkeypatch):
-    monkeypatch.setattr(battle_wait_strategy, 'options', None)
-    token = battle_wait_strategy._context.set(None)
+    monkeypatch.setattr(battle_wait_options, 'options', {
+        event: cls() for event, cls in _OPTION_CLASSES.items()
+    })
+    monkeypatch.setattr(runtime, 'task_owner', None)
+    monkeypatch.setattr(runtime, 'pub_ctx', None)
+    monkeypatch.setattr(runtime, 'pri_ctx', {})
+    contexts = (
+        battle_wait_strategy._context,
+        battle_wait_options._context,
+        battle_wait_options._decorator_options,
+    )
+    tokens = [context.set(None) for context in contexts]
     yield
     yield
-    battle_wait_strategy._context.reset(token)
+    for context, token in zip(contexts, tokens):
+        context.reset(token)
+
+
+def capture(owner, *, battle_wait_plan, options):
+    return battle_wait_plan, options
 
 
 
 
 def test_default_plan_contains_default_hooks_and_sequence():
 def test_default_plan_contains_default_hooks_and_sequence():
     plan = BattleWaitPlan()
     plan = BattleWaitPlan()
-
-    assert tuple(getattr(plan, hook) for hook in BattleWaitPlan.HOOKS_DEFAULT) == (
-        'default',
-        'default',
-        'default',
-        'default',
-        'default',
-        'default',
+    assert all(getattr(plan, hook) == 'default' for hook in plan.HOOKS_DEFAULT)
+    assert plan.sequence == (
+        'completion>interrupt>prepare>preset>green>red>echo>success>failure>idle'
     )
     )
-    assert plan.sequence == 'completion>interrupt>success>failure>idle'
     assert plan.function_setup_name == '_bw_setup_default'
     assert plan.function_setup_name == '_bw_setup_default'
 
 
 
 
 def test_decorator_passes_its_plan_to_the_wrapped_function():
 def test_decorator_passes_its_plan_to_the_wrapped_function():
     strategy = battle_wait_strategy('reserve_default', 'idle_default', failure='custom')
     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())
-
+    plan, _ = strategy(capture)(object())
     assert plan.reserve == 'default'
     assert plan.reserve == 'default'
     assert plan.idle == 'default'
     assert plan.idle == 'default'
     assert plan.failure == 'custom'
     assert plan.failure == 'custom'
@@ -47,297 +65,352 @@ def test_decorator_passes_its_plan_to_the_wrapped_function():
 
 
 def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
 def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
     strategy = battle_wait_strategy('success_default')
     strategy = battle_wait_strategy('success_default')
-
-    @strategy
-    def battle_wait(owner, *, battle_wait_plan):
-        return battle_wait_plan
-
-    default_plan = strategy.battle_wait_plan
-
+    wait = strategy(capture)
     with battle_wait_strategy('success_default', failure='custom'):
     with battle_wait_strategy('success_default', failure='custom'):
-        temporary_plan = battle_wait(object())
-        assert temporary_plan.failure == 'custom'
-
+        assert wait(object())[0].failure == 'custom'
     assert battle_wait_strategy._context.get() is None
     assert battle_wait_strategy._context.get() is None
-    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',
-    ]
+    assert wait(object())[0] is strategy.battle_wait_plan
 
 
 
 
 @pytest.mark.parametrize('strategies', [('default', 'activity'), ('activity', 'default')])
 @pytest.mark.parametrize('strategies', [('default', 'activity'), ('activity', 'default')])
 @pytest.mark.parametrize('random_click', [False, True])
 @pytest.mark.parametrize('random_click', [False, True])
 def test_task_strategies_are_independent_of_decoration_order(strategies, random_click):
 def test_task_strategies_are_independent_of_decoration_order(strategies, random_click):
-    def wait(owner, *, battle_wait_plan):
-        return battle_wait_plan
-
-    tasks = {
-        name: battle_wait_strategy(success=name)(wait)
-        for name in strategies
-    }
-
+    tasks = {name: battle_wait_strategy(success=name)(capture) for name in strategies}
     for name, wait in tasks.items():
     for name, wait in tasks.items():
-        plan = wait(object(), random_click_swipt_enable=random_click)
+        plan, _ = wait(object(), random_click_swipt_enable=random_click)
         assert plan.success == name
         assert plan.success == name
         assert hasattr(plan, 'randomclick') is random_click
         assert hasattr(plan, 'randomclick') is random_click
-
-    # A later call must still use the task's own strategy.
     for name, wait in tasks.items():
     for name, wait in tasks.items():
-        assert wait(object()).success == name
-
-
-def test_activity_reward_is_collected_after_another_task_is_decorated(monkeypatch):
-    from types import SimpleNamespace
-
-    @battle_wait_strategy()
-    def ordinary_wait(owner, *, battle_wait_plan):
-        return battle_wait_plan
-
-    class ActivityBattle(BattleWait):
-        def __init__(self):
-            self.reward_visible = True
-            self.frames = 0
-            self.clicks = []
-            self.device = SimpleNamespace(
-                stuck_record_add=lambda name: None,
-                click_record_clear=lambda: None,
-            )
+        assert wait(object())[0].success == name
 
 
-        def screenshot(self):
-            self.frames += 1
-            assert self.frames < 10, 'Activity reward was not collected'
-
-        def appear(self, asset, **kwargs):
-            return asset is self.I_UI_REWARD and self.reward_visible
 
 
-        def appear_then_click(self, asset, **kwargs):
-            return False
-
-        def click(self, asset, **kwargs):
-            self.clicks.append(asset.name)
-            self.reward_visible = False
-
-        @battle_wait_strategy(success='activity')
-        def battle_wait(self, *args, **kwargs):
-            return self.battle_wait_with_strategy(*args, **kwargs)
-
-    # Keep the replay on the normal dismissal path, without random item inspection.
-    monkeypatch.setattr('tasks.Component.GeneralBattle.battle_wait.random.random', lambda: 1)
-    task = ActivityBattle()
-
-    assert task.battle_wait(random_click_swipt_enable=False) is True
-    assert task.clicks == ['exclude_click_activity']
-    assert ordinary_wait(object()).success == 'default'
+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()[-3:-1] == ['_bw_yyy_default', '_bw_abcd_edf']
 
 
 
 
 def test_an_event_cannot_be_configured_with_two_strategies():
 def test_an_event_cannot_be_configured_with_two_strategies():
-    with pytest.raises(ValueError, match="configured more than once"):
+    with pytest.raises(ValueError, match='configured more than once'):
         BattleWaitPlan('success_default', success='custom')
         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')
-            bw_ctx.success = True
-            return HookSignal.DONE
+def test_custom_sequence_controls_hook_order():
+    sequence = 'failure>yyy>completion>interrupt>prepare>preset>green>red>echo>success>idle'
+    plan = BattleWaitPlan('yyy_default', sequence=sequence)
+    assert plan.sequence_function_names() == [f'_bw_{event}_default' for event in sequence.split('>')]
 
 
-    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_events_without_sequence_are_inserted_before_idle_in_argument_order():
+    plan = BattleWaitPlan('yyy_default', 'abcd_edf')
+    assert plan.sequence.endswith('failure>yyy>abcd>idle')
 
 
 
 
-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 test_dynamic_override_is_only_valid_for_the_current_call():
+    strategy = battle_wait_strategy('success_default')
+    wait = strategy(capture)
+    overridden, options = wait(object(), random_click_swipt_enable=True)
+    assert overridden is not strategy.battle_wait_plan
+    assert overridden.randomclick == 'default'
+    assert 'randomclick' in options
+    assert not hasattr(strategy.battle_wait_plan, 'randomclick')
+    assert wait(object(), random_click_swipt_enable=False)[0] is strategy.battle_wait_plan
 
 
-        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 test_nested_context_restores_each_task_strategy_even_after_an_exception():
+    ordinary = battle_wait_strategy()(capture)
+    activity = battle_wait_strategy(success='activity')(capture)
+    outer = battle_wait_strategy(success='outer')
+    inner = battle_wait_strategy(success='inner')
+    assert ordinary(object())[0].success == 'default'
+    assert activity(object())[0].success == 'activity'
+    with outer:
+        assert activity(object())[0].success == 'outer'
+        with pytest.raises(RuntimeError, match='interrupted'):
+            with inner:
+                assert ordinary(object())[0].success == 'inner'
+                raise RuntimeError('interrupted')
+        assert activity(object())[0].success == 'outer'
+    assert ordinary(object())[0].success == 'default'
+    assert activity(object())[0].success == 'activity'
+
+
+def test_same_context_manager_can_be_nested_and_used_in_independent_contexts():
+    strategy = battle_wait_strategy(success='activity')
+    options = battle_wait_options(prepare={'lock_team': True})
+    wait = battle_wait_strategy()(capture)
+    first, second = copy_context(), copy_context()
+    first.run(strategy.__enter__)
+    second.run(strategy.__enter__)
+    first.run(options.__enter__)
+    second.run(options.__enter__)
+    first.run(options.__exit__, None, None, None)
+    first.run(strategy.__exit__, None, None, None)
+    assert first.run(wait, object())[0].success == 'default'
+    assert second.run(wait, object())[0].success == 'activity'
+    assert second.run(wait, object())[1]['prepare'].lock_team is True
+    second.run(options.__exit__, None, None, None)
+    second.run(strategy.__exit__, None, None, None)
+    with strategy, options:
+        with strategy, options:
+            assert wait(object())[0].success == 'activity'
+        assert wait(object())[1]['prepare'].lock_team is True
+    assert wait(object())[0].success == 'default'
+    assert wait(object())[1]['prepare'].lock_team is False
+
+
+def test_options_decorator_and_with_are_scoped_to_the_current_call():
+    wait = battle_wait_options(
+        success={'excludes_1': ['C_REWARD_1']}, prepare={'lock_team': True}
+    )(battle_wait_strategy()(capture))
+    assert wait(object())[1]['success'].excludes_1 == ['C_REWARD_1']
+    with battle_wait_options(success={'excludes_1': ['C_END_MESSAGE_RIGHT_TOP']}):
+        options = wait(object())[1]
+        assert options['success'].excludes_1 == ['C_END_MESSAGE_RIGHT_TOP']
+        assert options['prepare'].lock_team is True
+        with pytest.raises(RuntimeError):
+            with battle_wait_options(prepare={'lock_team': False}):
+                assert wait(object())[1]['prepare'].lock_team is False
+                raise RuntimeError('interrupted')
+        assert wait(object())[1]['prepare'].lock_team is True
+    assert wait(object())[1]['success'].excludes_1 == ['C_REWARD_1']
+    assert battle_wait_options._context.get() is None
+    assert battle_wait_options._decorator_options.get() is None
 
 
-        def _bw_completion_finish(self, bw_ctx):
-            self.events.append('completion')
-            bw_ctx.success = True
-            return HookSignal.DONE
 
 
-    battle_wait = CustomBattleWait()
-    plan = BattleWaitPlan(
-        'setup_record',
-        'yyy_record',
-        'completion_finish',
-        sequence='yyy > completion > interrupt > success > failure > idle',
+def test_cross_task_options_do_not_leak_between_tasks_or_calls():
+    ordinary = battle_wait_options(success={'excludes_1': ['C_REWARD_1']})(
+        battle_wait_strategy()(capture)
+    )
+    activity = battle_wait_options(success={'excludes_1': ['C_END_ACTIVITY_REWARD']})(
+        battle_wait_strategy(success='activity')(capture)
     )
     )
+    assert ordinary(object())[0].success == 'default'
+    assert activity(object())[0].success == 'activity'
+    ordinary(object())[1]['success'].excludes_1.clear()
+    assert ordinary(object())[1]['success'].excludes_1 == ['C_REWARD_1']
+    assert activity(object())[1]['success'].excludes_1 == ['C_END_ACTIVITY_REWARD']
+    assert battle_wait_strategy()(capture)(object())[1]['success'] == OptionSuccessDefault()
 
 
-    assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
-    assert battle_wait.events == ['setup', 'yyy', 'completion']
 
 
+def test_options_decorator_restores_context_after_exception():
+    @battle_wait_options(prepare={'lock_team': True})
+    def fail(owner):
+        assert battle_wait_options.current()['prepare'].lock_team is True
+        raise RuntimeError('interrupted')
 
 
-def test_custom_sequence_controls_hook_order():
-    plan = BattleWaitPlan(
-        'yyy_default',
-        sequence='failure > yyy > completion > interrupt > success > idle',
-    )
+    with battle_wait_options(success={'excludes_1': ['C_REWARD_1']}):
+        with pytest.raises(RuntimeError):
+            fail(object())
+        options = battle_wait_options.current()
+        assert options['prepare'].lock_team is False
+        assert options['success'].excludes_1 == ['C_REWARD_1']
 
 
-    assert plan.sequence_function_names() == [
-        '_bw_failure_default',
-        '_bw_yyy_default',
-        '_bw_completion_default',
-        '_bw_interrupt_default',
-        '_bw_success_default',
-        '_bw_idle_default',
-    ]
 
 
+class ReplayBattle(BattleWait):
+    def __init__(self):
+        self.events = []
+        self.frames = 0
 
 
-def test_custom_events_without_sequence_are_inserted_before_idle_in_argument_order():
-    plan = BattleWaitPlan('yyy_default', 'abcd_edf')
+    def screenshot(self):
+        self.frames += 1
+        assert self.frames < 5, 'battle did not complete'
+        self.events.append('screenshot')
 
 
-    assert plan.sequence == 'completion>interrupt>success>failure>yyy>abcd>idle'
+    def _bw_setup_record(self, pub, pri):
+        self.events.append('setup')
+        return HookSignal.DONE
 
 
+    def _bw_prepare_default(self, pub, pri):
+        return HookSignal.CONTINUE
 
 
-def test_dynamic_override_does_not_modify_the_default_plan():
-    strategy = battle_wait_strategy('success_default')
+    def _bw_success_record(self, pub, pri):
+        self.events.append('success')
+        pub.per_battle.success = BattleResult.SUCCESS
+        return runtime.hook_enabled_update(enable=('completion',), disable=('success', 'failure'))
 
 
-    @strategy
-    def battle_wait(owner, *, battle_wait_plan):
-        return battle_wait_plan
+    def _bw_completion_record(self, pub, pri):
+        self.events.append('completion')
+        return HookSignal.DONE
 
 
-    default_plan = strategy.battle_wait_plan
+    @battle_wait_strategy(setup='record', success='record', completion='record')
+    def battle_wait(self, *args, **kwargs):
+        return self.battle_wait_with_strategy(*args, **kwargs)
 
 
-    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 strategy.battle_wait_plan is default_plan
+def test_setup_runs_before_the_wait_loop_and_completion_waits_for_settlement():
+    battle = ReplayBattle()
+    assert battle.battle_wait() is True
+    assert battle.events == ['setup', 'screenshot', 'success', 'screenshot', 'completion']
 
 
 
 
-def test_dynamic_override_is_only_valid_for_the_current_call():
-    strategy = battle_wait_strategy('success_default')
+def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
+    class CustomBattle(ReplayBattle):
+        def _bw_yyy_multi_word(self, pub, pri):
+            self.events.append('yyy')
+            pub.per_battle.success = BattleResult.SUCCESS
+            return runtime.hook_enabled_update(enable=('completion',), disable=())
 
 
-    @strategy
-    def battle_wait(owner, *, battle_wait_plan):
-        return battle_wait_plan
+    battle = CustomBattle()
+    with battle_wait_strategy(
+        setup='record', success='record', completion='record', yyy='multi_word',
+        sequence='yyy>completion>interrupt>prepare>preset>green>red>echo>success>failure>idle',
+    ):
+        assert battle.battle_wait() is True
+    assert battle.events == ['setup', 'screenshot', 'yyy', 'completion']
 
 
-    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')
+def test_activity_reward_is_collected_after_another_task_is_decorated(monkeypatch):
+    ordinary = battle_wait_strategy()(capture)
 
 
+    class ActivityBattle(BattleWait):
+        def __init__(self):
+            self.reward_visible = True
+            self.frames = 0
+            self.clicks = []
+            self.device = SimpleNamespace(
+                stuck_record_add=lambda name: None,
+                click_record_clear=lambda: None,
+            )
 
 
-# 验证单层装饰器保存自己的 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']},
-    }
+        def screenshot(self):
+            self.frames += 1
+            assert self.frames < 10, 'Activity reward was not collected'
 
 
-    strategy = battle_wait_strategy(
-        'setup_record', 'completion_record', options=decorator_options
-    )
+        def is_in_real_battle(self, is_screenshot=False):
+            return False
 
 
-    class OptionBattleWait(BattleWait):
-        def screenshot(self):
-            pass
+        def appear(self, asset, **kwargs):
+            return asset is self.I_UI_REWARD and self.reward_visible
 
 
-        def _bw_setup_record(self, bw_ctx):
-            return HookSignal.DONE
+        def appear_then_click(self, asset, **kwargs):
+            return False
 
 
-        def _bw_completion_record(self, bw_ctx):
-            received_options.append(bw_ctx.options)
-            bw_ctx.success = True
-            return HookSignal.DONE
+        def click(self, asset, **kwargs):
+            self.clicks.append(asset.name)
+            self.reward_visible = False
 
 
-        @strategy
+        @battle_wait_strategy(success='activity')
         def battle_wait(self, *args, **kwargs):
         def battle_wait(self, *args, **kwargs):
             return self.battle_wait_with_strategy(*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)
-
-
-def test_nested_context_restores_each_task_strategy_even_after_an_exception():
-    def wait(owner, *, battle_wait_plan, options=None):
-        return battle_wait_plan.success, options
+    monkeypatch.setattr('tasks.Component.GeneralBattle.battle_wait.random.random', lambda: 1)
+    task = ActivityBattle()
+    assert task.battle_wait(random_click_swipt_enable=False) is True
+    assert task.clicks == ['exclude_click_activity']
+    assert runtime.pub_ctx.per_task.count == 1
+    assert ordinary(object())[0].success == 'default'
 
 
-    ordinary_wait = battle_wait_strategy()(wait)
-    activity_wait = battle_wait_strategy(success='activity')(wait)
-    outer = battle_wait_strategy(success='outer', options={'success': {'source': 'outer'}})
-    inner = battle_wait_strategy(success='inner', options={'success': {'source': 'inner'}})
 
 
-    # Merely constructing temporary strategies must not change existing tasks.
-    assert ordinary_wait(object()) == ('default', None)
-    assert activity_wait(object()) == ('activity', None)
-    with outer:
-        assert activity_wait(object()) == ('outer', {'success': {'source': 'outer'}})
-        with pytest.raises(RuntimeError, match='interrupted'):
-            with inner:
-                assert ordinary_wait(object()) == ('inner', {'success': {'source': 'inner'}})
-                raise RuntimeError('interrupted')
-        assert activity_wait(object()) == ('outer', {'success': {'source': 'outer'}})
+def _make_runtime_probe():
+    class RuntimeProbe(BattleWait):
+        def __init__(self):
+            self.calls = []
 
 
-    assert ordinary_wait(object()) == ('default', None)
-    assert activity_wait(object()) == ('activity', None)
+        def _bw_setup_probe(self, pub, pri):
+            self.calls.append(('setup', pub, pri))
+            return HookSignal.DONE
 
 
+        def _bw_completion_probe(self, pub, pri):
+            self.calls.append(('completion', pub, pri))
+            return HookSignal.DONE
 
 
-def test_decorator_options_do_not_leak_between_tasks_or_calls():
-    def wait(owner, *, battle_wait_plan, options):
-        return options
+        def _bw_success_probe(self, pub, pri):
+            self.calls.append(('success', pub, pri))
+            return HookSignal.DONE
 
 
-    ordinary_options = {'success': {'excludes': ['C_REWARD_1']}}
-    activity_options = {'success': {'excludes': ['C_END_ACTIVITY_REWARD']}}
-    ordinary_wait = battle_wait_strategy(options=ordinary_options)(wait)
-    activity_wait = battle_wait_strategy(success='activity', options=activity_options)(wait)
+    return RuntimeProbe()
+
+
+def test_runtime_injects_shared_pub_and_per_hook_pri():
+    battle = _make_runtime_probe()
+    battle._bw_setup_probe()
+    battle._bw_completion_probe()
+    _, setup_pub, setup_pri = battle.calls[0]
+    _, completion_pub, completion_pri = battle.calls[1]
+    assert setup_pub is completion_pub is runtime.pub_ctx
+    assert setup_pri is runtime.pri_ctx['_bw_setup_probe']
+    assert completion_pri is runtime.pri_ctx['_bw_completion_probe']
+    assert setup_pri is not completion_pri
+    assert battle._bw_completion_probe.__name__ == '_bw_completion_probe'
+
+
+def test_runtime_task_owner_switch_resets_per_task():
+    battle = _make_runtime_probe()
+    battle._bw_setup_probe()
+    runtime.pub_ctx.cross['keep'] = 1
+    runtime.pub_ctx.per_task.count = 4
+    runtime._ensure_pri_default('_bw_preset_default')
+    runtime.pri_ctx['_bw_preset_default'].per_task.done = True
+    _make_runtime_probe()._bw_setup_probe()
+    assert runtime.pub_ctx.cross == {'keep': 1}
+    assert runtime.pub_ctx.per_task == PerTaskState()
+    assert runtime.pri_ctx['_bw_preset_default'].per_task == PerTaskPreset()
+
+
+def test_runtime_reset_per_battle_keeps_cross_and_per_task():
+    battle = _make_runtime_probe()
+    battle._bw_setup_probe()
+    runtime.pub_ctx.cross['c'] = 1
+    runtime.pub_ctx.per_task.count = 2
+    runtime.pub_ctx.per_battle.success = BattleResult.SUCCESS
+    runtime._ensure_pri_default('_bw_prepare_default')
+    runtime.pri_ctx['_bw_prepare_default'].per_battle.done = True
+    runtime.reset_per_battle()
+    assert runtime.pub_ctx.cross == {'c': 1}
+    assert runtime.pub_ctx.per_task.count == 2
+    assert runtime.pub_ctx.per_battle == PerBattleState()
+    assert runtime.pri_ctx['_bw_prepare_default'].per_battle == PerBattlePrepare()
+
+
+def test_runtime_update_options_distributes_by_hook_event_name_and_resets_defaults():
+    plan = BattleWaitPlan(setup='probe', completion='probe', success='multi_word')
+    options = {
+        'setup': OptionSetupDefault(excludes=['C_REWARD_1']),
+        'completion': OptionCompletionDefault(excludes=['C_REWARD_2']),
+        'success': OptionSuccessDefault(excludes_1=['C_REWARD_3']),
+    }
+    runtime.update_options(options, plan=plan)
+    assert runtime.pub_ctx.options == options
+    for hook in ('_bw_setup_probe', '_bw_completion_probe', '_bw_success_multi_word'):
+        assert runtime.pri_ctx[hook].options is options[runtime.hook2event(hook)]
+    runtime.update_options({}, plan=plan)
+    assert runtime.pri_ctx['_bw_setup_probe'].options == OptionSetupDefault()
+    assert runtime.pri_ctx['_bw_success_multi_word'].options == OptionSuccessDefault()
+
+
+def test_runtime_str_shows_hook_name_and_state_fields():
+    battle = _make_runtime_probe()
+    battle._bw_setup_probe()
+    text = str(battle.__class__._bw_setup_probe)
+    assert '_bw_setup_probe' in text
+    assert 'count' in text
+    assert 'hook_enabled' in text
+
+
+@pytest.mark.parametrize('locked', [False, True])
+def test_prepare_dismisses_soul_mismatch_dialog_before_progressing(locked):
+    class PrepareBattle(BattleWait):
+        def __init__(self):
+            self.visible = [self.I_DISABLE_7DAYS_DIFF_SOUL, self.I_CONFIRM_CLOSE_DIFF_SOUL]
+            self.clicked = []
+
+        def appear_then_click(self, target, **kwargs):
+            if self.visible and target is self.visible[0]:
+                self.clicked.append(target)
+                self.visible.pop(0)
+                return True
+            return False
 
 
-    assert ordinary_wait(object()) == ordinary_options
-    assert activity_wait(object()) == activity_options
-    ordinary_wait(object())['success']['excludes'].clear()
-    assert ordinary_wait(object()) == ordinary_options
-    assert activity_wait(object()) == activity_options
+        def is_in_real_battle(self, is_screenshot=False):
+            return True
+
+    battle = PrepareBattle()
+    runtime.update_options({'prepare': OptionPrepareDefault(lock_team=locked)}, BattleWaitPlan())
+    for _ in range(2):
+        assert battle._bw_prepare_default() == HookSignal.CONTINUE
+        assert runtime.pri_ctx['_bw_prepare_default'].per_battle.done is False
+    assert battle.clicked == [battle.I_DISABLE_7DAYS_DIFF_SOUL, battle.I_CONFIRM_CLOSE_DIFF_SOUL]
+    battle._bw_prepare_default()
+    assert runtime.pri_ctx['_bw_prepare_default'].per_battle.done is True

+ 196 - 0
tests/tasks/Component/GeneralBattle/test_randomclick_gate.py

@@ -0,0 +1,196 @@
+import time
+
+import pytest
+
+from tasks.Component.GeneralBattle.battle_wait import (
+    HookSignal,
+    OptionRandomclickDefault,
+    PerBattleRandomclick,
+    PerTaskRandomclick,
+    PrivateContext,
+    PublicContext,
+    randomclick_gate,
+)
+
+
+class FakeSelf:
+    in_battle = True
+    calls = 0
+
+    def is_in_battle(self, is_screenshot=False):
+        return self.in_battle
+
+    def click(self, *args, **kwargs):
+        self.calls += 1
+
+    def swipe(self, *args, **kwargs):
+        self.calls += 1
+
+
+def make_pub(options=None):
+    options = options if options is not None else OptionRandomclickDefault()
+    return PublicContext(options={'randomclick': options})
+
+
+def make_pri(per_battle=None, per_task=None):
+    return PrivateContext(
+        per_battle=per_battle if per_battle is not None else PerBattleRandomclick(),
+        per_task=per_task if per_task is not None else PerTaskRandomclick(),
+    )
+
+
+def make_gate():
+    fake = FakeSelf()
+
+    @randomclick_gate
+    def _bw_randomclick_default(self, pub, pri):
+        self.calls += 1
+        return HookSignal.CONTINUE
+
+    return fake, _bw_randomclick_default
+
+
+def test_type_mismatch_raises():
+    fake, gate = make_gate()
+
+    with pytest.raises(TypeError, match='OptionRandomclick'):
+        gate(fake, PublicContext(options={'randomclick': {'bad': 1}}), make_pri())
+
+    with pytest.raises(TypeError, match='PerBattleRandomclick'):
+        pub = make_pub()
+        gate(fake, pub, PrivateContext(per_battle={}, per_task=PerTaskRandomclick()))
+
+    with pytest.raises(TypeError, match='PerTaskRandomclick'):
+        pub = make_pub()
+        gate(fake, pub, PrivateContext(per_battle=PerBattleRandomclick(), per_task={}))
+
+
+def test_not_in_battle_skips():
+    fake, gate = make_gate()
+    fake.in_battle = False
+
+    pub = make_pub(OptionRandomclickDefault(start_delay=(0.0, 0.0), cooldown=(0.0, 0.0), trigger_probability=1.0))
+    pri = make_pri()
+    pri.per_battle.first_allowed_time = time.time() - 10  # 已过 delay
+    pri.per_battle.execution_limit_resolved = 5
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+
+
+def test_first_call_resolves_delay_and_limit():
+    fake, gate = make_gate()
+    pub = make_pub()
+    pri = make_pri()
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+    assert 5.0 <= pri.per_battle.start_delay_resolved <= 10.0
+    assert 1 <= pri.per_battle.execution_limit_resolved <= 2
+    assert pri.per_battle.first_allowed_time > 0.0
+
+
+def test_start_delay_blocks_until_first_allowed_time():
+    fake, gate = make_gate()
+    pub = make_pub(OptionRandomclickDefault(start_delay=(100.0, 100.0)))
+    pri = make_pri()
+    pri.per_battle.start_delay_resolved = 100.0
+    pri.per_battle.execution_limit_resolved = 5
+    pri.per_battle.first_allowed_time = time.time() + 100.0
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+
+
+def test_execution_limit_blocks_after_count_reached():
+    fake, gate = make_gate()
+    pub = make_pub(OptionRandomclickDefault(start_delay=(0.0, 0.0), cooldown=(0.0, 0.0), trigger_probability=1.0))
+    pri = make_pri()
+    pri.per_battle.start_delay_resolved = 0.0
+    pri.per_battle.execution_limit_resolved = 1
+    pri.per_battle.first_allowed_time = time.time() - 10
+    pri.per_battle.execution_count = 1
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+
+
+def test_cooldown_blocks_within_cooling_window():
+    fake, gate = make_gate()
+    pub = make_pub(OptionRandomclickDefault(start_delay=(0.0, 0.0), cooldown=(9999.0, 9999.0), trigger_probability=1.0))
+    pri = make_pri()
+    pri.per_battle.start_delay_resolved = 0.0
+    pri.per_battle.execution_limit_resolved = 5
+    pri.per_battle.first_allowed_time = time.time() - 10
+    pri.per_task.last_attempt_time = time.time()
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+
+
+def test_cooldown_records_attempt_even_when_probability_blocked():
+    fake, gate = make_gate()
+    pub = make_pub(OptionRandomclickDefault(start_delay=(0.0, 0.0), cooldown=(0.0, 0.0), trigger_probability=0.0))
+    pri = make_pri()
+    pri.per_battle.start_delay_resolved = 0.0
+    pri.per_battle.execution_limit_resolved = 5
+    pri.per_battle.first_allowed_time = time.time() - 10
+    pri.per_task.last_attempt_time = time.time() - 9999
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+    # 概率未通过也算一次尝试,cooldown 周期被刷新
+    assert pri.per_task.last_attempt_time > time.time() - 1
+
+
+def test_cooldown_survives_reset_per_battle():
+    fake, gate = make_gate()
+    pub = make_pub(OptionRandomclickDefault(start_delay=(0.0, 0.0), cooldown=(9999.0, 9999.0), trigger_probability=1.0))
+    pri = make_pri()
+    pri.per_battle.start_delay_resolved = 0.0
+    pri.per_battle.execution_limit_resolved = 5
+    pri.per_battle.first_allowed_time = time.time() - 10
+
+    # 上一场战斗刚尝试过 → last_attempt_time 在 per_task 保留
+    pri.per_task.last_attempt_time = time.time()
+
+    # 模拟新一场战斗: per_battle 更新, per_task 不变
+    pri.per_battle = PerBattleRandomclick()
+    pri.per_battle.start_delay_resolved = 0.0
+    pri.per_battle.execution_limit_resolved = 5
+    pri.per_battle.first_allowed_time = time.time() - 10
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 0
+
+
+def test_all_gates_pass_executes_once_and_increments():
+    fake, gate = make_gate()
+    pub = make_pub(OptionRandomclickDefault(start_delay=(0.0, 0.0), cooldown=(0.0, 0.0), trigger_probability=1.0))
+    pri = make_pri()
+    pri.per_battle.start_delay_resolved = 0.0
+    pri.per_battle.execution_limit_resolved = 3
+    pri.per_battle.first_allowed_time = time.time() - 10
+    pri.per_task.last_attempt_time = time.time() - 9999
+
+    result = gate(fake, pub, pri)
+
+    assert result == HookSignal.CONTINUE
+    assert fake.calls == 1
+    assert pri.per_battle.execution_count == 1
+    # cooldown 周期刷新
+    assert pri.per_task.last_attempt_time > time.time() - 1

+ 160 - 0
tests/tasks/WeeklyTrifles/test_touch_fish.py

@@ -0,0 +1,160 @@
+"""Replay the real weekly storage workflow without a device or OCR engine."""
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from module.exception import GameStuckError
+from tasks.WeeklyTrifles import script_task
+from tasks.WeeklyTrifles.script_task import ScriptTask
+
+
+@pytest.fixture(autouse=True)
+def advance_time_without_sleeping(monkeypatch):
+    clock = [0.0]
+
+    class ReplayTimer:
+        def __init__(self, limit):
+            self.limit = limit
+
+        def start(self):
+            self.deadline = clock[0] + self.limit
+            return self
+
+        def reached(self):
+            return clock[0] >= self.deadline
+
+    def sleep(seconds):
+        clock[0] += seconds
+
+    monkeypatch.setattr(script_task, 'Timer', ReplayTimer)
+    monkeypatch.setattr(script_task, 'sleep', sleep)
+
+
+class StorageReplay(ScriptTask):
+    def __init__(self, frames, *, failed_save_clicks=0, tickets=10, cost=5,
+                 menu_opens=True):
+        # BaseTask initialization requires a running emulator; keep its workflow.
+        self.frames = list(frames)
+        self.frame = set()
+        self.stage = None
+        self.menu_opens = menu_opens
+        self.failed_save_clicks = failed_save_clicks
+        self.save_attempts = 0
+        self.clicks = []
+        self.destinations = []
+        self.screenshots = 0
+        self.device = SimpleNamespace(image=None)
+        self.O_WT_LUCKY_TICKETS = SimpleNamespace(ocr=Mock(return_value=(tickets, 0, tickets)))
+        self.O_WT_SAVE_COST = SimpleNamespace(ocr=Mock(return_value=cost))
+        self.config = SimpleNamespace(weekly_trifles=SimpleNamespace(trifles=SimpleNamespace(
+            share_collect=False, share_area_boss=False, share_secret=False,
+            save_touch_fish=True, broken_amulet=0,
+        )))
+        self.set_next_run = Mock()
+
+    def ui_get_current_page(self):
+        pass
+
+    def ui_goto(self, page):
+        self.destinations.append(page)
+        self.stage = page
+        return True
+
+    def screenshot(self):
+        self.screenshots += 1
+        assert self.screenshots < 200, 'Storage workflow did not respect its timeout'
+        if self.stage is script_task.page_guild:
+            self.frame = {'I_WT_FOLD_WINDOW' if self.menu_opens else 'I_WT_OPEN_FOLD_WINDOW'}
+        elif self.frames:
+            self.frame = set(self.frames.pop(0))
+        self.device.image = frozenset(self.frame)
+
+    def appear(self, asset, **kwargs):
+        return any(asset is getattr(self, name) for name in self.frame)
+
+    def appear_then_click(self, asset, **kwargs):
+        if not self.appear(asset):
+            return False
+        if asset is self.I_WT_SAVE_ALL:
+            self.save_attempts += 1
+            if self.failed_save_clicks:
+                self.failed_save_clicks -= 1
+                return False
+        self.clicks.append(asset)
+        return True
+
+    def click(self, asset, **kwargs):
+        self.clicks.append(asset)
+        return True
+
+
+def test_storage_dismisses_obscuring_popups_before_reading_tickets():
+    task = StorageReplay([
+        {'I_WT_LAST_SAVE'},
+        {'I_WT_HAPPY_GET'},
+        {'I_WT_SAVE_ALL'},
+        {'I_WT_TF_CONFIRM'},
+        {'I_WT_TF_SAVE_SUCCESS'},
+    ])
+
+    task._save_touch_fish()
+
+    task.O_WT_LUCKY_TICKETS.ocr.assert_called_once_with(frozenset({'I_WT_SAVE_ALL'}))
+    assert task.I_WT_HAPPY_GET in task.clicks
+    assert task.I_WT_TF_CONFIRM in task.clicks
+    assert task.save_attempts == 1
+    assert task.destinations[-1] is script_task.page_main
+
+
+def test_storage_retries_a_save_button_that_was_not_clicked():
+    task = StorageReplay([
+        {'I_WT_SAVE_ALL'}, {'I_WT_SAVE_ALL'},
+        {'I_WT_TF_CONFIRM'}, {'I_WT_TF_SAVE_SUCCESS'},
+    ], failed_save_clicks=1)
+
+    task._save_touch_fish()
+
+    assert task.save_attempts == 2
+    assert task.destinations[-1] is script_task.page_main
+
+
+@pytest.mark.parametrize('stuck_frame', [
+    {'I_WT_LAST_SAVE'}, {'I_WT_HAPPY_GET'}, {'I_WT_TF_CONFIRM'}, set(),
+])
+def test_storage_timeout_cannot_mark_the_week_complete(stuck_frame):
+    task = StorageReplay([stuck_frame])
+
+    with pytest.raises(GameStuckError, match='Touch fish save'):
+        task.run()
+
+    task.set_next_run.assert_not_called()
+    assert task.destinations[-1] is script_task.page_touch_fish
+
+
+def test_guild_menu_has_a_bounded_wait():
+    task = StorageReplay([], menu_opens=False)
+
+    with pytest.raises(GameStuckError, match='guild menu'):
+        task._save_touch_fish()
+
+    assert script_task.page_touch_fish not in task.destinations
+
+
+def test_already_stored_week_needs_no_ocr_or_new_save():
+    task = StorageReplay([{'I_WT_TF_SAVE_SUCCESS'}])
+
+    task._save_touch_fish()
+
+    task.O_WT_LUCKY_TICKETS.ocr.assert_not_called()
+    assert task.save_attempts == 0
+    assert task.destinations[-1] is script_task.page_main
+
+
+def test_insufficient_tickets_does_not_click_save():
+    task = StorageReplay([{'I_WT_SAVE_ALL'}], tickets=1, cost=5)
+
+    task._save_touch_fish()
+
+    assert task.save_attempts == 0
+    assert task.destinations[-1] is script_task.page_main

+ 121 - 0
tests/test_switch_onmyoji.py

@@ -0,0 +1,121 @@
+"""SwitchOnmyoji must have a bounded exit path.
+
+Both loops in `SwitchOnmyoji.switch_role` used to be unconditional `while True`.
+When the onmyoji/hero tab cannot be reached (stale asset coordinates after a
+game UI update, emulator showing a different page, ...), they kept clicking
+forever until the global `GameStuckError` watchdog fired roughly two minutes
+later, discarding all context about what actually went wrong.
+
+These tests pin the exit conditions: a loop that never finds its target has to
+raise a named, catchable `ScriptError` instead of spinning, and the happy path
+must keep working unchanged.
+"""
+import pytest
+from types import SimpleNamespace
+
+import module.base.timer as timer_module
+from module.exception import ScriptError
+from tasks.Component.SwitchOnmyoji.config import Onmyoji
+from tasks.Component.SwitchOnmyoji.switch_onmyoji import SwitchOnmyoji
+
+
+@pytest.fixture
+def clock(monkeypatch):
+    """Advance only when a screenshot is taken; never depend on wall time."""
+    clock = SimpleNamespace(now=100.0)
+    monkeypatch.setattr(timer_module, 'time', SimpleNamespace(time=lambda: clock.now))
+    return clock
+
+
+class ScriptedSwitch(SwitchOnmyoji):
+    """Double that replays a fixed sequence of `appear` results.
+
+    `screenshot` and every click are no-ops, so the test exercises the real
+    loop control flow of `switch_role` without a Config, a Device or a game.
+    """
+
+    def __init__(self, appear_results, clock, timeout=20):
+        # deliberately skip BaseTask.__init__: it needs a real Config/Device
+        self._appear_results = list(appear_results)
+        self._appear_calls = 0
+        self._clock = clock
+        self.switch_clicks = 0
+        self.battle_clicks = 0
+        self.ui_clicks = 0
+        # The fake clock makes both real 20s guards run without waiting.
+        self.SWITCH_TAB_TIMEOUT = timeout
+        self.SWITCH_BATTLE_TIMEOUT = timeout
+
+    def _next_appear(self, button):
+        self._appear_calls += 1
+        if not self._appear_results:
+            return False
+        return self._appear_results.pop(0)
+
+    def screenshot(self):
+        self._clock.now += 1
+
+    def appear(self, button, interval=None, **kwargs):
+        return self._next_appear(button)
+
+    def appear_then_click(self, button, interval=None, **kwargs):
+        self.switch_clicks += 1
+        return True
+
+    def click(self, button, interval=None, **kwargs):
+        self.battle_clicks += 1
+        return True
+
+    def ui_click(self, button1, button2, interval=None, **kwargs):
+        self.ui_clicks += 1
+        return True
+
+
+def test_switch_role_raises_when_battle_list_never_appears(clock):
+    task = ScriptedSwitch(appear_results=[], clock=clock)
+
+    with pytest.raises(ScriptError, match='cannot reach the role list'):
+        task.switch_role(role=None, battle_dict={'x': object()}, check_img=object())
+
+    assert task.switch_clicks == 21
+    assert task.battle_clicks == 0
+
+
+def test_switch_role_raises_when_check_icon_never_appears(clock):
+    # battle icon visible, confirm icon never does
+    task = ScriptedSwitch(appear_results=[True], clock=clock)
+
+    with pytest.raises(ScriptError, match='cannot select'):
+        task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.battle_clicks == 21
+
+
+def test_switch_role_still_switches_when_the_flow_is_healthy(clock):
+    # appear order: battle icon, then confirm icon -> no extra clicks needed
+    task = ScriptedSwitch(appear_results=[True, True], clock=clock)
+
+    task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.battle_clicks == 0
+    assert task.ui_clicks == 0
+
+
+def test_switch_role_clicks_the_battle_icon_when_confirm_icon_is_absent(clock):
+    # appear order: battle icon, not-confirm, battle icon -> ui_click back path
+    task = ScriptedSwitch(appear_results=[True, False, True], clock=clock)
+
+    task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.ui_clicks == 1
+
+
+def test_timeouts_are_not_shared_between_instances(clock):
+    a = ScriptedSwitch(appear_results=[], clock=clock)
+    b = ScriptedSwitch(appear_results=[], clock=clock)
+
+    assert a.SWITCH_TAB_TIMEOUT is not None
+    assert b.SWITCH_TAB_TIMEOUT is not None

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.