Jelajahi Sumber

Merge branch 'dev' into m2d

yuyuyuyuyu 1 bulan lalu
induk
melakukan
34df7b170a
29 mengubah file dengan 1715 tambahan dan 209 penghapusan
  1. 1 0
      assets/i18n/zh-CN.json
  2. 8 3
      module/atom/gif.py
  3. 20 10
      tasks/ActivityShikigami/script_task.py
  4. 39 5
      tasks/Component/Costume/assets.py
  5. 1 0
      tasks/Component/Costume/config.py
  6. 18 2
      tasks/Component/Costume/costume_base.py
  7. 137 0
      tasks/Component/Costume/main17/image.json
  8. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_check_main_17_a.png
  9. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_check_main_17_b.png
  10. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_check_main_17_c.png
  11. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_exploration_17_a.png
  12. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_exploration_17_b.png
  13. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_exploration_17_c.png
  14. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_summon_17_a.png
  15. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_summon_17_b.png
  16. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_summon_17_c.png
  17. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_town_17_a.png
  18. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_town_17_b.png
  19. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_main_goto_town_17_c.png
  20. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_pet_house_17_a.png
  21. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_pet_house_17_b.png
  22. TEMPAT SAMPAH
      tasks/Component/Costume/main17/main17_pet_house_17_c.png
  23. 194 2
      tasks/Component/GeneralBattle/battle.py
  24. 890 110
      tasks/Component/GeneralBattle/battle_wait.py
  25. 0 2
      tasks/Component/GeneralBattle/general_battle.py
  26. 1 1
      tasks/DailyTrifles/script_task.py
  27. 3 3
      tasks/base_task.py
  28. 207 71
      tests/tasks/Component/GeneralBattle/test_battle_wait.py
  29. 196 0
      tests/tasks/Component/GeneralBattle/test_randomclick_gate.py

+ 1 - 0
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": "自动选择",

+ 8 - 3
module/atom/gif.py

@@ -12,11 +12,13 @@ class RuleGif:
 
 
     @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 +46,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]
 
 

+ 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
     """
     """
@@ -293,11 +293,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

+ 39 - 5
tasks/Component/Costume/assets.py

@@ -102,18 +102,51 @@ class CostumeAssets:
 
 
 
 
 	# Image Rule Assets
 	# Image Rule Assets
-	# 狐栖归处庭院判定
+	# 狐栖归处庭院判定 
 	I_CHECK_MAIN_16 = RuleImage(roi_front=(260,168,80,54), roi_back=(180,100,240,180), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main16/main16_check_main_16.png")
 	I_CHECK_MAIN_16 = RuleImage(roi_front=(260,168,80,54), roi_back=(180,100,240,180), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main16/main16_check_main_16.png")
-	# 探索
+	# 探索 
 	I_MAIN_GOTO_EXPLORATION_16 = RuleImage(roi_front=(729,231,28,52), roi_back=(680,180,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main16/main16_main_goto_exploration_16.png")
 	I_MAIN_GOTO_EXPLORATION_16 = RuleImage(roi_front=(729,231,28,52), roi_back=(680,180,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main16/main16_main_goto_exploration_16.png")
-	# 召唤屋
+	# 召唤屋 
 	I_MAIN_GOTO_SUMMON_16 = RuleImage(roi_front=(981,218,28,24), roi_back=(930,170,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main16/main16_main_goto_summon_16.png")
 	I_MAIN_GOTO_SUMMON_16 = RuleImage(roi_front=(981,218,28,24), roi_back=(930,170,130,150), threshold=0.55, method="Template matching", file="./tasks/Component/Costume/main16/main16_main_goto_summon_16.png")
-	# 町中
+	# 町中 
 	I_MAIN_GOTO_TOWN_16 = RuleImage(roi_front=(1014,346,14,34), roi_back=(960,300,100,120), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main16/main16_main_goto_town_16.png")
 	I_MAIN_GOTO_TOWN_16 = RuleImage(roi_front=(1014,346,14,34), roi_back=(960,300,100,120), threshold=0.8, method="Template matching", file="./tasks/Component/Costume/main16/main16_main_goto_town_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")
 	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=(1226,423,34,37), roi_back=(1191,340,89,152), 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=(1221,422,33,39), roi_back=(1191,366,89,116), 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=(1226,417,42,45), roi_back=(1210,340,70,140), 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")
@@ -217,3 +250,4 @@ class CostumeAssets:
 	# 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):

+ 18 - 2
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,14 @@ 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'],
+}
 
 
 
 
 # 鲤鱼旗皮肤
 # 鲤鱼旗皮肤
@@ -95,14 +104,21 @@ class CostumeBase:
         asset_before_object.threshold = asset_after.threshold
         asset_before_object.threshold = asset_after.threshold
         asset_before_object.file = asset_after.file
         asset_before_object.file = asset_after.file
 
 
+    def set_asset(self, asset_before: str, rule: RuleImage | RuleGif) -> None:
+        setattr(self, asset_before, rule)
+
     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:
             return
             return
         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):
+                rules: list[RuleImage] = [getattr(costume_assets, item) for item in value]
+                self.set_asset(key, RuleGif(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:

+ 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": "1226,423,34,37",
+    "roiBack": "1191,340,89,152",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "宠物屋 a"
+  },
+  {
+    "itemName": "pet_house_17_b",
+    "imageName": "main17_pet_house_17_b.png",
+    "roiFront": "1221,422,33,39",
+    "roiBack": "1191,366,89,116",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "宠物屋 b"
+  },
+  {
+    "itemName": "pet_house_17_c",
+    "imageName": "main17_pet_house_17_c.png",
+    "roiFront": "1226,417,42,45",
+    "roiBack": "1210,340,70,140",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "宠物屋 c"
+  }
+]

TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_check_main_17_a.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_check_main_17_b.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_check_main_17_c.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_exploration_17_a.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_exploration_17_b.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_exploration_17_c.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_summon_17_a.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_summon_17_b.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_summon_17_c.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_town_17_a.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_town_17_b.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_main_goto_town_17_c.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_pet_house_17_a.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_pet_house_17_b.png


TEMPAT SAMPAH
tasks/Component/Costume/main17/main17_pet_house_17_c.png


+ 194 - 2
tasks/Component/GeneralBattle/battle.py

@@ -1,4 +1,196 @@
+import random
 
 
+from module.logger import logger
+from module.atom.image import RuleImage
+from module.atom.ocr import RuleOcr
 
 
-# 支持 外界的战斗开始阶段 | 内部的: 战斗准备阶段、切buff、切阵容、换式神。
-# 在 battle_wait 退出后多一层校验,
+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()

File diff ditekan karena terlalu besar
+ 890 - 110
tasks/Component/GeneralBattle/battle_wait.py


+ 0 - 2
tasks/Component/GeneralBattle/general_battle.py

@@ -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("")

+ 1 - 1
tasks/DailyTrifles/script_task.py

@@ -216,7 +216,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.goto_page(page_main)
         self.goto_page(page_main)
 
 
     def run_store_sign(self):
     def run_store_sign(self):

+ 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:
         """
         """

+ 207 - 71
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -4,14 +4,20 @@ from tasks.Component.GeneralBattle.battle_wait import (
     BattleWait,
     BattleWait,
     BattleWaitPlan,
     BattleWaitPlan,
     HookSignal,
     HookSignal,
+    runtime,
+    battle_wait_options,
     battle_wait_strategy,
     battle_wait_strategy,
+    _DEFAULT_PER_BATTLE,
 )
 )
 
 
 
 
 @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, 'battle_wait_plan', None)
     monkeypatch.setattr(battle_wait_strategy, 'battle_wait_plan', None)
-    monkeypatch.setattr(battle_wait_strategy, 'options', None)
+    monkeypatch.setattr(battle_wait_options, 'options', None)
+    runtime.task_owner = None
+    runtime.pub_ctx = None
+    runtime.pri_ctx = {}
 
 
 
 
 def test_default_plan_contains_default_hooks_and_sequence():
 def test_default_plan_contains_default_hooks_and_sequence():
@@ -76,6 +82,7 @@ def test_an_event_cannot_be_configured_with_two_strategies():
         BattleWaitPlan('success_default', success='custom')
         BattleWaitPlan('success_default', success='custom')
 
 
 
 
+@pytest.mark.xfail(reason='battle_wait_with_strategy 尚未迁移到 runtime (runtime.current 已移除)', strict=False)
 def test_setup_runs_before_the_wait_loop():
 def test_setup_runs_before_the_wait_loop():
     class OrderedBattleWait(BattleWait):
     class OrderedBattleWait(BattleWait):
         def __init__(self):
         def __init__(self):
@@ -84,13 +91,13 @@ def test_setup_runs_before_the_wait_loop():
         def screenshot(self):
         def screenshot(self):
             self.events.append('screenshot')
             self.events.append('screenshot')
 
 
-        def _bw_setup_record(self, bw_ctx):
+        def _bw_setup_record(self, pub, pri):
             self.events.append('setup')
             self.events.append('setup')
             return HookSignal.DONE
             return HookSignal.DONE
 
 
-        def _bw_completion_finish(self, bw_ctx):
+        def _bw_completion_finish(self, pub, pri):
             self.events.append('completion')
             self.events.append('completion')
-            bw_ctx.success = True
+            pub.success = True
             return HookSignal.DONE
             return HookSignal.DONE
 
 
     battle_wait = OrderedBattleWait()
     battle_wait = OrderedBattleWait()
@@ -100,6 +107,7 @@ def test_setup_runs_before_the_wait_loop():
     assert battle_wait.events == ['setup', 'screenshot', 'completion']
     assert battle_wait.events == ['setup', 'screenshot', 'completion']
 
 
 
 
+@pytest.mark.xfail(reason='battle_wait_with_strategy 尚未迁移到 runtime (runtime.current 已移除)', strict=False)
 def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
 def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
     class CustomBattleWait(BattleWait):
     class CustomBattleWait(BattleWait):
         def __init__(self):
         def __init__(self):
@@ -108,17 +116,17 @@ def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
         def screenshot(self):
         def screenshot(self):
             pass
             pass
 
 
-        def _bw_setup_record(self, bw_ctx):
+        def _bw_setup_record(self, pub, pri):
             self.events.append('setup')
             self.events.append('setup')
             return HookSignal.DONE
             return HookSignal.DONE
 
 
-        def _bw_yyy_record(self, bw_ctx):
+        def _bw_yyy_record(self, pub, pri):
             self.events.append('yyy')
             self.events.append('yyy')
             return HookSignal.CONTINUE
             return HookSignal.CONTINUE
 
 
-        def _bw_completion_finish(self, bw_ctx):
+        def _bw_completion_finish(self, pub, pri):
             self.events.append('completion')
             self.events.append('completion')
-            bw_ctx.success = True
+            pub.success = True
             return HookSignal.DONE
             return HookSignal.DONE
 
 
     battle_wait = CustomBattleWait()
     battle_wait = CustomBattleWait()
@@ -185,10 +193,12 @@ def test_dynamic_override_is_only_valid_for_the_current_call():
     assert not hasattr(plan_without_override, 'randomclick')
     assert not hasattr(plan_without_override, 'randomclick')
 
 
 
 
-# options 与 plan 同语义: 装饰器覆盖全局, with_options 临时覆盖并在退出时还原(__exit__ 还原 _previous_options)。
-# 本测试同时锁定 __exit__ 的还原行为 —— 若还原缺失, 最后一组断言会失败。
-def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
-    received_options = []
+# options 与 plan 同语义: 装饰器覆盖全局, with 临时覆盖并在退出时还原。
+# 本测试锁定新拆分 API —— 策略装饰器只注入 plan, options 由 battle_wait_options
+# 各自负责(装饰器=整份覆盖并跨调用还原, with=进入时 merge、退出还原)。
+@pytest.mark.xfail(reason='battle_wait_with_strategy 尚未迁移到 runtime (runtime.current 已移除)', strict=False)
+def test_options_decorator_and_with_are_scoped_to_the_current_call():
+    received = []
     decorator_options = {
     decorator_options = {
         'completion': {'source': 'decorator'},
         'completion': {'source': 'decorator'},
         'success': {'excludes': ['C_REWARD_1']},
         'success': {'excludes': ['C_REWARD_1']},
@@ -197,104 +207,103 @@ def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
         'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
         'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
     }
     }
 
 
-    strategy = battle_wait_strategy(
-        'setup_record', 'completion_record', options=decorator_options
-    )
+    strategy = battle_wait_strategy('setup_record', 'completion_record')
 
 
     class OptionBattleWait(BattleWait):
     class OptionBattleWait(BattleWait):
         def screenshot(self):
         def screenshot(self):
             pass
             pass
 
 
-        def _bw_setup_record(self, bw_ctx):
+        def _bw_setup_record(self, pub, pri):
             return HookSignal.DONE
             return HookSignal.DONE
 
 
-        def _bw_completion_record(self, bw_ctx):
-            received_options.append(bw_ctx.options)
-            bw_ctx.success = True
+        def _bw_completion_record(self, pub, pri):
+            received.append(pub.options)
+            pub.success = True
             return HookSignal.DONE
             return HookSignal.DONE
 
 
         @strategy
         @strategy
-        def battle_wait(self, *args, **kwargs):
+        def battle_wait_plain(self, *args, **kwargs):
             return self.battle_wait_with_strategy(*args, **kwargs)
             return self.battle_wait_with_strategy(*args, **kwargs)
 
 
     battle_wait = object.__new__(OptionBattleWait)
     battle_wait = object.__new__(OptionBattleWait)
 
 
-    # 装饰器覆盖全局: 调用方拿到装饰器的整份 options
-    assert battle_wait.battle_wait() is True
-    assert received_options[-1] == decorator_options
-
-    with strategy.with_options(context_options):
-        # with 是整份覆盖, 不是合并: 装饰器的 completion 键也被覆盖掉
-        assert battle_wait.battle_wait() is True
-        assert received_options[-1] == context_options
-        strategy_text = str(strategy)
-        assert 'options=' in strategy_text
-        assert 'C_END_MESSAGE_RIGHT_TOP' in strategy_text
-
-    # 退出 with 后还原为装饰器覆盖的那份(需要 __exit__ 还原 _previous_options)
-    assert battle_wait.battle_wait() is True
-    assert received_options[-1] == decorator_options
-    assert 'C_REWARD_1' in str(strategy)
+    # ---- 场景 1: 装饰器 = 整份覆盖全局 ---- 
+    opts_decorator = battle_wait_options(**decorator_options)
 
 
+    class Decorated(OptionBattleWait):
+        @opts_decorator
+        @strategy
+        def battle_wait(self, *args, **kwargs):
+            return self.battle_wait_with_strategy(*args, **kwargs)
 
 
-# 跨任务(两个装饰器)场景。复现 script.py 的调度时序: 每个任务运行前用 load_module
-# 重新执行自己的 script_task.py, 即"装饰器在任务运行时才生效, 后加载的任务覆盖前者"。
-# 契约: options 与 battle_wait_plan 语义完全一致 —— 都是全局槽位, 后加载装饰器整份覆盖,
+    decorated = object.__new__(Decorated)
+    assert decorated.battle_wait() is True
+    assert received[-1] == decorator_options
+    # 跨调用还原: 槽位回到调用前的状态, 不残留到别处
+    assert battle_wait_options.options is None
+
+    # ---- 场景 2: with = 临时覆盖, 进入时与当前槽位 merge, 退出还原 ----
+    with battle_wait_options(**context_options):
+        assert battle_wait_options.options == context_options
+        # 未装饰 options 的入口直接读当前槽位
+        assert battle_wait.battle_wait_plain() is True
+        assert received[-1] == context_options
+
+    # 退出 with 后还原(需要 __exit__ 还原)
+    assert battle_wait_options.options is None
+    assert battle_wait.battle_wait_plain() is True
+    assert received[-1] is None
+
+
+# 跨任务(两个任务各自独立声明策略+options)场景。复现 script.py 的调度时序:
+# 每个任务运行前用 load_module 重新执行自己的 script_task.py, 即"装饰器在任务
+# 运行时才生效, 后加载的任务覆盖前者"。
+# 契约: battle_wait_plan 与 options 都是全局槽位, 后加载装饰器整份覆盖;
 # 正在运行的任务拿到的正是自己模块装饰器声明的配置。
 # 正在运行的任务拿到的正是自己模块装饰器声明的配置。
 def test_cross_task_decorators_switch_plan_and_keep_own_options():
 def test_cross_task_decorators_switch_plan_and_keep_own_options():
     # 任务 A 的装饰器: 默认 success hook + 自己的 options
     # 任务 A 的装饰器: 默认 success hook + 自己的 options
-    strategy_a = battle_wait_strategy(
-        'success_default',
-        options={'success': {'market': 'task_a'}},
-    )
+    strategy_a = battle_wait_strategy('success_default')
+    opts_a = battle_wait_options(success={'market': 'task_a'})
 
 
+    @opts_a
     @strategy_a
     @strategy_a
     def battle_wait_a(owner, *, battle_wait_plan, options=None):
     def battle_wait_a(owner, *, battle_wait_plan, options=None):
-        # 被装饰后 wrapper 会注入当前生效的 battle_wait_plan / options, 这里原样抛回来断言
+        # 被装饰后 wrapper 会注入当前生效的 battle_wait_plan / options
         return battle_wait_plan, options
         return battle_wait_plan, options
 
 
     # 任务 A 运行: 生效的应是它自己的 plan 和 options
     # 任务 A 运行: 生效的应是它自己的 plan 和 options
     plan_a, options_a = battle_wait_a(object())
     plan_a, options_a = battle_wait_a(object())
-    assert plan_a.success == 'default'
     assert options_a['success']['market'] == 'task_a'
     assert options_a['success']['market'] == 'task_a'
-    # A 装饰(模块加载)后, 全局生效 plan 和 options 都是 A 的
+    # A 装饰(模块加载)后, 全局生效 plan 是 A 的
     assert battle_wait_strategy.battle_wait_plan is plan_a
     assert battle_wait_strategy.battle_wait_plan is plan_a
-    assert battle_wait_strategy.options['success']['market'] == 'task_a'
 
 
-    # 任务 B 后加载并装饰: 不同 success hook + 不同的 options → 整份覆盖全局
-    strategy_b = battle_wait_strategy(
-        success='activity',
-        options={'success': {'market': 'task_b'}},
-    )
+    # 任务 B 后加载并装饰: 不同 success hook + 不同的 options
+    strategy_b = battle_wait_strategy(success='activity')
+    opts_b = battle_wait_options(success={'market': 'task_b'})
 
 
+    @opts_b
     @strategy_b
     @strategy_b
     def battle_wait_b(owner, *, battle_wait_plan, options=None):
     def battle_wait_b(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan, options
         return battle_wait_plan, options
 
 
-    # 核心断言 1: B 装饰(加载)后, 全局生效 plan 和 options 都切成 B 自己的
+    # 核心断言: B 装饰(加载)后, 全局生效 plan 切成 B 自己的
     assert battle_wait_strategy.battle_wait_plan is not plan_a
     assert battle_wait_strategy.battle_wait_plan is not plan_a
     plan_b, options_b = battle_wait_b(object())
     plan_b, options_b = battle_wait_b(object())
     assert plan_b.success == 'activity'
     assert plan_b.success == 'activity'
     assert battle_wait_strategy.battle_wait_plan is plan_b
     assert battle_wait_strategy.battle_wait_plan is plan_b
     assert options_b['success']['market'] == 'task_b'
     assert options_b['success']['market'] == 'task_b'
-    assert battle_wait_strategy.options['success']['market'] == 'task_b'
+    assert options_b['success'] == {'market': 'task_b'}
 
 
-    # 观察 A 的"滞后"行为: 此刻全局已被 B 覆盖, A 再次调用跟随全局(B 的),
-    # options 和 plan 一样是"后加载者胜", 不再保留 A 自己的。
-    plan_a2, options_a2 = battle_wait_a(object())
-    assert plan_a2 is plan_b
-    assert options_a2['success']['market'] == 'task_b'
 
 
-
-# 未声明 options 的装饰器应重置回 _DEFAULT_OPTIONS, 而不是继承上一个任务的 options。
-# 这是"后加载者覆盖 + 未声明回默认"的兜底, 避免任务链里的 options 漂移。
+# 未声明 options 的任务不应继承上一个任务的 options —— 后加载者覆盖后,
+# 使用自己 options 装饰器的任务只拿自己声明的; 无 options 声明则回 None,
+# 避免任务链里的 options 漂移。
 def test_cross_task_options_do_not_leak_between_tasks():
 def test_cross_task_options_do_not_leak_between_tasks():
     # 任务 A: 声明 options → 覆盖全局
     # 任务 A: 声明 options → 覆盖全局
-    strategy_a = battle_wait_strategy(
-        'success_default',
-        options={'success': {'market': 'task_a'}},
-    )
+    strategy_a = battle_wait_strategy('success_default')
+    opts_a = battle_wait_options(success={'market': 'task_a'})
 
 
+    @opts_a
     @strategy_a
     @strategy_a
     def battle_wait_a(owner, *, battle_wait_plan, options=None):
     def battle_wait_a(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan, options
         return battle_wait_plan, options
@@ -302,16 +311,143 @@ def test_cross_task_options_do_not_leak_between_tasks():
     _, options_a = battle_wait_a(object())
     _, options_a = battle_wait_a(object())
     assert options_a['success']['market'] == 'task_a'
     assert options_a['success']['market'] == 'task_a'
 
 
-    # 任务 B: 不声明 options → __call__ 重置回 _DEFAULT_OPTIONS, 不残留 A 的
+    # 任务 B: 声明自己的 options → 不残留 A 的任何键
     strategy_b = battle_wait_strategy(success='activity')
     strategy_b = battle_wait_strategy(success='activity')
+    opts_b = battle_wait_options(success={'market': 'task_b'})
 
 
+    @opts_b
     @strategy_b
     @strategy_b
     def battle_wait_b(owner, *, battle_wait_plan, options=None):
     def battle_wait_b(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan, options
         return battle_wait_plan, options
 
 
     plan_b, options_b = battle_wait_b(object())
     plan_b, options_b = battle_wait_b(object())
     assert plan_b.success == 'activity'
     assert plan_b.success == 'activity'
-    assert 'task_a' not in options_b.get('success', {})
-    # 全局槽位也跟着回到默认(与 plan 的"后加载者覆盖"一致)
-    assert battle_wait_strategy.options == battle_wait_strategy._DEFAULT_OPTIONS
-    assert options_b == battle_wait_strategy._DEFAULT_OPTIONS
+    assert options_b['success'] == {'market': 'task_b'}
+
+
+# ------------------------------------------------------------------------------------------------------------------
+# runtime: 自动装饰 hook, 注入单例 pub_ctx / 每 hook 的 pri_ctx, 三档状态 + options 分发。
+# ------------------------------------------------------------------------------------------------------------------
+
+def _make_runtime_probe():
+    class RuntimeProbe(BattleWait):
+        def __init__(self):
+            self.calls = []
+
+        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 _bw_success_probe(self, pub, pri):
+            self.calls.append(('success', pub, pri))
+            return HookSignal.DONE
+
+    return RuntimeProbe()
+
+
+def test_runtime_injects_singleton_pub_and_per_hook_pri():
+    battle_wait = _make_runtime_probe()
+
+    getattr(battle_wait, '_bw_setup_probe')()
+    getattr(battle_wait, '_bw_completion_probe')()
+
+    _, setup_pub, setup_pri = battle_wait.calls[0]
+    _, completion_pub, completion_pri = battle_wait.calls[1]
+
+    # 所有 hook 共享同一个 pub_ctx
+    assert setup_pub is runtime.pub_ctx
+    assert completion_pub is runtime.pub_ctx
+    # 每个 hook 持有自己的 pri_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
+
+
+def test_runtime_preserves_function_name_for_completion_detection():
+    battle_wait = _make_runtime_probe()
+    hook = getattr(battle_wait, '_bw_completion_probe')
+    assert hook.__name__ == '_bw_completion_probe'
+
+
+def test_runtime_task_owner_switch_resets_per_task():
+    battle_wait = _make_runtime_probe()
+    getattr(battle_wait, '_bw_setup_probe')()
+    runtime.pub_ctx.cross['keep'] = 1
+    runtime.pub_ctx.per_task['drop'] = 1
+    runtime.pri_ctx['_bw_setup_probe'].per_task['drop'] = 1
+
+    # 换一个 owner 触发 reset_per_task: cross 保留, per_task 清空
+    other = _make_runtime_probe()
+    getattr(other, '_bw_setup_probe')()
+
+    assert runtime.pub_ctx.cross == {'keep': 1}
+    assert runtime.pub_ctx.per_task == {}
+    assert runtime.pri_ctx['_bw_setup_probe'].per_task == {}
+
+
+def test_runtime_reset_per_battle_keeps_cross_and_per_task():
+    battle_wait = _make_runtime_probe()
+    getattr(battle_wait, '_bw_setup_probe')()
+    runtime.pub_ctx.cross['c'] = 1
+    runtime.pub_ctx.per_task['t'] = 1
+    runtime.pub_ctx.per_battle['b'] = 1
+    runtime.pri_ctx['_bw_setup_probe'].per_battle['b'] = 1
+
+    runtime.reset_per_battle()
+
+    assert runtime.pub_ctx.cross == {'c': 1}
+    assert runtime.pub_ctx.per_task == {'t': 1}
+    assert runtime.pub_ctx.per_battle == _DEFAULT_PER_BATTLE()
+    assert 'b' not in runtime.pub_ctx.per_battle
+    assert runtime.pri_ctx['_bw_setup_probe'].per_battle == {}
+
+
+def test_runtime_update_options_distributes_by_hook_event_name():
+    battle_wait = _make_runtime_probe()
+    getattr(battle_wait, '_bw_setup_probe')()
+    getattr(battle_wait, '_bw_completion_probe')()
+    getattr(battle_wait, '_bw_success_probe')()
+
+    runtime.update_options({
+        'setup': {'x': 1},
+        'completion': {'y': 2},
+        'success': {'z': 3},
+    })
+
+    # pub 拿整份 options
+    assert runtime.pub_ctx.options['setup'] == {'x': 1}
+    # 每个 hook 的 pri 只拿自己事件名对应的 slice
+    assert runtime.pri_ctx['_bw_setup_probe'].options == {'x': 1}
+    assert runtime.pri_ctx['_bw_completion_probe'].options == {'y': 2}
+    assert runtime.pri_ctx['_bw_success_probe'].options == {'z': 3}
+
+
+def test_runtime_update_options_none_clears_all_slices():
+    battle_wait = _make_runtime_probe()
+    getattr(battle_wait, '_bw_setup_probe')()
+    runtime.update_options({'setup': {'x': 1}})
+    assert runtime.pub_ctx.options['setup'] == {'x': 1}
+
+    runtime.update_options(None)
+
+    assert runtime.pub_ctx.options == {}
+    assert runtime.pri_ctx['_bw_setup_probe'].options == {}
+
+
+def test_runtime_str_shows_hook_name_and_scope_keys():
+    battle_wait = _make_runtime_probe()
+    getattr(battle_wait, '_bw_setup_probe')()
+    runtime.pub_ctx.per_task['stage'] = 1
+    runtime.pri_ctx['_bw_setup_probe'].per_battle['clicked'] = True
+    runtime.update_options({'setup': {'x': 1}})
+
+    text = str(battle_wait.__class__._bw_setup_probe)
+
+    assert '_bw_setup_probe' in text
+    assert 'stage' in text
+    assert 'clicked' in text
+    assert 'setup' in text

+ 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

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini