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

Enhance Hyakkiyakoou(百鬼夜行) Task

Asriel Xu 10 месяцев назад
Родитель
Сommit
339aaa1462

+ 5 - 5
tasks/Hyakkiyakou/.gitignore

@@ -1,5 +1,5 @@
-
-/utils/exp_gen.py
-/temp
-/agent/tagent.py
-/agent/tfocus.py
+
+/utils/exp_gen.py
+/temp
+/agent/tagent.py
+/agent/tfocus.py

+ 22 - 14
tasks/Hyakkiyakou/README.md

@@ -1,14 +1,22 @@
-
-
-
-- agent: 砸豆子的决策模型
-- slave: 针对百鬼对接模拟器的接口
-- debugger.py: 辅助
----
-
-detector: 检测器
-
-tracker: 跟踪器
-
-
-
+
+
+
+- agent: 砸豆子的决策模型
+- slave: 针对百鬼对接模拟器的接口
+- debugger.py: 辅助
+---
+
+detector: 检测器
+
+tracker: 跟踪器
+
+xxz7528的修改:
+1.添加了根据稀有度选择鬼王的函数 in script_task
+    -然而不太管用 因为识别率比较低 但也比没有好 偶尔能识别出来特征鲜明的ssr/sp
+2.延长了完成百鬼后截图记录等待时间,避免截到一半的图 in script_task
+3.添加了没有概率up时不砸ssr/sp的逻辑 in focus.py
+4.添加了冰冻逻辑:仅当目标是ssr/sp且带概率up的时候允许砸冰冻buff,冰冻buff时只砸有概率up的ssr/sp和buff, 删除了gamma和script的冰冻判定逻辑
+    -然而目前由于识别率比较低而且会把各种式神识别成sp蝉冰雪女 这套逻辑仅是添加了 没有启用(在script_task.py里还是会决策冰冻什么都不做)
+
+
+

BIN
tasks/Hyakkiyakou/__pycache__/assets.cpython-310.pyc


BIN
tasks/Hyakkiyakou/__pycache__/config.cpython-310.pyc


BIN
tasks/Hyakkiyakou/__pycache__/debugger.cpython-310.pyc


BIN
tasks/Hyakkiyakou/__pycache__/script_task.cpython-310.pyc


BIN
tasks/Hyakkiyakou/agent/__pycache__/agent.cpython-310.pyc


BIN
tasks/Hyakkiyakou/agent/__pycache__/focus.cpython-310.pyc


+ 5 - 5
tasks/Hyakkiyakou/agent/agent.py

@@ -100,9 +100,9 @@ class Agent:
                 case _ if CI.MIN_SR <= _class <= CI.MAX_SR: weight = weights[2]
                 case _ if CI.MIN_SSR <= _class <= CI.MAX_SSR: weight = 1.5 * weights[1]
                 case _ if CI.MIN_SP <= _class <= CI.MAX_SP: weight = 1.5 * weights[0]
-                case CI.BUFF_005:  # freeze
-                    weight = -1.
-                    _cy += 100
+                # case CI.BUFF_005:  # freeze
+                #     weight = -1.
+                #     _cy += 100
                 case _: continue
             for priority in priorities:  # 我的代码在你之上
                 if priority == _class:
@@ -126,7 +126,7 @@ class Agent:
                 max_variance = variance
         return Focus(inputs=tracks[max_index])
 
-    def decision(self, tracks: list[tuple], state: list) -> list:
+    def decision(self, tracks: list[tuple], state: list, freeze: bool = False) -> list:
         not_decision = [-1, -1, False, -1]
         if not tracks:
             return not_decision
@@ -136,7 +136,7 @@ class Agent:
         self.check_observe(tracks=tracks)
         if self.focus is None:
             return not_decision
-        result = self.focus.decision(tracks=tracks, strategy=self.strategy, state=[delta_time] + state)
+        result = self.focus.decision(tracks=tracks, strategy=self.strategy, state=[delta_time] + state, freeze=freeze)
         if result[2]:
             self.last_throw_time = new_time
             self.dbg_throw += 1

+ 165 - 0
tasks/Hyakkiyakou/agent/agent_ori.py

@@ -0,0 +1,165 @@
+import cv2
+import time
+import copy
+import numpy as np
+
+from datetime import datetime
+from pathlib import Path
+from numpy import uint8, fromfile
+from cached_property import cached_property
+
+from oashya.tracker import Tracker
+from oashya.labels import CLASSINDEX as CI
+from oashya.labels import id2label, id2name
+from module.logger import logger
+from tasks.Hyakkiyakou.agent.focus import Focus
+from tasks.Hyakkiyakou.debugger import Debugger
+
+
+def generate_gaussian_patch(size=(300, 300), mean=0, std_dev=60):
+    x = np.linspace(-150, 150, size[1])
+    y = np.linspace(-150, 150, size[0])
+    x, y = np.meshgrid(x, y)
+    z = np.exp(-(((x - mean) ** 2 + (y - mean) ** 2) / (2 * std_dev ** 2)))
+    return z
+
+
+def embed_patch_in_canvas(canvas, patch, position=(0, 0), patch_size=(300, 300)):
+    canvas_height, canvas_width = 720, 1280
+    patch_height, patch_width = patch_size
+    pos_x, pos_y = position
+    pos_x = max(0, min(pos_x, canvas_width))
+    pos_y = max(0, min(pos_y, canvas_width))
+
+    x1 = pos_x - patch_width // 2
+    y1 = pos_y - patch_height // 2
+    x2 = pos_x + patch_width // 2
+    y2 = pos_y + patch_height // 2
+    x1 = max(0, x1)
+    y1 = max(0, y1)
+    x2 = min(canvas_width, x2)
+    y2 = min(canvas_height, y2)
+    embed_w = x2 - x1
+    embed_h = y2 - y1
+    if embed_w <= 0 or embed_h <= 0:
+        logger.warning(f'Cannot embed patch in canvas: ({position})')
+        return canvas
+    if embed_w < patch_width or embed_h < patch_height:
+        _patch = patch[:embed_h, :embed_w]
+    else:
+        _patch = patch
+    # Embed the patch in the canvas
+    canvas[y1:y2, x1:x2] += _patch
+    return canvas
+
+
+class Agent:
+    GAUSSIAN = generate_gaussian_patch()
+    OBSERVE_THRESHOLD = 0.6
+    # --------------------------------------------------------------------------------
+
+    def __init__(self, strategy: dict = None):
+        self.z = np.zeros((720, 1280), dtype=np.float32)
+        self.focus: Focus = None
+        # 
+        strategy: dict = strategy if strategy is not None else {
+            # 'weights': [1., 1., 1., 0.6, 0.3, 0.3],
+            'priorities': [],
+            'invite_friend': False,
+            'auto_bean': False
+        }
+        self.strategy = strategy
+        self.weights: list[float] = strategy.get('weights', [1., 1., 0.7, 0.3, 0., 0.])
+        self.priorities: list[int] = strategy.get('priorities', [])
+        self.invite_friend: bool = strategy.get('invite_friend', False)
+        self.auto_bean: bool = strategy.get('auto_bean', False)
+        #
+        self.last_throw_time = datetime.now()
+        self.dbg_throw: int = 0
+        self.dbg_throw_n: int = 0
+
+    @classmethod
+    def gamma(cls, tracks: list[tuple],
+              weights: list[float],
+              priorities: list[int] = []) -> np.ndarray:
+        """
+        @param tracks:
+        @param weights: sp, ssr, sr, r, n, g
+        @param priorities:
+        @return:
+        """
+        z = np.zeros((720, 1280), dtype=np.float32)
+        for _id, _class, _conf, _cx, _cy, _w, _h, _v in tracks:
+            weight = 1.
+            mu = 0.8 + (_cx * 0.2) / 1280
+            match _class:
+                case _ if CI.MIN_G <= _class <= CI.MAX_G: weight = weights[5]
+                case _ if CI.MIN_N <= _class <= CI.MAX_N: weight = weights[4]
+                case _ if _class != CI.R_008 and _class != CI.R_007 and (CI.MIN_R <= _class <= CI.MAX_R):
+                    weight = weights[3]  # 不要童男童女
+                case _ if CI.MIN_SR <= _class <= CI.MAX_SR: weight = weights[2]
+                case _ if CI.MIN_SSR <= _class <= CI.MAX_SSR: weight = 1.5 * weights[1]
+                case _ if CI.MIN_SP <= _class <= CI.MAX_SP: weight = 1.5 * weights[0]
+                case CI.BUFF_005:  # freeze
+                    weight = -1.
+                    _cy += 100
+                case _: continue
+            for priority in priorities:  # 我的代码在你之上
+                if priority == _class:
+                    weight = 1.7
+                    break
+            if weight == 0.:
+                continue
+            z = embed_patch_in_canvas(canvas=z, patch=(mu * weight) * Agent.GAUSSIAN, position=(_cx, _cy))
+        return z
+
+    @classmethod
+    def argmax_gamma(cls, z: np.ndarray, tracks: list[tuple]) -> Focus:
+        max_y, max_x = np.unravel_index(np.argmax(z), z.shape)
+        max_variance = 2000
+        max_index = -1
+        for index, track in enumerate(tracks):
+            _id, _class, _conf, _cx, _cy, _w, _h, _v = track
+            variance = (max_x - _cx)**2 + (max_y - _cy)**2
+            if variance < max_variance:
+                max_index = index
+                max_variance = variance
+        return Focus(inputs=tracks[max_index])
+
+    def decision(self, tracks: list[tuple], state: list) -> list:
+        not_decision = [-1, -1, False, -1]
+        if not tracks:
+            return not_decision
+        # Cache the time interval for scattering beans
+        new_time = datetime.now()
+        delta_time = 1000 * (new_time - self.last_throw_time).total_seconds()  # ms
+        self.check_observe(tracks=tracks)
+        if self.focus is None:
+            return not_decision
+        result = self.focus.decision(tracks=tracks, strategy=self.strategy, state=[delta_time] + state)
+        if result[2]:
+            self.last_throw_time = new_time
+            self.dbg_throw += 1
+        else:
+            self.dbg_throw_n += 1
+        return result
+
+    def check_observe(self, tracks: list[tuple]):
+        z = Agent.gamma(tracks=tracks, weights=self.weights, priorities=self.priorities)
+        focus = Agent.argmax_gamma(z=z, tracks=tracks)
+        omega = focus.omega(z)
+        if omega < self.OBSERVE_THRESHOLD:
+            if self.focus is not None:
+                logger.info(f'Focus disappear')
+            self.focus = None
+            return
+        if self.focus is None or self.focus != focus:
+            logger.info(f'Focus changed, now: {id2name(focus._class)}')
+            self.focus = focus
+            self.focus.set_omega(omega)
+        elif self.focus == focus:
+            self.focus.update(focus)
+            self.focus.set_omega(omega)
+        # if Debugger.info_enable:
+        #     self.focus.show()
+

+ 42 - 9
tasks/Hyakkiyakou/agent/focus.py

@@ -9,6 +9,9 @@ from module.logger import logger
 from oashya.labels import id2label, id2name
 from oashya.labels import CLASSINDEX as CI
 
+# get buff status
+from tasks.Hyakkiyakou.slave.hya_slave import HyaBuff
+
 
 class Focus:
     def __init__(self, inputs: list[tuple]):
@@ -67,30 +70,42 @@ velocity: {self._v}"""
         self._h = focus._h
         self._v = focus._v
 
-    def decision(self, tracks, strategy, state) -> list:
+    def decision(self, tracks, strategy, state, freeze: bool = False) -> list:
 
-        buff_omega, buff_cx, buff_cy, buff_v, buff_class = self.omega_buff(tracks, strategy['invite_friend'])
+        buff_states = state[4:] if len(state) > 4 else []  # get buff status:state[4:] = buff_0 ~ buff_3,对应 HyaBuff
+        has_prob_up = any(b == HyaBuff.BUFF_STATE6 for b in buff_states) # 是否存在“概率UP”buff(HyaBuff.BUFF_STATE6)
+        buff_omega, buff_cx, buff_cy, buff_v, buff_class = self.omega_buff(tracks, strategy['invite_friend'], has_prob_up)
         if self._omega > buff_omega:
             buffed = False
             target_x = self._cx + self._v * 100 - (self._w // 2)
             target_y = self._cy - 40
+            target_class = self._class # new : for class
         else:
             buffed = True
             target_x = buff_cx + buff_v * 100
             target_y = buff_cy - 40  # top left corner
-
-        _r = self.r(vector=state, omega=self._omega, omega_buff=self._omega_buff)
+            target_class = buff_class # new : for class
+
+        # ========= 新增:利用和 gamma() 一样的区间判断当前“打的对象”是不是 SSR/SP =========
+        is_rare_ssr_sp = False
+        if CI.MIN_SSR <= target_class <= CI.MAX_SSR and self._omega > buff_omega:
+            is_rare_ssr_sp = True
+        elif CI.MIN_SP <= target_class <= CI.MAX_SP and self._omega > buff_omega:
+            is_rare_ssr_sp = True
+        _r = self.r(vector=state, omega=self._omega, omega_buff=self._omega_buff, is_rare_ssr_sp=is_rare_ssr_sp, freeze=freeze, is_buff=buffed)
         throw = True if _r > 0 else False
         # x, y, throw, number
         return [target_x, target_y, throw, 10]
 
-    def omega_buff(self, tracks, invite_friend: bool) -> float:
+    def omega_buff(self, tracks, invite_friend: bool, has_prob_up: bool) -> float:
         max_omega = 0.
         max_cx = 0
         max_cy = 0
         max_v = 0
         max_class = 0
 
+        focus_is_ssr_sp = (CI.MIN_SSR <= self._class <= CI.MAX_SSR or CI.MIN_SP <= self._class <= CI.MAX_SP)
+
         for _id, _class, _conf, _cx, _cy, _w, _h, _v in tracks:
             _current_omega = 0.
             match _class:
@@ -98,8 +113,8 @@ velocity: {self._v}"""
                 case CI.BUFF_006: _current_omega = 2.0
                 case CI.BUFF_007: _current_omega = 2.0 if invite_friend and _cx <= 1000 else 0
                 case CI.BUFF_002: _current_omega = 2.0 if self._omega >= 1.5 else 0
-                case CI.BUFF_003: _current_omega = 2.0 if self._omega >= 1.5 else 0
                 case CI.BUFF_003: _current_omega = 2.0 if self._omega >= 1.5 and _cx <= 640 else 0
+                # case CI.BUFF_005: _current_omega = max(self._omega + 0.1, 3.0) if focus_is_ssr_sp and has_prob_up else 0 # 冻住,不许跑
                 case _: pass
             if _current_omega > max_omega:
                 max_omega = _current_omega
@@ -110,12 +125,30 @@ velocity: {self._v}"""
         return max_omega, max_cx, max_cy, max_v, max_class
             
     @classmethod
-    def r(cls, vector: list, omega: float, omega_buff: float) -> float:
+    def r(cls, vector: list, omega: float, omega_buff: float, is_rare_ssr_sp: bool, freeze: bool = False, is_buff: bool = False) -> float:
         _omega = max(omega, omega_buff)
-        tau = - 140 / (max(101, vector[0]) - 100)
-        upsilon = (vector[1] / 250 - vector[2] / 35)
+        tau = - 140 / (max(101, vector[0]) - 100) # 时间冷却项:避免过密投豆
+        upsilon = (vector[1] / 250 - vector[2] / 35) # 豆子数量 vs 进度:豆多进度低 -> 倾向多砸;豆少进度高 -> 惩罚多砸
         upsilon = 100 * (upsilon**2 if upsilon > 0 else - upsilon**2)
         result = _omega + tau + upsilon - 0.6
         # print(f"total: {result:.4f} | {_omega:.4f} | {tau:.4f} | {upsilon:.4f}")
+       
+        buff_states = vector[4:] if len(vector) > 4 else []  # get buff status:vector[4:] = buff_0 ~ buff_3,对应 HyaBuff
+        has_prob_up = any(b == HyaBuff.BUFF_STATE6 for b in buff_states) # 是否存在“概率UP”buff(HyaBuff.BUFF_STATE6)
+
+        # punishment:
+        #    no throwing when ssr/sp with no enhanced probability
+        if is_rare_ssr_sp and not has_prob_up:
+            result = -999.0 # stop throwing nonsense
+        
+        # punishment:
+        #   only throw ssr/sp with enhanced probability or buff when freezed
+        if freeze:
+            # if not (is_rare_ssr_sp and has_prob_up):
+            #     result = -999.0 # stop throwing nonsense
+            # if is_buff:
+            #     result = 5.0
+            result = -999.0
+            
         return result
 

+ 121 - 0
tasks/Hyakkiyakou/agent/focus_ori.py

@@ -0,0 +1,121 @@
+import numpy as np
+
+from rich.table import Table
+from rich.text import Text
+from cached_property import cached_property
+
+from module.logger import logger
+
+from oashya.labels import id2label, id2name
+from oashya.labels import CLASSINDEX as CI
+
+
+class Focus:
+    def __init__(self, inputs: list[tuple]):
+        self._id: int = inputs[0]
+        self._class: int = inputs[1]
+        self._conf: int = inputs[2]
+        self._cx: int = inputs[3]
+        self._cy: int = inputs[4]
+        self._w: int = inputs[5]
+        self._h: int = inputs[6]
+        self._v: float = inputs[7]
+        # -----------------------
+        self._omega: float = 0.
+        self._omega_buff: float = 0.
+
+    def __eq__(self, o):
+        return self._id == o._id or o._class == self._class
+
+    def __str__(self):
+        return f"""
+id: {self._id}
+class: {self._class}
+label: {id2label(self._class)}
+name: {id2name(self._class)}
+conf: {self._conf}
+xywh: ({self._cx}, {self._cy}, {self._w}, {self._h})
+velocity: {self._v}"""
+
+    def omega(self, z):
+        __omega = z[self._cy, self._cx]
+        self._omega = __omega
+        return __omega
+
+    def set_omega(self, value):
+        self._omega = value
+
+    def show(self):
+        table = Table(show_lines=True)
+        table.add_column('Property', header_style="bright_cyan", style="cyan", no_wrap=True)
+        table.add_column("Value", style="green")
+        table.add_column('Property', header_style="bright_cyan", style="cyan", no_wrap=True)
+        table.add_column("Value", style="green")
+        table.add_row('id', str(self._id), 'conf', str(self._conf))
+        table.add_row('class', str(self._class), 'xywh', f'({self._cx}, {self._cy}, {self._w}, {self._h})')
+        table.add_row('label', id2label(self._class), 'velocity', str(self._v))
+        table.add_row('name', f'{id2name(self._class)}', 'omega', str(self._omega))
+        logger.print(table, justify='center')
+
+    def update(self, focus):
+        self._id = focus._id
+        self._class = focus._class
+        self._conf = focus._conf
+        self._cx = focus._cx
+        self._cy = focus._cy
+        self._w = focus._w
+        self._h = focus._h
+        self._v = focus._v
+
+    def decision(self, tracks, strategy, state) -> list:
+
+        buff_omega, buff_cx, buff_cy, buff_v, buff_class = self.omega_buff(tracks, strategy['invite_friend'])
+        if self._omega > buff_omega:
+            buffed = False
+            target_x = self._cx + self._v * 100 - (self._w // 2)
+            target_y = self._cy - 40
+        else:
+            buffed = True
+            target_x = buff_cx + buff_v * 100
+            target_y = buff_cy - 40  # top left corner
+
+        _r = self.r(vector=state, omega=self._omega, omega_buff=self._omega_buff)
+        throw = True if _r > 0 else False
+        # x, y, throw, number
+        return [target_x, target_y, throw, 10]
+
+    def omega_buff(self, tracks, invite_friend: bool) -> float:
+        max_omega = 0.
+        max_cx = 0
+        max_cy = 0
+        max_v = 0
+        max_class = 0
+
+        for _id, _class, _conf, _cx, _cy, _w, _h, _v in tracks:
+            _current_omega = 0.
+            match _class:
+                case CI.BUFF_004: _current_omega = 2.2
+                case CI.BUFF_006: _current_omega = 2.0
+                case CI.BUFF_007: _current_omega = 2.0 if invite_friend and _cx <= 1000 else 0
+                case CI.BUFF_002: _current_omega = 2.0 if self._omega >= 1.5 else 0
+                case CI.BUFF_003: _current_omega = 2.0 if self._omega >= 1.5 else 0
+                case CI.BUFF_003: _current_omega = 2.0 if self._omega >= 1.5 and _cx <= 640 else 0
+                case _: pass
+            if _current_omega > max_omega:
+                max_omega = _current_omega
+                max_cx = _cx
+                max_cy = _cy
+                max_v = _v
+                max_class = _class
+        return max_omega, max_cx, max_cy, max_v, max_class
+            
+    @classmethod
+    def r(cls, vector: list, omega: float, omega_buff: float) -> float:
+        _omega = max(omega, omega_buff)
+        tau = - 140 / (max(101, vector[0]) - 100)
+        upsilon = (vector[1] / 250 - vector[2] / 35)
+        upsilon = 100 * (upsilon**2 if upsilon > 0 else - upsilon**2)
+        result = _omega + tau + upsilon - 0.6
+        # print(f"total: {result:.4f} | {_omega:.4f} | {tau:.4f} | {upsilon:.4f}")
+        return result
+

+ 102 - 11
tasks/Hyakkiyakou/script_task.py

@@ -13,7 +13,7 @@ from cached_property import cached_property
 # Use cmd to install: ./toolkit/python.exe -m pip install -i https://pypi.org/simple/ oashya --trusted-host pypi.org
 # update oashya:  ./toolkit/python.exe -m pip install --upgrade oashya
 from oashya.tracker import Tracker
-from oashya.labels import label2id
+from oashya.labels import label2id, CLASSINDEX as CI, id2name
 from oashya.utils import draw_tracks
 
 from module.exception import TaskEnd
@@ -63,9 +63,9 @@ class ScriptTask(GameUi, HyaSlave, SwitchOnmyoji):
             raise RequestHumanTakeover('iou_threshold should be in [0.2, 1]')
         inf_en = 'onnxruntime' if hyakkiyakou_models.inference_engine == InferenceEngine.ONNXRUNTIME else 'tensorrt'
         precision = 'fp32' if hyakkiyakou_models.model_precision == ModelPrecision.FP32 else 'int8'
-        # 这个坑后面在补
+        # 这个坑后面再补
         if inf_en == 'tensorrt' or precision == 'int8':
-            raise RequestHumanTakeover('Only support onnxruntime')
+            raise RequestHumanTakeover('Only support onnxruntime and FP32 now')
         debug_info: bool = self._config.debug_config.hya_info
         args = {
             'conf_threshold': conf,
@@ -151,6 +151,91 @@ class ScriptTask(GameUi, HyaSlave, SwitchOnmyoji):
         self.set_next_run(task='Hyakkiyakou', success=True, finish=False)
         raise TaskEnd
 
+    # ------------ 新增三个函数:用于检测 ------------
+    def _rarity_score(self, class_id: int) -> int:
+        """
+        返回一个用于比较的稀有度分数:
+        SP > SSR > SR > R > N > G
+        没有匹配到的返回 -1
+        """
+        # G(呱太)
+        if CI.MIN_G <= class_id <= CI.MAX_G:
+            return 0
+        # N
+        if CI.MIN_N <= class_id <= CI.MAX_N:
+            return 1
+        # R(排除童男/童女)
+        if (CI.MIN_R <= class_id <= CI.MAX_R) and class_id not in (CI.R_007, CI.R_008):
+            return 2
+        # SR
+        if CI.MIN_SR <= class_id <= CI.MAX_SR:
+            return 3
+        # SSR
+        if CI.MIN_SSR <= class_id <= CI.MAX_SSR:
+            return 4
+        # SP
+        if CI.MIN_SP <= class_id <= CI.MAX_SP:
+            return 5
+        # 其他(buff/未收录 等)不参与排序
+        return -1
+
+    def _detect_current_rarity(self) -> tuple[int, int]:
+        """
+        在当前截图上跑一遍 tracker,返回:
+        (最高稀有度分数, 对应的 class_id)
+        如果没检测到式神,则返回 (-1, -1)
+        """
+        # 截一张当前图
+        self.screenshot()
+        # 这里 response 随便给一个默认值即可,主线战斗里是 last_action
+        tracks = self.tracker(image=self.device.image, response=[0, 0, False, 10])
+        best_score = -1
+        best_class = -1
+        for _id, _class, _conf, _cx, _cy, _w, _h, _v in tracks:
+            score = self._rarity_score(_class)
+            if score > best_score:
+                best_score = score
+                best_class = _class
+        if best_class != -1:
+            logger.info(
+                f'Hyakki select: detect {id2name(_class)} '
+                f'with rarity score {score}'
+            )
+        else:
+            logger.warning('Hyakki select: no valid shikigami detected on title screen')
+        return best_score, best_class
+
+    def _select_best_boss(self):
+        """
+        在鬼王选择界面依次点三个候选,识别稀有度,最终选择最高稀有度的那个。
+        要求:当前已经在 I_HTITLE 画面。
+        """
+        candidates = [self.C_HSELECT_1, self.C_HSELECT_2, self.C_HSELECT_3]
+        logger.info('Start selecting boss')
+        best_idx = 0
+        best_score = -1
+        scores = []
+
+        for idx, btn in enumerate(candidates):
+            # 点一下第 idx 个候选,让它成为当前选中的式神
+            self.click(btn, interval=0.1)
+            time.sleep(1)  # 给界面一点刷新时间
+            score, cls = self._detect_current_rarity()
+            scores.append(score)
+            if score > best_score:
+                best_score = score
+                best_idx = idx
+        
+        #所以如果三个都识别失败了会选第一个
+        logger.info(f'Hyakki select scores: {scores}, choose index {best_idx + 1}') 
+
+        # 记录一下,后面如果需要兜底再点一次可以用
+        self._best_boss_button = candidates[best_idx]
+
+        # 再点一次最高稀有度那个,确保它处于选中状态
+        self.click(self._best_boss_button, interval=0.1)
+        time.sleep(0.5)
+
     def one(self):
         self.reset_state()
         if not self.appear(self.I_HACCESS):
@@ -160,16 +245,18 @@ class ScriptTask(GameUi, HyaSlave, SwitchOnmyoji):
         # start
         self.ui_click(self.I_HACCESS, self.I_HSTART, interval=2)
         self.wait_until_appear(self.I_HTITLE)
-        # 随机选一个
-        click_button = choice([self.C_HSELECT_1, self.C_HSELECT_2, self.C_HSELECT_3])
+        # 这里改成:在三个候选中选择稀有度最高的作为鬼王
+        self._best_boss_button = None
+        self._select_best_boss()
         while 1:
             self.screenshot()
             if not self.appear(self.I_HTITLE):
                 break
             if self.appear_then_click(self.I_HSTART, interval=2):
                 continue
-            if not self.appear(self.I_HSELECTED):
-                self.click(click_button, interval=2)
+            if not self.appear(self.I_HSELECTED) and getattr(self, '_best_boss_button', None) is not None:
+                self.click(self._best_boss_button, interval=2) # 保险:如果因为某些原因还没处于“已选中”状态,就再点一次最佳按钮
+                continue
         self.device.stuck_record_add('BATTLE_STATUS_S')
         # 正式开始
         logger.hr('Start Hyakkiyakou')
@@ -188,15 +275,19 @@ class ScriptTask(GameUi, HyaSlave, SwitchOnmyoji):
                 init_bean_flag = True
                 self.bean_05to10()
                 time.sleep(0.5)
+            #修改:在这里不再区分freeze,而是将状态传到decision用于执行冻结策略
+            #目前被禁用了 因为冰冻状态下检测正确率约等于0 全是蝉冰雪女 =.=
             if not self.appear(self.I_HFREEZE):
-                # --------------------------------------------------------
+                # -------------------------------------------------------
+                freeze = self.appear(self.I_HFREEZE)
                 self.slave_state = self.update_state()
                 tracks = self.tracker(image=self.device.image, response=last_action)
-                last_action = self.agent.decision(tracks=tracks, state=self.slave_state)
+                last_action = self.agent.decision(tracks=tracks, state=self.slave_state, freeze=freeze)
                 self.do_action(last_action, state=self.slave_state)
             else:
                 # TODO freeze state
                 tracks = []
+
             # debug
             if self._config.debug_config.hya_show:
                 draw_image = draw_tracks(self.device.image, tracks=tracks)
@@ -210,8 +301,8 @@ class ScriptTask(GameUi, HyaSlave, SwitchOnmyoji):
         if self._config.debug_config.hya_show:
             self.debugger.show_stop()
         if self._config.debug_config.hya_save_result:
-            # 走个动画
-            time.sleep(1.5)
+            # 走个动画 - 修改了时间以保证能截到图
+            time.sleep(2)
             self.debugger.save_result(self.device.image)
         self.ui_click(self.I_HEND, self.I_HACCESS)
         self.debugger.save_images()

BIN
tasks/Hyakkiyakou/slave/__pycache__/hya_color.cpython-310.pyc


BIN
tasks/Hyakkiyakou/slave/__pycache__/hya_device.cpython-310.pyc


BIN
tasks/Hyakkiyakou/slave/__pycache__/hya_slave.cpython-310.pyc


+ 2 - 0
tasks/Hyakkiyakou/slave/hya_slave.py

@@ -255,7 +255,9 @@ class HyaSlave(HyaDevice, HyaColor, HyakkiyakouAssets):
                     raise RequestHumanTakeover('Invite friend failed')
 
     def _invite_friend(self, button1: RuleImage, button2: RuleImage, hya_recall_activity: bool = False ) -> bool:
+        logger.info('Start clicking')
         self.ui_click(button1, button2)
+        logger.info('End clicking')
         invite_timer = Timer(8)
         invite_timer.start()
         while 1: