فهرست منبع

fix(GeneralBattle): Override class-level battle wait plan and options per decorator

neptine 2 ماه پیش
والد
کامیت
f214461b75

+ 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_green: bool = Field(default=False, description='enable_pass_green_help')
     pass_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='pass_green_mark_help')
-    enable_pass_anti_detect: bool = Field(default=False, description='enable_pass_anti_detect_help')
+    enable_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_green: bool = Field(default=False, description='enable_ap_green_help')
     ap_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='ap_green_mark_help')
-    enable_ap_anti_detect: bool = Field(default=False, description='enable_ap_anti_detect_help')
+    enable_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_green: bool = Field(default=False, description='enable_boss_green_help')
     boss_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='boss_green_mark_help')
-    enable_boss_anti_detect: bool = Field(default=False, description='enable_boss_anti_detect_help')
+    enable_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_green: bool = Field(default=False, description='enable_ap100_green_help')
     ap100_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='ap100_green_mark_help')
-    enable_ap100_anti_detect: bool = Field(default=False, description='enable_ap100_anti_detect_help')
+    enable_ap100_anti_detect: bool = Field(default=True, description='enable_ap100_anti_detect_help')
 
 
 class ActivityShikigami(ConfigBase):

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

@@ -0,0 +1,4 @@
+
+
+# 支持 外界的战斗开始阶段 | 内部的: 战斗准备阶段、切buff、切阵容、换式神。
+# 在 battle_wait 退出后多一层校验,

+ 40 - 39
tasks/Component/GeneralBattle/battle_wait.py

@@ -1,6 +1,7 @@
 import random
 import time
 import copy
+from copy import deepcopy
 
 
 from functools import wraps
@@ -190,12 +191,7 @@ class BattleWaitPlan:
         return self
 
 class battle_wait_strategy:
-    """
-    使用with 上下文临时修改  battle_wait_plan
-    首次装饰 func 初始化 battle_wait_plan
-    """
-    battle_wait_plan: BattleWaitPlan = None
-    options: dict[str: dict] = {
+    _DEFAULT_OPTIONS: dict[str: dict] = {
         'success': {
             'reward_exclude_click_1': ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',],
             'reward_exclude_click_2': ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
@@ -204,44 +200,39 @@ class battle_wait_strategy:
         }
     }
 
+    battle_wait_plan: BattleWaitPlan = None
+    options: dict[str: dict] = deepcopy(_DEFAULT_OPTIONS)
+
+
 
     def __init__(self, *arg, **kwargs):
-        self._temp_options = kwargs.pop('options', None)
-        if self._temp_options is not None:
-            if not isinstance(self._temp_options, dict):
-                raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
-            for key, value in self._temp_options.items():
+        self._options = kwargs.pop('options', None)
+        if self._options is not None:
+            if not isinstance(self._options, dict):
+                raise TypeError(f'temp_options must be a dict, got {self._options!r}')
+            for key, value in self._options.items():
                 if not isinstance(key, str):
                     raise
                 if not isinstance(value, dict):
-                    raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
-            battle_wait_strategy.options.update(self._temp_options)
+                    raise TypeError(f'temp_options must be a dict, got {self._options!r}')
+            # battle_wait_strategy.options.update(self._options)
 
-        self._temp_battle_wait_plan = None
-        if battle_wait_strategy.battle_wait_plan is None:
-            # 首次装饰 func 初始化 battle_wait_plan
-            battle_wait_strategy.battle_wait_plan = BattleWaitPlan(*arg, **kwargs)  # pylint: disable=unused-argument
-        elif self._temp_battle_wait_plan is None:
-            # 使用 with 上下文临时修改 battle_wait_plan
-            self._temp_battle_wait_plan = BattleWaitPlan(*arg, **kwargs)
+        self._battle_wait_plan = BattleWaitPlan(*arg, **kwargs)
 
     def __enter__(self):
         self._previous_plan = battle_wait_strategy.battle_wait_plan
-
-        if self._temp_battle_wait_plan is not None:
-            battle_wait_strategy.battle_wait_plan = self._temp_battle_wait_plan
+        battle_wait_strategy.battle_wait_plan = self._battle_wait_plan
         return self
 
     def __exit__(self, *exc):
         battle_wait_strategy.battle_wait_plan = self._previous_plan
-        self._temp_options = None
+        self._options = None
         return False
 
     def __str__(self):
-        temp_plan = getattr(self, '_temp_battle_wait_plan', None)
+        temp_plan = getattr(self, '_battle_wait_plan', None)
         default_plan = getattr(self, 'battle_wait_plan', None)
         options = dict(battle_wait_strategy.options or {})
-        options.update(self._temp_options or {})
 
         if temp_plan is not None:
             plan = temp_plan
@@ -268,6 +259,14 @@ class battle_wait_strategy:
         return self
 
     def __call__(self, func: Callable[P, T]) -> Callable[P, T]:
+        # 跨任务重置配置和策略,但是不重置状态
+        battle_wait_strategy.options = (
+            deepcopy(self._options)
+            if self._options is not None
+            else deepcopy(self._DEFAULT_OPTIONS)
+        )
+        battle_wait_strategy.battle_wait_plan = self._battle_wait_plan
+
         @wraps(func)
         def inner(owner, *args: P.args, **kwargs: P.kwargs) -> T:
             # 兼容性处理
@@ -289,7 +288,6 @@ class battle_wait_strategy:
             #     self.battle_wait_plan,
             # )
             options = dict(battle_wait_strategy.options or {})
-            options.update(self._temp_options or {})
             return func(owner, battle_wait_plan=current_plan, options=options) \
                 if options else func(owner, battle_wait_plan=current_plan)
 
@@ -304,11 +302,8 @@ class battle_wait_strategy:
             if not isinstance(v, dict):
                 raise TypeError()
         # 先装饰器, 后临时变量
-        if battle_wait_strategy.options is None:
-            battle_wait_strategy.options = options
-            self._temp_options = None
-        else:
-            self._temp_options = options
+        self._previous_options = battle_wait_strategy.options
+        battle_wait_strategy.options = deepcopy(options)
         return self
 
 
@@ -537,7 +532,7 @@ class BattleWait(BaseTask, GeneralBattleAssets):
                     x, y = self.exclude_click_activity.coord_in_excluded(['C_END_ACTIVITY_REWARD'])
                     self.device.click(x=x, y=y, control_name='reward_item')
                     continue
-                self.click(self.exclude_click_activity, interval=1.5)
+                self.click(self.exclude_click_activity, interval=2.5)
             elif not self.appear(self.I_END_FIX_2):
                 self.screenshot()
                 if any([self.appear(self.I_UI_REWARD), self.appear(self.I_END_FIX_1), self.appear(self.I_END_FIX_2), self.appear(self.I_END_FIX_3)]):
@@ -557,14 +552,14 @@ class BattleWait(BaseTask, GeneralBattleAssets):
     def battle_wait_with_strategy(self, *args, **kwargs) -> bool:
         """
         三种自定义配置方法:
-        1. 使用装饰器battle_wait_strategy
+        1. 使用装饰器battle_wait_strategy, 将会覆盖掉类变量
             @battle_wait_strategy( 'reserve_default', 'idle_default', failure='default')
             def battle_wait(self, *args, **kwargs):
                 return self.battle_wait_with_strategy(*args, **kwargs)
-        2. 使用 with 上下文 (!在1基础上)
+        2. 使用 with 上下文 (!在1基础上), 将会临时覆盖掉原先的类变量,退出后恢复
             with battle_wait_strategy('reserve_default'):
                 test_battle_wait.battle_wait()
-        3. 调用时动态传参 (!在2基础上)
+        3. 调用时动态传参 (!在1基础上), 不覆盖,就临时更新策略
             obj.battle_wait(random_click_swipt_enable=1)  # 详细参数看 battle_wait_strategy.__call__()
 
         理解 event + strategy 概念: 把战斗过程抽象为一系列触发事件以及对应的实现函数,也称hook。
@@ -572,7 +567,7 @@ class BattleWait(BaseTask, GeneralBattleAssets):
         这些 hook 跑在一个 while 里面,默认的调用顺序 BattleWaitPlan.SEQUENCE_DEFAULT = 'completion > interrupt > success > failure > idle'
         setup 没有跑在 while里面 而是在 while之前
 
-        event + strategy 拼成了一个hook, 一个 event 在一次战斗过程中只能挂载一个 strategy】
+        event + strategy 拼成了一个hook, 一个 event 在一次战斗过程中只能挂载一个 strategy
         自定义hook就是字符串拼起来:  battle_wait_strategy的入参可以有 ‘event_strategy’ 或者 'event=strategy'
         可以添加任意 event 以及其对应的 strategy。比如 ‘yyy_default’ 'abcd_edf'
         但是必须要实现对应的hook 上面的比如 _bw_yyy_default() 以及 _bw_abcd_edf()
@@ -580,13 +575,19 @@ class BattleWait(BaseTask, GeneralBattleAssets):
         hook 可以自定义顺序,比如 battle_wait_strategy(sequence='completion > interrupt > success > failure > idle')
         如果没有指定sequence, 新增的event会按照传参时候从左到右排序,左边高优先级,新增的会插入到 failure 和 idle 之间
 
+        ----------------------------------------------------------------------------------------------------------------
         如果希望每一个hook带上参数:
-        1. 可以在装饰器定义 @battle_wait_strategy(options = options)
-        2. 上下文带上  with battle_wait_strategy(...).with_options(options)
+        1. 在 battle_wait_strategy 定义了一组默认的 options
+        2. 可以在装饰器定义 @battle_wait_strategy(options = options),这里将会覆盖掉原先的 battle_wait_strategy.options
+        3. 上下文带上  with battle_wait_strategy(...).with_options(options),同样也是临时覆盖掉 battle_wait_strategy.options
+        4.
         options: dict[str: dict] = {
             "setup": {...}
             ...
         }
+        ----------------------------------------------------------------------------------------------------------------
+        跨战斗,考虑把状态挂到方法上,而不是挂到类对象上。】
+        我突然感觉 一个类里面装了 策略和参数,这样不好,考虑拆分成两个装饰器
 
         """
         bw_ctx = BattleWaitContext()

+ 3 - 3
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.check_and_open_buff(buff)
                         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
             # 未知界面, 既不是准备界面也不是战斗界面
             # logger.info('Wait for preparation page')  # 这玩意刷屏

+ 1 - 1
tasks/RichMan/mall/navbar.py

@@ -89,7 +89,7 @@ class MallNavbar(GameUi, RichManAssets):
         返回商城
         :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:
         """

+ 93 - 9
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -33,7 +33,7 @@ def test_decorator_passes_its_plan_to_the_wrapped_function():
     strategy = battle_wait_strategy('reserve_default', 'idle_default', failure='custom')
 
     @strategy
-    def battle_wait(owner, *, battle_wait_plan):
+    def battle_wait(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan
 
     plan = battle_wait(object())
@@ -47,7 +47,7 @@ def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
     strategy = battle_wait_strategy('success_default')
 
     @strategy
-    def battle_wait(owner, *, battle_wait_plan):
+    def battle_wait(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan
 
     default_plan = battle_wait_strategy.battle_wait_plan
@@ -90,6 +90,7 @@ def test_setup_runs_before_the_wait_loop():
 
         def _bw_completion_finish(self, bw_ctx):
             self.events.append('completion')
+            bw_ctx.success = True
             return HookSignal.DONE
 
     battle_wait = OrderedBattleWait()
@@ -117,6 +118,7 @@ def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
 
         def _bw_completion_finish(self, bw_ctx):
             self.events.append('completion')
+            bw_ctx.success = True
             return HookSignal.DONE
 
     battle_wait = CustomBattleWait()
@@ -157,7 +159,7 @@ def test_dynamic_override_does_not_modify_the_default_plan():
     strategy = battle_wait_strategy('success_default')
 
     @strategy
-    def battle_wait(owner, *, battle_wait_plan):
+    def battle_wait(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan
 
     default_plan = battle_wait_strategy.battle_wait_plan
@@ -174,7 +176,7 @@ def test_dynamic_override_is_only_valid_for_the_current_call():
     strategy = battle_wait_strategy('success_default')
 
     @strategy
-    def battle_wait(owner, *, battle_wait_plan):
+    def battle_wait(owner, *, battle_wait_plan, options=None):
         return battle_wait_plan
 
     battle_wait(object(), random_click_swipt_enable=True)
@@ -183,7 +185,8 @@ def test_dynamic_override_is_only_valid_for_the_current_call():
     assert not hasattr(plan_without_override, 'randomclick')
 
 
-# 验证单层装饰器保存自己的 options,with_options() 只在上下文内临时覆盖,退出后恢复。
+# options 与 plan 同语义: 装饰器覆盖全局, with_options 临时覆盖并在退出时还原(__exit__ 还原 _previous_options)。
+# 本测试同时锁定 __exit__ 的还原行为 —— 若还原缺失, 最后一组断言会失败。
 def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
     received_options = []
     decorator_options = {
@@ -207,6 +210,7 @@ def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
 
         def _bw_completion_record(self, bw_ctx):
             received_options.append(bw_ctx.options)
+            bw_ctx.success = True
             return HookSignal.DONE
 
         @strategy
@@ -215,19 +219,99 @@ def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
 
     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] == {
-            'completion': {'source': 'decorator'},
-            'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
-        }
+        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)
+
+
+# 跨任务(两个装饰器)场景。复现 script.py 的调度时序: 每个任务运行前用 load_module
+# 重新执行自己的 script_task.py, 即"装饰器在任务运行时才生效, 后加载的任务覆盖前者"。
+# 契约: options 与 battle_wait_plan 语义完全一致 —— 都是全局槽位, 后加载装饰器整份覆盖,
+# 正在运行的任务拿到的正是自己模块装饰器声明的配置。
+def test_cross_task_decorators_switch_plan_and_keep_own_options():
+    # 任务 A 的装饰器: 默认 success hook + 自己的 options
+    strategy_a = battle_wait_strategy(
+        'success_default',
+        options={'success': {'market': 'task_a'}},
+    )
+
+    @strategy_a
+    def battle_wait_a(owner, *, battle_wait_plan, options=None):
+        # 被装饰后 wrapper 会注入当前生效的 battle_wait_plan / options, 这里原样抛回来断言
+        return battle_wait_plan, options
+
+    # 任务 A 运行: 生效的应是它自己的 plan 和 options
+    plan_a, options_a = battle_wait_a(object())
+    assert plan_a.success == 'default'
+    assert options_a['success']['market'] == 'task_a'
+    # A 装饰(模块加载)后, 全局生效 plan 和 options 都是 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'}},
+    )
+
+    @strategy_b
+    def battle_wait_b(owner, *, battle_wait_plan, options=None):
+        return battle_wait_plan, options
+
+    # 核心断言 1: B 装饰(加载)后, 全局生效 plan 和 options 都切成 B 自己的
+    assert battle_wait_strategy.battle_wait_plan is not plan_a
+    plan_b, options_b = battle_wait_b(object())
+    assert plan_b.success == 'activity'
+    assert battle_wait_strategy.battle_wait_plan is plan_b
+    assert options_b['success']['market'] == 'task_b'
+    assert battle_wait_strategy.options['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 漂移。
+def test_cross_task_options_do_not_leak_between_tasks():
+    # 任务 A: 声明 options → 覆盖全局
+    strategy_a = battle_wait_strategy(
+        'success_default',
+        options={'success': {'market': 'task_a'}},
+    )
+
+    @strategy_a
+    def battle_wait_a(owner, *, battle_wait_plan, options=None):
+        return battle_wait_plan, options
+
+    _, options_a = battle_wait_a(object())
+    assert options_a['success']['market'] == 'task_a'
+
+    # 任务 B: 不声明 options → __call__ 重置回 _DEFAULT_OPTIONS, 不残留 A 的
+    strategy_b = battle_wait_strategy(success='activity')
+
+    @strategy_b
+    def battle_wait_b(owner, *, battle_wait_plan, options=None):
+        return battle_wait_plan, options
+
+    plan_b, options_b = battle_wait_b(object())
+    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