Quellcode durchsuchen

fix(GeneralBattle): Select named reward areas for targeted clicks
- match excluded click areas by asset names such as C_END_1_1
- randomly select a matching click and generate a coordinate inside its ROI
- add regression tests for area matching and random selection

neptine vor 2 Monaten
Ursprung
Commit
5951edfb84

+ 15 - 0
module/atom/click.py

@@ -194,3 +194,18 @@ class RuleClickExclude(RuleClick):
         if self.strategy == 'rejection':
             return self._coord_rejection(self.distribution)
         return self._coord_complement(self.distribution)
+
+    def coord_in_excluded(self, areas: list[str] | None = None) -> tuple:
+        """Return a random coordinate inside one of the named excluded areas."""
+        if not areas:
+            areas = ['C_END_1_1', 'C_END_1_2', 'C_END_1_3', 'C_END_1_4', 'C_END_1_5', 'C_END_1_6',
+                     'C_END_2_1', 'C_END_2_2', 'C_END_2_3', 'C_END_2_4', 'C_END_2_5', 'C_END_2_6']
+        area_names = {area.casefold() for area in areas}
+        matched = []
+        for click in self.clicks:
+            names = {str(click), click.name, click.name.upper(), f'C_{click.name.upper()}'}
+            if area_names.intersection(name.casefold() for name in names):
+                matched.append(click)
+        if not matched:
+            raise ValueError(f'No excluded click matches areas: {areas!r}')
+        return random.choice(matched).coord()

+ 38 - 52
tasks/Component/GeneralBattle/battle_wait.py

@@ -14,6 +14,7 @@ from module.base.timer import Timer
 from module.atom.click import RuleClickExclude
 
 from tasks.base_task import BaseTask
+from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
 
 
 P = ParamSpec('P')
@@ -194,7 +195,14 @@ class battle_wait_strategy:
     首次装饰 func 初始化 battle_wait_plan
     """
     battle_wait_plan: BattleWaitPlan = None
-    options: dict[str: dict] = None
+    options: dict[str: dict] = {
+        'success': {
+            'reward_exclude_click_1': ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',],
+            'reward_exclude_click_2': ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
+                                       'C_END_1_1', 'C_END_1_2', 'C_END_1_3', 'C_END_1_4', 'C_END_1_5', 'C_END_1_6',
+                                       ]
+        }
+    }
 
 
     def __init__(self, *arg, **kwargs):
@@ -207,8 +215,7 @@ class battle_wait_strategy:
                     raise
                 if not isinstance(value, dict):
                     raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
-            if battle_wait_strategy.options is None:
-                battle_wait_strategy.options = self._temp_options
+            battle_wait_strategy.options.update(self._temp_options)
 
         self._temp_battle_wait_plan = None
         if battle_wait_strategy.battle_wait_plan is None:
@@ -227,11 +234,14 @@ class battle_wait_strategy:
 
     def __exit__(self, *exc):
         battle_wait_strategy.battle_wait_plan = self._previous_plan
+        self._temp_options = None
         return False
 
     def __str__(self):
         temp_plan = getattr(self, '_temp_battle_wait_plan', None)
         default_plan = getattr(self, 'battle_wait_plan', None)
+        options = dict(battle_wait_strategy.options or {})
+        options.update(self._temp_options or {})
 
         if temp_plan is not None:
             plan = temp_plan
@@ -241,11 +251,12 @@ class battle_wait_strategy:
             scope = 'decorator'
 
         if plan is None:
-            return f'{type(self).__name__}(plan=None)'
+            return f'{type(self).__name__}(options={options}, plan=None)'
 
         return (
             f'{type(self).__name__}('
             f'scope={scope}, '
+            f'options={options}, '
             f'plan=\n{plan}'
             f')'
         )
@@ -277,9 +288,10 @@ class battle_wait_strategy:
             #     'battle_wait_plan',
             #     self.battle_wait_plan,
             # )
-            options = self.options if self.options is not None else battle_wait_strategy.options
+            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 is not None else func(owner, battle_wait_plan=current_plan)
+                if options else func(owner, battle_wait_plan=current_plan)
 
         return inner
 
@@ -294,30 +306,26 @@ class battle_wait_strategy:
         # 先装饰器, 后临时变量
         if battle_wait_strategy.options is None:
             battle_wait_strategy.options = options
+            self._temp_options = None
         else:
             self._temp_options = options
         return self
 
 
-class BattleWait(BaseTask):
-    # build in
+class BattleWait(BaseTask, GeneralBattleAssets):
+
     # ------------------------------------------------------------------------------------------------------------------
-    # @property
-    # def reward_exclude_click(self):
-    #     if not hasattr(self, '_reward_exclude_click'):
-    #         self._reward_exclude_click = RuleClickExclude(
-    #             [self.C_REWARD_1, self.C_REWARD_2, self.C_REWARD_3]
-    #         )
-    #     return self._reward_exclude_click
     @cached_property
     def exclude_button_stage_1(self):
         return ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2',
-                'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS', 'C_END_FRIENDS_1'
+                'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
                 ]
 
     @cached_property
     def exclude_button_stage_2(self):
-        return []
+        return ['C_END_MESSAGE_RIGHT_TOP', 'C_END_BUFF_AREA_1', 'C_END_BUFF_AREA_2', 'C_END_SOUL_RECORD', 'C_END_SOUL_DETAILS',
+                'C_END_1_1', 'C_END_1_2', 'C_END_1_3', 'C_END_1_4', 'C_END_1_5', 'C_END_1_6',
+                ]
 
     def reward_exclude_click(self, areas: list[str] = None, name: str = 'success_exclude_click') -> RuleClickExclude:
         inputs = []
@@ -363,11 +371,10 @@ class BattleWait(BaseTask):
         return HookSignal.CONTINUE
 
     def _bw_interrupt_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
+        # 比如 御魂溢出
         return HookSignal.CONTINUE
 
     def _bw_success_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
-
-
         if self.appear_then_click(self.I_WIN, interval=0.8):
             self.click(self._reward_exclude_click_1)
             return HookSignal.CONTINUE
@@ -384,6 +391,10 @@ class BattleWait(BaseTask):
         while 1:
             self.screenshot()
 
+            # 不小心点到了具体的奖励,他会弹出这个物品的详细描述 里面必定包含有“获取途径”
+            if self.appear(self.I_END_FIX_1) or self.appear(self.I_END_FIX_2):
+                self.click(self.C_REWARD_2, interval=1.5)
+
             _appear_ghost, _appear_reward, _appear_gold, _appear_skin = (
                 self.appear(self.I_GREED_GHOST, threshold=0.6),
                 self.appear(self.I_REWARD),
@@ -392,7 +403,13 @@ class BattleWait(BaseTask):
             )
             # logger.info(f'_appear_ghost: {_appear_ghost} _appear_reward: {_appear_reward} _appear_gold: {_appear_gold} _appear_skin: {_appear_skin}')
             if any([_appear_ghost, _appear_reward, _appear_gold, _appear_skin]):
+                if random.random() < 0.02:
+                    # 有一定的概率专门点击具体的奖励物品
+                    x, y = self._reward_exclude_click_2.coord_in_excluded(None)
+                    self.device.click(x=x, y=y, control_name='reward_item')
+                    continue
                 self.click(self._reward_exclude_click_2, interval=1.5)
+                pass
             else:
                 logger.info('Get all reward')
                 bw_ctx.success = True
@@ -409,8 +426,8 @@ class BattleWait(BaseTask):
             logger.warning('False battle')
             self.ui_click_until_disappear(self.I_FALSE)
             bw_ctx.completion = True
-            return True
-        return True
+            return HookSignal.CONTINUE
+        return HookSignal.CONTINUE
 
     def _bw_idle_default(self, bw_ctx: BattleWaitContext) -> HookSignal:
         return HookSignal.CONTINUE
@@ -479,36 +496,6 @@ class BattleWait(BaseTask):
         return HookSignal.CONTINUE
 
 
-    # def _bw_idle_random_click(self, bw_ctx: BattleWaitContext):
-    #     if 0 <= random.randint(0, 500) <= 3:  # 百分之4的概率
-    #         rand_type = random.randint(0, 2)
-    #         match rand_type:
-    #             case 0:
-    #                 self.click(self.C_RANDOM_CLICK, interval=20)
-    #             case 1:
-    #                 self.swipe(self.S_BATTLE_RANDOM_LEFT, interval=20)
-    #             case 2:
-    #                 self.swipe(self.S_BATTLE_RANDOM_RIGHT, interval=20)
-    #         # 重新设置为长战斗
-    #         # self.device.stuck_record_add('BATTLE_STATUS_S')
-    #     else:
-    #         time.sleep(0.4)  # 这样的好像不对
-    #
-    # def _bw_random_click(self, bw_ctx: BattleWaitContext):
-    #     if 0 <= random.randint(0, 500) <= 3:  # 百分之4的概率
-    #         rand_type = random.randint(0, 2)
-    #         match rand_type:
-    #             case 0:
-    #                 self.click(self.C_RANDOM_CLICK, interval=20)
-    #             case 1:
-    #                 self.swipe(self.S_BATTLE_RANDOM_LEFT, interval=20)
-    #             case 2:
-    #                 self.swipe(self.S_BATTLE_RANDOM_RIGHT, interval=20)
-    #         # 重新设置为长战斗
-    #         # self.device.stuck_record_add('BATTLE_STATUS_S')
-    #     else:
-    #         time.sleep(0.4)  # 这样的好像不对
-
     # ------------------------------------------------------------------------------------------------------------------
     def battle_wait_with_strategy(self, *args, **kwargs) -> bool:
         """
@@ -602,4 +589,3 @@ if __name__ == '__main__':
 
 
 
-

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

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

+ 0 - 1
tasks/EvoZone/script_task.py

@@ -331,7 +331,6 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
 
 
     @battle_wait_strategy()
-    # @battle_wait_strategy(options={'success': {}})
     def battle_wait(self, *args, **kwargs):
         return self.battle_wait_with_strategy(*args, **kwargs)
 

+ 4 - 2
tasks/RealmRaid/script_task.py

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

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

@@ -3,6 +3,44 @@ import pytest
 from module.atom.click import RuleClick, RuleClickExclude
 
 
+def test_coord_in_excluded_selects_a_matching_click_and_uses_its_roi_front():
+    first = RuleClick((10, 20, 5, 6), (100, 100, 20, 20), name='first')
+    second = RuleClick((30, 40, 7, 8), (200, 200, 20, 20), name='second')
+    click = RuleClickExclude([first, second], strategy='complement', distribution='uniform')
+
+    for _ in range(100):
+        x, y = click.coord_in_excluded(['second'])
+        assert 30 <= x < 37
+        assert 40 <= y < 48
+
+
+def test_coord_in_excluded_matches_asset_attribute_name():
+    click = RuleClick((30, 40, 7, 8), (200, 200, 20, 20), name='end_1_1')
+    exclude = RuleClickExclude([click], strategy='complement', distribution='uniform')
+
+    x, y = exclude.coord_in_excluded(['C_END_1_1'])
+    assert 30 <= x < 37
+    assert 40 <= y < 48
+
+
+def test_coord_in_excluded_randomly_selects_from_multiple_matches(monkeypatch):
+    first = RuleClick((10, 20, 5, 6), (100, 100, 20, 20), name='area')
+    second = RuleClick((30, 40, 7, 8), (200, 200, 20, 20), name='area')
+    click = RuleClickExclude([first, second], strategy='complement', distribution='uniform')
+    monkeypatch.setattr('module.atom.click.random.choice', lambda values: values[1])
+
+    x, y = click.coord_in_excluded(['area'])
+    assert 30 <= x < 37
+    assert 40 <= y < 48
+
+
+def test_coord_in_excluded_rejects_unknown_area():
+    click = RuleClickExclude([], strategy='complement', distribution='uniform')
+
+    with pytest.raises(ValueError, match='No excluded click matches'):
+        click.coord_in_excluded(['unknown'])
+
+
 def test_exclude_click_string_contains_excluded_click_names():
     first = RuleClick((0, 0, 1, 1), (100, 100, 20, 20), name='first')
     second = RuleClick((0, 0, 1, 1), (200, 200, 20, 20), name='second')

+ 21 - 5
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -186,8 +186,17 @@ def test_dynamic_override_is_only_valid_for_the_current_call():
 # 验证单层装饰器保存自己的 options,with_options() 只在上下文内临时覆盖,退出后恢复。
 def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
     received_options = []
-    decorator_options = {'completion': {'source': 'decorator'}}
-    context_options = {'completion': {'source': 'with'}}
+    decorator_options = {
+        'completion': {'source': 'decorator'},
+        'success': {'excludes': ['C_REWARD_1']},
+    }
+    context_options = {
+        'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
+    }
+
+    strategy = battle_wait_strategy(
+        'setup_record', 'completion_record', options=decorator_options
+    )
 
     class OptionBattleWait(BattleWait):
         def screenshot(self):
@@ -200,7 +209,7 @@ def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
             received_options.append(bw_ctx.options)
             return HookSignal.DONE
 
-        @battle_wait_strategy('setup_record', 'completion_record', options=decorator_options)
+        @strategy
         def battle_wait(self, *args, **kwargs):
             return self.battle_wait_with_strategy(*args, **kwargs)
 
@@ -209,9 +218,16 @@ def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
     assert battle_wait.battle_wait() is True
     assert received_options[-1] == decorator_options
 
-    with battle_wait_strategy().with_options(context_options):
+    with strategy.with_options(context_options):
         assert battle_wait.battle_wait() is True
-        assert received_options[-1] == context_options
+        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)