Explorar o código

Merge pull request #1882 from runhey/dev

Automated PR 2026.10.09
github-actions[bot] hai 1 mes
pai
achega
62340f37f1
Modificáronse 45 ficheiros con 859 adicións e 165 borrados
  1. 8 2
      assets/i18n/zh-CN.json
  2. 10 2
      dev_tools/assets_test.py
  3. 132 11
      module/atom/image.py
  4. 1 1
      module/config/config_manual.py
  5. 1 1
      module/config/config_menu.py
  6. 2 0
      module/config/config_model.py
  7. 2 0
      module/config/i18n/zh_CN.xml
  8. 1 1
      module/server/annotator_rule_schema.py
  9. 17 1
      module/server/app.py
  10. 6 1
      tasks/Component/GeneralBattle/assets.py
  11. 6 1
      tasks/Component/GeneralBattle/battle.py
  12. 77 28
      tasks/Component/GeneralBattle/battle_wait.py
  13. 10 0
      tasks/Component/GeneralBattle/config_general_battle.py
  14. 24 0
      tasks/Component/GeneralBattle/gb/click.json
  15. 9 0
      tasks/Component/GeneralBattle/gb/ocr.json
  16. 69 37
      tasks/Component/GeneralBattle/general_battle.py
  17. 13 1
      tasks/Delegation/script_task.py
  18. 11 11
      tasks/DemonEncounter/script_task.py
  19. 2 2
      tasks/EvoZone/assets.py
  20. 2 2
      tasks/EvoZone/o/image.json
  21. 8 0
      tasks/Exploration/assets.py
  22. 10 3
      tasks/Exploration/base.py
  23. 44 0
      tasks/Exploration/page.py
  24. 12 0
      tasks/Exploration/res/click.json
  25. 18 0
      tasks/Exploration/res/image.json
  26. BIN=BIN
      tasks/Exploration/res/res_check_main_title.png
  27. BIN=BIN
      tasks/Exploration/res/res_check_play_title.png
  28. 4 3
      tasks/GameUi/navigator.py
  29. 10 5
      tasks/HeroTest/script_task.py
  30. 25 0
      tasks/OtherWorldTwilight/assets.py
  31. 47 0
      tasks/OtherWorldTwilight/config.py
  32. 47 0
      tasks/OtherWorldTwilight/owt/image.json
  33. BIN=BIN
      tasks/OtherWorldTwilight/owt/owt_de_to_other_world.png
  34. BIN=BIN
      tasks/OtherWorldTwilight/owt/owt_owt_fire.png
  35. BIN=BIN
      tasks/OtherWorldTwilight/owt/owt_owt_lock.png
  36. BIN=BIN
      tasks/OtherWorldTwilight/owt/owt_owt_team.png
  37. BIN=BIN
      tasks/OtherWorldTwilight/owt/owt_owt_unlock.png
  38. 10 0
      tasks/OtherWorldTwilight/page.py
  39. 198 0
      tasks/OtherWorldTwilight/script_task.py
  40. 2 5
      tasks/TrueOrochi/assets.py
  41. 0 1
      tasks/TrueOrochi/config.py
  42. 12 35
      tasks/TrueOrochi/script_task.py
  43. 9 0
      tasks/TrueOrochi/st/image.json
  44. 0 11
      tasks/TrueOrochi/st/ocr.json
  45. BIN=BIN
      tasks/TrueOrochi/st/st_module.png

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

@@ -60,6 +60,8 @@
   "enable_switch_cultivation_drills": "修行合训开启切换御魂",
   "demon_battle_config": "逢魔战斗内切换阵容",
   "best_demon_battle_config": "极逢魔战斗内切换阵容",
+  "OtherWorldTwilight": "彼世逢魔",
+  "other_world_twilight_config": "彼世逢魔配置",
   "anti_ban": "防风控作息",
   "antiban_enable_help": "开启后启用作息约束(睡眠时间窗、累计活跃上限、强制休息),用于避免24小时不间断/深夜连续运行这类服务端可见的异常行为特征。\n注意:点击/滑动的拟人化(真实按压时长、坐标高斯化、微动、压力抖动)始终生效,不受此开关控制。",
   "sleep_start": "睡眠开始时间",
@@ -144,5 +146,9 @@
   "costume_battle_scene_type_help": "",
   "costume_shikigami_12": "拾光之窗",
   "save_touch_fish": "惠比寿的摸鱼行动",
-  "save_touch_fish_help": "默认使用全部存储按钮,主要目的是为了配合真蛇每周打一次即可获得俩次奖励(并不会节省体力)"
-}
+  "save_touch_fish_help": "默认使用全部存储按钮,主要目的是为了配合真蛇每周打一次即可获得俩次奖励(并不会节省体力)",
+  "green_mark_type": "绿标匹配方式",
+  "green_mark_type_help": "按坐标点击指定绿标,或按式神名OCR 匹配后点击",
+  "green_mark_name": "绿标式神名称",
+  "green_mark_name_help": "仅当绿标按式神名匹配时生效,填写目标式神名"
+}

+ 10 - 2
dev_tools/assets_test.py

@@ -74,12 +74,20 @@ def detect_image_detail(file: str, target: RuleImage) -> dict:
         target.roi_front[3] = int(mat.shape[0])
         message = "match" if matched else "not_match"
     else:
+        # 掩码 / 多尺度 / SIFT 走本地 test_match
         try:
             matched = bool(target.test_match(img))
-            similarity = 1.0 if matched else 0.0
+            # 优先取匹配过程记录的真实分数; SIFT 等未记录分数的方法退回 0/1
+            similarity = float(getattr(target, "last_score", -1.0))
+            if similarity < 0:
+                similarity = 1.0 if matched else 0.0
             message = "match" if matched else "not_match"
+            # 多尺度命中时带回最高分档的缩放倍数
+            scale = getattr(target, "last_scale", None)
+            if matched and scale is not None:
+                message += f" scale={float(scale):.2f}"
         except Exception as e:
-            message = f"sift_error:{e}"
+            message = f"match_error:{e}"
 
     return {
         "matched": matched,

+ 132 - 11
module/atom/image.py

@@ -22,7 +22,7 @@ class RuleImage(RuleImageMallResourceMixin):
         初始化
         :param roi_front: 前置roi
         :param roi_back: 后置roi 用于匹配的区域
-        :param method: 匹配方法 "Template matching"
+        :param method: 匹配方法 "Template matching" / "Masked template matching" / "Multi-scale template matching" / "Sift Flann"
         :param threshold: 阈值  0.8
         :param file: 相对路径, 带后缀
         """
@@ -30,6 +30,10 @@ class RuleImage(RuleImageMallResourceMixin):
         self._image = None  # 这个是匹配的目标
         self._kp = None  #
         self._des = None
+        self._mask_loaded = False  # 掩码懒加载标记: False=未加载, 加载后看 _mask
+        self._mask = None  # 掩码图, None 表示无掩码(回退普通匹配)
+        self.last_score = -1.0  # 最近一次匹配的真实分数, -1 表示本次未产生分数
+        self.last_scale = None  # 最近一次多尺度匹配命中的缩放倍数, 仅 Multi-scale 方法写入
         self.method = method
 
         self.roi_front: list = list(roi_front)
@@ -104,6 +108,18 @@ class RuleImage(RuleImageMallResourceMixin):
         """
         return self.method == "Template matching"
 
+    @cached_property
+    def is_masked_template_match(self) -> bool:
+        """
+        是否是掩码模板匹配,掩码取自同目录下 `xxx_mask.png`
+        :return:
+        """
+        return self.method == "Masked template matching"
+
+    @cached_property
+    def is_multi_scale_template_match(self) -> bool:
+        return self.method == "Multi-scale template matching"
+
     @cached_property
     def is_sift_flann(self) -> bool:
         return self.method == "Sift Flann"
@@ -124,6 +140,68 @@ class RuleImage(RuleImageMallResourceMixin):
             self.load_kp_des()
         return self._des
 
+    @property
+    def mask(self):
+        """
+        掩码图,取模板同目录下 `xxx_mask.png`(`xxx.png` -> `xxx_mask.png`)。
+        语义为「非零参与匹配,零忽略」。文件缺失、读取失败或尺寸与模板不一致时
+        返回 None,由调用方回退到普通匹配,避免一张画错尺寸的掩码直接让规则报错。
+        :return:
+        """
+        if not self._mask_loaded:
+            self._mask_loaded = True
+            path = Path(self.file)
+            mask_path = path.with_name(f"{path.stem}_mask{path.suffix}")
+            try:
+                mask = cv2.imdecode(fromfile(str(mask_path), dtype=uint8), cv2.IMREAD_GRAYSCALE)
+            except OSError:
+                mask = None
+            if mask is None:
+                logger.debug(f"{self.name} template mask unavailable, fallback to plain matching: {mask_path}")
+            elif mask.shape[:2] != self.image.shape[:2]:
+                logger.error(
+                    f"{self.name} template mask size mismatch "
+                    f"{mask.shape[:2]} != {self.image.shape[:2]}, fallback to plain matching"
+                )
+            else:
+                self._mask = mask
+        return self._mask
+
+    @staticmethod
+    def _template_is_degenerate(template: np.ndarray, mask: np.ndarray | None = None) -> bool:
+        """
+        判断模板在参与匹配的区域内是否逐通道恒为常量。
+
+        CCOEFF_NORMED 归一化时分母来自各通道的方差,参与区域内所有通道都完全没有起伏时,
+        分母才是 0,OpenCV 会走特判:无掩码时整张结果矩阵被填成 1.0(恒假阳性,且落点固定
+        在 roi_back 左上角),带掩码时整张变成 0/0 的 nan。两种都让这条规则失去意义,
+        这里提前拦掉,而不是把异常数值当成命中。
+        """
+        if template is None or template.size == 0:
+            return True
+        region = template if mask is None else template[mask > 0]
+        if region.size == 0:
+            return True
+        # 掩码取值后是 `(N, C)`、整体模板是 `(H, W, C)`、灰度图是 `(H, W)` 或 `(N,)`,
+        # 通道数只认模板本身,再统一摊平成 `(N, C)` 逐通道判断。
+        channels = 1 if template.ndim == 2 else template.shape[-1]
+        samples = region.reshape(-1, channels)
+        return all(float(samples[:, channel].std()) == 0.0 for channel in range(channels))
+
+    @staticmethod
+    def _sanitize_match_result(result: np.ndarray) -> np.ndarray:
+        """
+        压掉匹配结果矩阵里的非有限值。
+
+        源图窗口整块同色时 CCOEFF_NORMED 会算出 nan/inf:nan 会让
+        `max_val > threshold` 恒为假而静默漏检,inf 则会越过阈值并把命中位置指到随机
+        坐标(假阳性,点错位置)。这里统一替换为 -1.0,等价于「该位置判不匹配」。
+        """
+        if np.isfinite(result).all():
+            return result
+        logger.error("match result contains nan/inf (solid-color region), treated as not matched")
+        return np.nan_to_num(result, nan=-1.0, posinf=-1.0, neginf=-1.0)
+
     def corp(self, image: np.array, roi: list = None) -> np.array:
         """
         截取图片
@@ -147,7 +225,10 @@ class RuleImage(RuleImageMallResourceMixin):
         if threshold is None:
             threshold = self.threshold
 
-        if not self.is_template_match:
+        if self.is_multi_scale_template_match:
+            return self.match_multi_scale(image, threshold, scale_range=(0.6, 1.2))
+
+        if not (self.is_template_match or self.is_masked_template_match):
             return self.sift_match(image)
             # raise Exception(f"unknown method {self.method}")
 
@@ -161,8 +242,18 @@ class RuleImage(RuleImageMallResourceMixin):
             # 模板大于源图, 视为无效匹配(避免 matchTemplate 的异常行为)
             return False
 
-        res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        mask = self.mask if self.is_masked_template_match else None
+        if self._template_is_degenerate(mat, mask):
+            logger.error(f"{self.name} template is flat (no variance in matching area), treated as not matched")
+            return False
+
+        if mask is None:
+            res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        else:
+            res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED, mask=mask)
+        res = self._sanitize_match_result(res)
         min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
+        self.last_score = float(max_val)
         if self.debug_mode:
             logger.attr(self.name, f'matching score {max_val:.5f}')
 
@@ -203,6 +294,9 @@ class RuleImage(RuleImageMallResourceMixin):
         if mat is None or mat.shape[0] == 0 or mat.shape[1] == 0:
             logger.error(f"Template image is invalid: {mat.shape}")
             return False
+        if self._template_is_degenerate(mat):
+            logger.error(f"{self.name} template is flat (no variance), treated as not matched")
+            return False
 
         # 预计算模板尺寸
         mat_h, mat_w = mat.shape[:2]
@@ -211,6 +305,8 @@ class RuleImage(RuleImageMallResourceMixin):
         best_score = 0
         best_loc = None
         best_scale = 1.0
+        best_shape = None  # 最佳得分对应的是哪一档缩放尺寸, 回写 roi_front 只能用它
+        self.last_scale = None
 
         for scale in scales:
             scaled_w = int(mat_w * scale)
@@ -226,23 +322,28 @@ class RuleImage(RuleImageMallResourceMixin):
             try:
                 scaled_mat = cv2.resize(mat, (scaled_w, scaled_h))
                 res = cv2.matchTemplate(source, scaled_mat, cv2.TM_CCOEFF_NORMED)
+                res = self._sanitize_match_result(res)
                 _, max_val, _, max_loc = cv2.minMaxLoc(res)
 
                 if max_val > best_score:
                     best_score = max_val
                     best_loc = max_loc
                     best_scale = scale
+                    best_shape = (scaled_w, scaled_h)
             except Exception as e:
                 continue
 
         if self.debug_mode:
             logger.attr(self.name, f'best scale: {best_scale:.2f}, best score: {best_score:.5f}')
+        self.last_score = float(best_score)
+        if best_loc is not None:
+            self.last_scale = float(best_scale)
 
-        if best_score > threshold and best_loc is not None:
+        if best_score > threshold and best_loc is not None and best_shape is not None:
             self.roi_front[0] = best_loc[0] + self.roi_back[0]
             self.roi_front[1] = best_loc[1] + self.roi_back[1]
-            self.roi_front[2] = scaled_w
-            self.roi_front[3] = scaled_h
+            self.roi_front[2] = best_shape[0]
+            self.roi_front[3] = best_shape[1]
             return True
         else:
             return False
@@ -259,11 +360,21 @@ class RuleImage(RuleImageMallResourceMixin):
             self.roi_back = roi
         if threshold is None:
             threshold = self.threshold
-        if not self.is_template_match:
+        if not (self.is_template_match or self.is_masked_template_match):
             raise Exception(f"unknown method {self.method}")
         source = self.corp(image)
         mat = self.image
-        results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        mask = self.mask if self.is_masked_template_match else None
+        if self._template_is_degenerate(mat, mask):
+            logger.error(f"{self.name} template is flat (no variance in matching area), treated as not matched")
+            return []
+        if mask is None:
+            results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        else:
+            results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED, mask=mask)
+        results = self._sanitize_match_result(results)
+        if results.size:
+            self.last_score = float(results.max())
         locations = np.where(results >= threshold)
         matches = []
         for pt in zip(*locations[::-1]):  # (x, y) coordinates
@@ -286,11 +397,21 @@ class RuleImage(RuleImageMallResourceMixin):
             self.roi_back = roi
         if threshold is None:
             threshold = self.threshold
-        if not self.is_template_match:
+        if not (self.is_template_match or self.is_masked_template_match):
             raise Exception(f"unknown method {self.method}")
         source = self.corp(image)
         mat = self.image
-        results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        mask = self.mask if self.is_masked_template_match else None
+        if self._template_is_degenerate(mat, mask):
+            logger.error(f"{self.name} template is flat (no variance in matching area), treated as not matched")
+            return []
+        if mask is None:
+            results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        else:
+            results = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED, mask=mask)
+        results = self._sanitize_match_result(results)
+        if results.size:
+            self.last_score = float(results.max())
         locations = np.where(results >= threshold)
         matches = []
         for pt in zip(*locations[::-1]):  # (x, y) coordinates
@@ -334,7 +455,7 @@ class RuleImage(RuleImageMallResourceMixin):
 
     def test_match(self, image: np.array):
         self.debug_mode = True
-        if self.is_template_match:
+        if self.is_template_match or self.is_masked_template_match or self.is_multi_scale_template_match:
             return self.match(image)
         if self.is_sift_flann:
             return self.sift_match(image, show=True)

+ 1 - 1
module/config/config_manual.py

@@ -12,7 +12,7 @@ class ConfigManual:
         > KekkaiUtilize > KekkaiActivation > DemonEncounter
         > AreaBoss > GoldYoukai > ExperienceYoukai > Nian > Tako > AutoCheckinBigGod > RealmRaid > RyouToppa > DailyTrifles > Exploration
         > Dokan > AbyssShadows > Hunt > GuildBanquet > DemonRetreat > GuildActivityMonitor
-        > Orochi > OrochiMoans > OrochiJudgement > Sougenbi > FallenSun > EternitySea > SixRealms
+        > Orochi > OrochiMoans > OrochiJudgement > Sougenbi > FallenSun > EternitySea > SixRealms > OtherWorldTwilight
         > ActivityShikigami > BudokaiTournament > WantedQuests
         > BondlingFairyland > EvoZone > GoryouRealm > HeroTest
         > CollectiveMissions

+ 1 - 1
module/config/config_menu.py

@@ -19,7 +19,7 @@ class ConfigMenu:
         # 脚本设置
         self.menu['Script'] = ['Script', 'Restart', 'GlobalGame']
         # 刷御魂
-        self.menu["Soul Zones"] = ['Orochi', 'Sougenbi', 'FallenSun', 'EternitySea', 'SixRealms']
+        self.menu["Soul Zones"] = ['Orochi', 'Sougenbi', 'FallenSun', 'EternitySea', 'SixRealms', 'OtherWorldTwilight']
         # 日常的任务
         self.menu["Daily Task"] = ['DailyTrifles', 'AreaBoss', 'GoldYoukai', 'ExperienceYoukai', 'Nian',
                                    'TalismanPass', 'DemonEncounter', 'Pets', 'SoulsTidy', 'Delegation', 'WantedQuests',

+ 2 - 0
module/config/config_model.py

@@ -44,6 +44,7 @@ from tasks.Sougenbi.config import Sougenbi
 from tasks.FallenSun.config import FallenSun
 from tasks.EternitySea.config import EternitySea
 from tasks.SixRealms.config import SixRealms
+from tasks.OtherWorldTwilight.config import OtherWorldTwilight
 from tasks.RealmRaid.config import RealmRaid
 from tasks.CollectiveMissions.config import CollectiveMissions
 from tasks.Hunt.config import Hunt
@@ -116,6 +117,7 @@ class ConfigModel(ConfigBase):
     fallen_sun: FallenSun = Field(default_factory=FallenSun)
     eternity_sea: EternitySea = Field(default_factory=EternitySea)
     six_realms: SixRealms = Field(default_factory=SixRealms)
+    other_world_twilight: OtherWorldTwilight = Field(default_factory=OtherWorldTwilight)
 
     # 这些是活动的
     activity_shikigami: ActivityShikigami = Field(default_factory=ActivityShikigami)

+ 2 - 0
module/config/i18n/zh_CN.xml

@@ -170,6 +170,7 @@
     <message><source>Sougenbi</source><translation>业原火</translation></message>
     <message><source>FallenSun</source><translation>日轮之城</translation></message>
     <message><source>EternitySea</source><translation>永生之海</translation></message>
+    <message><source>OtherWorldTwilight</source><translation>彼世逢魔</translation></message>
 	<message><source>GlobalGame</source><translation>全局游戏设置</translation></message>
 	<message><source>RealmRaid</source><translation>个人突破</translation></message>
 	<message><source>RyouToppa</source><translation>寮突破</translation></message>
@@ -218,6 +219,7 @@
     <message><source>Sougenbi</source><translation>业原火</translation></message>
     <message><source>FallenSun</source><translation>日轮之城</translation></message>
     <message><source>EternitySea</source><translation>永生之海</translation></message>
+    <message><source>OtherWorldTwilight</source><translation>彼世逢魔</translation></message>
 	<message><source>GlobalGame</source><translation>全局游戏设置</translation></message>
 	<message><source>RealmRaid</source><translation>个人突破</translation></message>
 	<message><source>RyouToppa</source><translation>寮突破</translation></message>

+ 1 - 1
module/server/annotator_rule_schema.py

@@ -29,7 +29,7 @@ RULE_TYPE_SCHEMAS: OrderedDict[str, dict[str, Any]] = OrderedDict(
                     "label": "method",
                     "control": "select",
                     "default": "Template matching",
-                    "options": ["Template matching", "Sift Flann"],
+                    "options": ["Template matching", "Masked template matching", "Multi-scale template matching", "Sift Flann"],
                 },
                 {
                     "key": "threshold",

+ 17 - 1
module/server/app.py

@@ -46,8 +46,24 @@ app.include_router(script_app)
 app.include_router(tool_app)
 
 annotator_static_dir = Path(__file__).resolve().parent / "web" / "annotator" / "static"
+
+
+class NoCacheStaticFiles(StaticFiles):
+    """
+    静态资源响应加 Cache-Control: no-cache:
+    浏览器仍可缓存,但每次都携带 ETag 回源校验,未变更返回 304。
+    StaticFiles 默认不下发 Cache-Control,Edge 等按启发式缓存旧 JS,
+    前端更新后页面会继续执行旧脚本(表现为控件读不到数据/点了没反应)。
+    """
+
+    def file_response(self, *args, **kwargs):
+        response = super().file_response(*args, **kwargs)
+        response.headers["Cache-Control"] = "no-cache"
+        return response
+
+
 if annotator_static_dir.exists():
-    app.mount("/tool/annotator/static", StaticFiles(directory=str(annotator_static_dir)), name="annotator_static")
+    app.mount("/tool/annotator/static", NoCacheStaticFiles(directory=str(annotator_static_dir)), name="annotator_static")
 
 
 async def on_startup():

+ 6 - 1
tasks/Component/GeneralBattle/assets.py

@@ -64,10 +64,13 @@ class GeneralBattleAssets:
 	C_GREEN_MARK_AREA = RuleClick(roi_front=(0,0,1280,720), roi_back=(0,0,1280,720), name="green_mark_area")
 	# 战斗的时候有一定的概率随机点击 
 	C_RANDOM_CLICK = RuleClick(roi_front=(104,79,1050,507), roi_back=(255,65,100,100), name="random_click")
-	# 结算安全随机点击区域(移植自mine) 
+	# 左边随机点击 
 	C_RANDOM_LEFT = RuleClick(roi_front=(17,104,55,370), roi_back=(17,104,55,370), name="random_left")
+	# 右边随机点击 
 	C_RANDOM_RIGHT = RuleClick(roi_front=(1185,115,79,388), roi_back=(1185,115,79,388), name="random_right")
+	# 上边随机点击 
 	C_RANDOM_TOP = RuleClick(roi_front=(250,58,868,68), roi_back=(250,58,868,68), name="random_top")
+	# 下边随机点击 
 	C_RANDOM_BOTTOM = RuleClick(roi_front=(462,599,492,78), roi_back=(462,599,492,78), name="random_bottom")
 
 
@@ -170,6 +173,8 @@ class GeneralBattleAssets:
 	O_PRESET_FULL = RuleOcr(roi=(20,620,60,80), area=(20,620,60,80), mode="Single", method="Default", keyword="预设", name="preset_full")
 	# 已标记 
 	O_BOSS_MARK = RuleOcr(roi=(379,44,50,21), area=(379,44,50,21), mode="Single", method="Default", keyword="已标记", name="boss_mark")
+	# 绿标区域 
+	O_GREEN_MARK_AREA = RuleOcr(roi=(84,256,1116,308), area=(84,256,1116,308), mode="Full", method="Default", keyword="", name="green_mark_area")
 
 
 	# Swipe Rule Assets

+ 6 - 1
tasks/Component/GeneralBattle/battle.py

@@ -90,7 +90,12 @@ class Battle(BattleWait):
                 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)
+            options['green'] = OptionGreenDefault(
+                green_enable=True,
+                green_mark=conf.green_mark,
+                green_mark_type=conf.green_mark_type,
+                green_mark_name=conf.green_mark_name,
+            )
         if conf.random_click_swipt_enable:
             strategies['randomclick'] = 'default'
             options['randomclick'] = OptionRandomclickDefault()

+ 77 - 28
tasks/Component/GeneralBattle/battle_wait.py

@@ -77,6 +77,7 @@ import random
 import time
 import copy
 import math
+import difflib
 from copy import deepcopy
 
 
@@ -94,7 +95,7 @@ from module.base.utils import get_color, color_similar
 
 from tasks.base_task import BaseTask
 from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
-from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType
+from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GreenMarkEnum
 
 
 P = ParamSpec('P')
@@ -195,6 +196,8 @@ class OptionPresetDefault:
 class OptionGreenDefault:
     green_enable: bool = False
     green_mark: GreenMarkType = GreenMarkType.GREEN_LEFT1
+    green_mark_type: GreenMarkEnum = GreenMarkEnum.CHOOSE
+    green_mark_name: str = ''
 
 
 @dataclass
@@ -1372,39 +1375,85 @@ class BattleWait(BaseTask, GeneralBattleAssets):
                 disable=('green',),
             )
 
-        logger.info("Green is enable")
-        x, y = None, None
-        match pri_options.green_mark:
-            case GreenMarkType.GREEN_LEFT1:
-                x, y = self.C_GREEN_LEFT_1.coord()
-                logger.info("Green left 1")
-            case GreenMarkType.GREEN_LEFT2:
-                x, y = self.C_GREEN_LEFT_2.coord()
-                logger.info("Green left 2")
-            case GreenMarkType.GREEN_LEFT3:
-                x, y = self.C_GREEN_LEFT_3.coord()
-                logger.info("Green left 3")
-            case GreenMarkType.GREEN_LEFT4:
-                x, y = self.C_GREEN_LEFT_4.coord()
-                logger.info("Green left 4")
-            case GreenMarkType.GREEN_LEFT5:
-                x, y = self.C_GREEN_LEFT_5.coord()
-                logger.info("Green left 5")
-            case GreenMarkType.GREEN_MAIN:
-                x, y = self.C_GREEN_MAIN.coord()
-                logger.info("Green main")
-
         # 等待那个准备的消失
         while 1:
             self.screenshot()
             if not self.appear(self.I_PREPARE_HIGHLIGHT):
                 break
 
-        # 判断有无坐标的偏移
-        self.appear_then_click(self.I_LOCAL)
-        time.sleep(0.3)
-        # 点击绿标
-        self.device.click(x, y)
+        if pri_options.green_mark_type == GreenMarkEnum.NAME:
+            name = pri_options.green_mark_name
+            if not name:
+                logger.warning("Green mark name is empty")
+            else:
+                timeout_timer = Timer(6).start()
+                best = {
+                    'name': '',
+                    'x': -1,
+                    'y': -1,
+                    'similarity': 0.0,
+                }
+                while not timeout_timer.reached():
+                    self.screenshot()
+                    results = self.O_GREEN_MARK_AREA.detect_and_ocr(self.device.image)
+                    for ret in results:
+                        similarity = difflib.SequenceMatcher(
+                            None,
+                            ret.ocr_text,
+                            name,
+                        ).ratio()
+                        if similarity > best['similarity']:
+                            x = self.O_GREEN_MARK_AREA.roi[0] + ret.box[0, 0] + 5
+                            y = self.O_GREEN_MARK_AREA.roi[1] + ret.box[0, 1] + 30
+                            best = {
+                                'name': ret.ocr_text,
+                                'x': min(1279, x),
+                                'y': min(719, y),
+                                'similarity': similarity,
+                            }
+                    if best['similarity'] > 0.5:
+                        logger.info(
+                            f'Green name success, text: {best["name"]}'
+                            f'[{best["similarity"]:.2f}]'
+                        )
+                        self.device.click(
+                            best['x'],
+                            best['y'],
+                            control_name=best['name'],
+                        )
+                        break
+                else:
+                    logger.warning(
+                        f'Green name failed, best text: {best["name"]}'
+                        f'[{best["similarity"]:.2f}]'
+                    )
+        else:
+            x, y = None, None
+            match pri_options.green_mark:
+                case GreenMarkType.GREEN_LEFT1:
+                    x, y = self.C_GREEN_LEFT_1.coord()
+                    logger.info("Green left 1")
+                case GreenMarkType.GREEN_LEFT2:
+                    x, y = self.C_GREEN_LEFT_2.coord()
+                    logger.info("Green left 2")
+                case GreenMarkType.GREEN_LEFT3:
+                    x, y = self.C_GREEN_LEFT_3.coord()
+                    logger.info("Green left 3")
+                case GreenMarkType.GREEN_LEFT4:
+                    x, y = self.C_GREEN_LEFT_4.coord()
+                    logger.info("Green left 4")
+                case GreenMarkType.GREEN_LEFT5:
+                    x, y = self.C_GREEN_LEFT_5.coord()
+                    logger.info("Green left 5")
+                case GreenMarkType.GREEN_MAIN:
+                    x, y = self.C_GREEN_MAIN.coord()
+                    logger.info("Green main")
+
+            # 判断有无坐标的偏移
+            self.appear_then_click(self.I_LOCAL)
+            time.sleep(0.3)
+            # 点击绿标
+            self.device.click(x, y)
         state.done = True
         return runtime.hook_enabled_update(
             enable=(),

+ 10 - 0
tasks/Component/GeneralBattle/config_general_battle.py

@@ -13,6 +13,12 @@ class GreenMarkType(str, Enum):
     GREEN_LEFT5 = 'green_left5'
     GREEN_MAIN = 'green_main'
 
+class GreenMarkEnum(str, Enum):
+    # 按 green_mark 指定的坐标点击
+    CHOOSE = 'choose'
+    # 按式神名OCR 匹配后点击
+    NAME = 'name'
+
 class GeneralBattleConfig(BaseModel):
 
     # 是否锁定阵容, 有些的战斗是外边的锁定阵容甚至有些的战斗没有锁定阵容的
@@ -43,6 +49,10 @@ class GeneralBattleConfig(BaseModel):
     green_enable: bool = Field(default=False, description='green_enable_help')
     # 选哪一个绿标
     green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='green_mark_help')
+    # 绿标按坐标还是按式神名点击
+    green_mark_type: GreenMarkEnum = Field(default=GreenMarkEnum.CHOOSE, description='green_mark_type_help')
+    # 绿标式神的名称
+    green_mark_name: str = Field(default='', description='green_mark_name_help')
 
     # 是否启动战斗时随机点击或者随机滑动
     random_click_swipt_enable: bool = Field(default=False, description='random_click_swipt_enable_help')

+ 24 - 0
tasks/Component/GeneralBattle/gb/click.json

@@ -112,5 +112,29 @@
     "roiFront": "104,79,1050,507",
     "roiBack": "255,65,100,100",
     "description": "战斗的时候有一定的概率随机点击"
+  },
+  {
+    "itemName": "random_left",
+    "roiFront": "17,104,55,370",
+    "roiBack": "17,104,55,370",
+    "description": "左边随机点击"
+  },
+  {
+    "itemName": "random_right",
+    "roiFront": "1185,115,79,388",
+    "roiBack": "1185,115,79,388",
+    "description": "右边随机点击"
+  },
+  {
+    "itemName": "random_top",
+    "roiFront": "250,58,868,68",
+    "roiBack": "250,58,868,68",
+    "description": "上边随机点击"
+  },
+  {
+    "itemName": "random_bottom",
+    "roiFront": "462,599,492,78",
+    "roiBack": "462,599,492,78",
+    "description": "下边随机点击"
   }
 ]

+ 9 - 0
tasks/Component/GeneralBattle/gb/ocr.json

@@ -34,5 +34,14 @@
     "method": "Default",
     "keyword": "已标记",
     "description": "已标记"
+  },
+  {
+    "itemName": "green_mark_area",
+    "roiFront": "84,256,1116,308",
+    "roiBack": "84,256,1116,308",
+    "mode": "Full",
+    "method": "Default",
+    "keyword": "",
+    "description": "绿标区域"
   }
 ]

+ 69 - 37
tasks/Component/GeneralBattle/general_battle.py

@@ -3,6 +3,7 @@
 # github https://github.com/runhey
 import time
 import random
+import difflib
 from time import sleep
 
 import cv2
@@ -10,9 +11,9 @@ from module.base.timer import Timer
 
 from module.base.utils import get_color, color_similar
 from tasks.base_task import BaseTask
-from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GeneralBattleConfig
+from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GreenMarkEnum, GeneralBattleConfig
 from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
-from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GeneralBattleConfig
+from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType, GreenMarkEnum, GeneralBattleConfig
 from tasks.Component.GeneralBuff.config_buff import BuffClass
 from tasks.Component.GeneralBuff.general_buff import GeneralBuff
 from tasks.Component.GeneralBattle.battle_wait import BattleWait
@@ -317,47 +318,78 @@ class GeneralBattle(BattleWait, GeneralBuff):
         """
         return False
 
-    def green_mark(self, enable: bool = False, mark_mode: GreenMarkType = GreenMarkType.GREEN_MAIN):
+    def green_mark(self, enable: bool = False, mark_mode: GreenMarkType = GreenMarkType.GREEN_MAIN,
+                   green_mark_type: GreenMarkEnum = GreenMarkEnum.CHOOSE, green_mark_name: str = ''):
         """
         绿标, 如果不使能就直接返回
         :param enable:
-        :param mark_mode:
+        :param mark_mode:绿标目标位置
+        :param green_mark_type: 按坐标还是按式神名点击
+        :param green_mark_name: 式神名,仅 green_mark_type 为 NAME 时生效
         :return:
         """
-        if enable:
-            logger.info("Green is enable")
-            x, y = None, None
-            match mark_mode:
-                case GreenMarkType.GREEN_LEFT1:
-                    x, y = self.C_GREEN_LEFT_1.coord()
-                    logger.info("Green left 1")
-                case GreenMarkType.GREEN_LEFT2:
-                    x, y = self.C_GREEN_LEFT_2.coord()
-                    logger.info("Green left 2")
-                case GreenMarkType.GREEN_LEFT3:
-                    x, y = self.C_GREEN_LEFT_3.coord()
-                    logger.info("Green left 3")
-                case GreenMarkType.GREEN_LEFT4:
-                    x, y = self.C_GREEN_LEFT_4.coord()
-                    logger.info("Green left 4")
-                case GreenMarkType.GREEN_LEFT5:
-                    x, y = self.C_GREEN_LEFT_5.coord()
-                    logger.info("Green left 5")
-                case GreenMarkType.GREEN_MAIN:
-                    x, y = self.C_GREEN_MAIN.coord()
-                    logger.info("Green main")
-
-            # 等待那个准备的消失
-            while 1:
-                self.screenshot()
-                if not self.appear(self.I_PREPARE_HIGHLIGHT):
-                    break
-
-            # 判断有无坐标的偏移
-            self.appear_then_click(self.I_LOCAL)
+        if not enable:
+            return
+        logger.info("Green is enable")
+        self.device.screenshot_interval_set()
+        match green_mark_type:
+            case GreenMarkEnum.CHOOSE:
+                self.green_mark_choose(mark_mode)
+            case GreenMarkEnum.NAME:
+                self.green_mark_name(green_mark_name)
+        self.device.screenshot_interval_set('combat')
+
+    def green_mark_choose(self, mark_mode: GreenMarkType = GreenMarkType.GREEN_MAIN):
+        x, y = None, None
+        match mark_mode:
+            case GreenMarkType.GREEN_LEFT1:
+                x, y = self.C_GREEN_LEFT_1.coord()
+                logger.info("Green left 1")
+            case GreenMarkType.GREEN_LEFT2:
+                x, y = self.C_GREEN_LEFT_2.coord()
+                logger.info("Green left 2")
+            case GreenMarkType.GREEN_LEFT3:
+                x, y = self.C_GREEN_LEFT_3.coord()
+                logger.info("Green left 3")
+            case GreenMarkType.GREEN_LEFT4:
+                x, y = self.C_GREEN_LEFT_4.coord()
+                logger.info("Green left 4")
+            case GreenMarkType.GREEN_LEFT5:
+                x, y = self.C_GREEN_LEFT_5.coord()
+                logger.info("Green left 5")
+            case GreenMarkType.GREEN_MAIN:
+                x, y = self.C_GREEN_MAIN.coord()
+                logger.info("Green main")
+        while 1:
+            self.screenshot()
+            if not self.appear(self.I_PREPARE_HIGHLIGHT):
+                break
+        if self.appear_then_click(self.I_LOCAL):
             time.sleep(0.3)
-            # 点击绿标
-            self.device.click(x, y)
+        self.device.click(x, y)
+
+    def green_mark_name(self, name: str = ''):
+        if name == '':
+            logger.warning("Green mark name is empty")
+            return
+        timeout_timer = Timer(6).start()
+        best = {'name': '', 'x': -1, 'y': -1, 'similarity': 0.0}
+        while not timeout_timer.reached():
+            self.screenshot()
+            results = self.O_GREEN_MARK_AREA.detect_and_ocr(self.device.image)
+            for ret in results:
+                similarity = difflib.SequenceMatcher(None, ret.ocr_text, name).ratio()
+                if similarity > best['similarity']:
+                    x = self.O_GREEN_MARK_AREA.roi[0] + ret.box[0, 0] + 5
+                    y = self.O_GREEN_MARK_AREA.roi[1] + ret.box[0, 1] + 30
+                    x = 1280 if x > 1280 else x
+                    y = 720 if y > 720 else y
+                    best = {'name': ret.ocr_text, 'x': x, 'y': y, 'similarity': similarity}
+            if best['similarity'] > 0.5:
+                logger.info(f'Green name success, text: {best["name"]}[{best["similarity"]:.2f}]')
+                self.device.click(best['x'], best['y'], control_name=best['name'])
+                return
+        logger.warning(f'Green name failed, best text: {best["name"]}[{best["similarity"]:.2f}]')
 
     def switch_preset_team(self, enable: bool = False, preset_group: int = 1, preset_team: int = 1):
         """

+ 13 - 1
tasks/Delegation/script_task.py

@@ -121,7 +121,19 @@ class ScriptTask(GameUi, DelegationAssets):
                 continue
             if check_timer.reached():
                 break
-            if self.ocr_appear_click(self.O_D_DONE, interval=1):
+            # O_D_DONE 命中的是卡片上“完成”缎带,可点的领取位置在其正下方同样大小的一块
+            if self.ocr_appear(self.O_D_DONE, interval=1):
+                # 同一帧里可能有多张卡都显示“完成”,此时 Full 模式会把多个命中框合并成一个,
+                # 合并框正下方不一定是可点的领取位置;这里取单个命中框,点它正下方同样大小的一块
+                results = self.O_D_DONE.detect_and_ocr(self.device.image, logDisplay=False)
+                index_list = self.O_D_DONE.filter(results, self.O_D_DONE.keyword) if results else None
+                if index_list:
+                    box = results[index_list[0]].box
+                    x = box[0, 0] + self.O_D_DONE.roi[0]
+                    y = box[0, 1] + self.O_D_DONE.roi[1]
+                    w = box[1, 0] - box[0, 0]
+                    h = box[2, 1] - box[0, 1]
+                    self.device.click(x=x + w / 2, y=y + h + h / 2, control_name=self.O_D_DONE.name)
                 check_timer.reset()
                 continue
 

+ 11 - 11
tasks/DemonEncounter/script_task.py

@@ -9,13 +9,13 @@ from cached_property import cached_property
 from datetime import datetime, timedelta
 
 from module.logger import logger
-from module.exception import TaskEnd
+from module.exception import GameStuckError, TaskEnd
 from module.base.timer import Timer
 
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
 from tasks.DemonEncounter.config import BossType, DemonEncounter, convert_to_general_battle_config
 from tasks.GameUi.game_ui import GameUi
-from tasks.GameUi.page import page_demon_encounter, page_demon_encounter_realworld, page_shikigami_records
+from tasks.GameUi.page import page_town, page_demon_encounter_realworld, page_shikigami_records
 from tasks.DemonEncounter.assets import DemonEncounterAssets
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
 from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
@@ -108,8 +108,8 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
                     self.appear_then_click(self.I_DE_LOCATION, interval=2)
                     time.sleep(1)
 
-                # 最多重新执行两轮“逢魔/极逢魔 -> 地图中央首领”的完整流程。
-                for search_attempt in range(1, 3):
+                # 最多重新执行三轮“逢魔/极逢魔 -> 地图中央首领”的完整流程。
+                for search_attempt in range(1, 4):
                     self.device.click_record_clear()
                     self.screenshot()
                     if self.appear(self.I_BOSS_FIRE) or self.appear(self.I_BEST_BOSS_FIRE):
@@ -121,14 +121,14 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
                     if not self.appear_then_click(search_button, interval=2):
                         raise GameStuckError(f'Cannot find {boss_name} search button')
                     logger.info(
-                        f'Finding {boss_name}, attempt {search_attempt}/2 '
+                        f'Finding {boss_name}, attempt {search_attempt}/3 '
                         f'(re-enter round {reenter_round}/3)...'
                     )
                     time.sleep(1)
 
-                    # 每轮点击地图中央框选的红色“集结”区域至多两次,
+                    # 每轮点击地图中央框选的红色“集结”区域至多三次,
                     # 每次等待集结挑战标志5秒。
-                    for center_attempt in range(1, 3):
+                    for center_attempt in range(1, 4):
                         self.click(self.C_DM_BOSS_CLICK, interval=2)
                         deadline = time.monotonic() + 5
                         while time.monotonic() < deadline:
@@ -136,13 +136,13 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
                             if self.appear(self.I_BOSS_FIRE) or self.appear(self.I_BEST_BOSS_FIRE):
                                 logger.info(
                                     f'{boss_name} gather appeared after center click '
-                                    f'{center_attempt}/2'
+                                    f'{center_attempt}/3'
                                 )
                                 return True
                             time.sleep(0.2)
                         logger.warning(
                             f'{boss_name} gather did not appear after center click '
-                            f'{center_attempt}/2'
+                            f'{center_attempt}/3'
                         )
 
                     # 本轮失败,返回逢魔地图,重新点击逢魔/极逢魔进行下一轮搜寻。
@@ -156,9 +156,9 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
                                 break
                             time.sleep(0.2)
 
-                # 2次搜索都没找到: 重进地图清状态, 最多3轮
+                # 3次搜索都没找到: 重进地图清状态, 最多3轮
                 logger.info(f'Boss not found, re-enter demon encounter map (round {reenter_round}/3)')
-                self.goto_page(page_demon_encounter)
+                self.goto_page(page_town)
                 self.goto_page(page_demon_encounter_realworld)
 
             raise GameStuckError(

+ 2 - 2
tasks/EvoZone/assets.py

@@ -16,9 +16,9 @@ class EvoZoneAssets:
 	# 组队 
 	I_FORM_TEAM = RuleImage(roi_front=(959,580,100,100), roi_back=(916,572,156,130), threshold=0.8, method="Template matching", file="./tasks/EvoZone/o/o_form_team.png")
 	# description 
-	I_EVOZONE_LOCK = RuleImage(roi_front=(700,655,31,32), roi_back=(690,648,53,54), threshold=0.8, method="Template matching", file="./tasks/EvoZone/o/o_evozone_lock.png")
+	I_EVOZONE_LOCK = RuleImage(roi_front=(700,655,31,32), roi_back=(613,614,155,91), threshold=0.8, method="Template matching", file="./tasks/EvoZone/o/o_evozone_lock.png")
 	# description 
-	I_EVOZONE_UNLOCK = RuleImage(roi_front=(701,657,26,29), roi_back=(695,650,43,45), threshold=0.8, method="Template matching", file="./tasks/EvoZone/o/o_evozone_unlock.png")
+	I_EVOZONE_UNLOCK = RuleImage(roi_front=(701,657,26,29), roi_back=(609,623,170,89), threshold=0.8, method="Template matching", file="./tasks/EvoZone/o/o_evozone_unlock.png")
 	# 点击挑战 
 	I_EVOZONE_FIRE = RuleImage(roi_front=(1127,568,131,124), roi_back=(1127,568,131,124), threshold=0.6, method="Template matching", file="./tasks/EvoZone/o/o_evozone_fire.png")
 	# 式神录 

+ 2 - 2
tasks/EvoZone/o/image.json

@@ -21,7 +21,7 @@
     "itemName": "evozone_lock",
     "imageName": "o_evozone_lock.png",
     "roiFront": "700,655,31,32",
-    "roiBack": "690,648,53,54",
+    "roiBack": "613,614,155,91",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"
@@ -30,7 +30,7 @@
     "itemName": "evozone_unlock",
     "imageName": "o_evozone_unlock.png",
     "roiFront": "701,657,26,29",
-    "roiBack": "695,650,43,45",
+    "roiBack": "609,623,170,89",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"

+ 8 - 0
tasks/Exploration/assets.py

@@ -68,6 +68,10 @@ class ExplorationAssets:
 	C_CLICK_ROTATE_4 = RuleClick(roi_front=(921,590,21,21), roi_back=(921,590,21,21), name="click_rotate_4")
 	# 随机点 
 	C_SAFE_RANDOM = RuleClick(roi_front=(0,0,111,12), roi_back=(0,0,111,12), name="safe_random")
+	# 探索大地图 · 主线 tab 标题("章"字锚点)点击区域 
+	C_CLICK_MAIN_TITLE = RuleClick(roi_front=(1070,174,77,28), roi_back=(1070,174,77,28), name="click_main_title")
+	# 探索大地图 · 玩法 tab 标题("御魂"标题锚点)点击区域 
+	C_CLICK_PALY_TITLE = RuleClick(roi_front=(1178,172,77,28), roi_back=(1178,172,77,28), name="click_paly_title")
 
 
 	# Image Rule Assets
@@ -127,6 +131,10 @@ class ExplorationAssets:
 	I_EXP_ARROW_LEFT = RuleImage(roi_front=(1244,115,18,26), roi_back=(1178,78,100,100), threshold=0.8, method="Template matching", file="./tasks/Exploration/res/res_exp_arrow_left.png")
 	# 战斗中的队友标识 
 	I_TEAM_EMOJI_FIGHT = RuleImage(roi_front=(38,405,37,37), roi_back=(18,386,74,75), threshold=0.8, method="Template matching", file="./tasks/Exploration/res/res_team_emoji_fight.png")
+	# 探索大地图 · 主线 tab 标题锚点("章"字,仅主线 tab 命中,玩法 tab 不命中) 
+	I_CHECK_MAIN_TITLE = RuleImage(roi_front=(1150,457,32,32), roi_back=(1069,222,113,336), threshold=0.85, method="Template matching", file="./tasks/Exploration/res/res_check_main_title.png")
+	# 探索大地图 · 玩法 tab 标题锚点("御魂"标题,仅玩法 tab 命中,主线 tab 不命中) 
+	I_CHECK_PLAY_TITLE = RuleImage(roi_front=(1073,214,40,32), roi_back=(1065,210,190,316), threshold=0.85, method="Template matching", file="./tasks/Exploration/res/res_check_play_title.png")
 
 
 	# Long Click Rule Assets

+ 10 - 3
tasks/Exploration/base.py

@@ -16,7 +16,8 @@ from tasks.Exploration.assets import ExplorationAssets
 from tasks.Exploration.config import ChooseRarity, AutoRotate, AttackNumber, UpType
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
 from tasks.GameUi.game_ui import GameUi
-from tasks.GameUi.page import page_exploration, page_shikigami_records, page_main
+from tasks.GameUi.page import page_shikigami_records, page_main
+import tasks.Exploration.page as pages
 from tasks.RealmRaid.script_task import ScriptTask as RealmRaidScriptTask
 from tasks.Utils.config_enum import ShikigamiClass
 
@@ -112,8 +113,9 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
                 self.exp_100()
             self.close_buff()
 
-        # 探索页面
-        self.goto_page(page_exploration)
+        # 探索页面(大地图始终处于主线/玩法 tab 之一,裸 page_exploration 永远被 prio 60 的 tab 页遮蔽、
+        # 无法作为当前页抵达,故直接进入主线 tab)
+        self.goto_page(pages.page_mainline)
 
     def post_process(self):
         self.wait_until_stable(self.I_UI_BACK_RED)
@@ -133,6 +135,11 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
 
     # 打开指定的章节:
     def open_expect_level(self):
+        # 选关依赖主线 tab 右侧的章节列表(I_E_EXPLORATION_CLICK + 章节名 OCR)。
+        # 探索大地图常驻「主线/玩法」之一,若停在玩法 tab 不选回主线,右边会是御魂/今日掉落等模块名,
+        # I_E_EXPLORATION_CLICK 不出现、OCR 交集为空 → 一直滑屏卡死。故进选关前无条件确保主线 tab。
+        self.goto_page(pages.page_mainline)
+
         swipeCount = 0
         while 1:
             # 探索的 config

+ 44 - 0
tasks/Exploration/page.py

@@ -0,0 +1,44 @@
+from tasks.Exploration.assets import ExplorationAssets
+from tasks.GameUi.assets import GameUiAssets
+from tasks.GameUi.page import all_of, page_exploration
+from tasks.GameUi.page_definition import Page
+
+
+def inherit_transitions(source: Page, *targets: Page) -> None:
+    """把 source 的全部出边复制给 targets(tab 页继承大地图出口,动作与 tab 状态无关)。
+
+    跳过目标页自身(自环防护),若目标页已有到同一目的地的边则不重复添加。
+    """
+    for target in targets:
+        for transition in source.transitions:
+            if transition.destination == target:
+                continue
+            if any(item.destination == transition.destination for item in target.transitions):
+                continue
+            target.connect(
+                transition.destination,
+                transition.action,
+                cost=transition.cost,
+                on_enter_success=transition.on_enter_success,
+                on_enter_failure=transition.on_enter_failure,
+                on_leave_success=transition.on_leave_success,
+                on_leave_failure=transition.on_leave_failure,
+            )
+
+
+# 探索大地图 · 主线 tab("章"字锚点,优先级高于 page_exploration 的兜底识别)
+page_mainline = Page(all_of(GameUiAssets.I_CHECK_EXPLORATION, ExplorationAssets.I_CHECK_MAIN_TITLE), priority=60)
+# 探索大地图 · 玩法 tab("御魂"标题锚点)
+page_gameplay = Page(all_of(GameUiAssets.I_CHECK_EXPLORATION, ExplorationAssets.I_CHECK_PLAY_TITLE), priority=60)
+
+# 大地图 tab 互切(固定坐标点击,幂等)
+page_mainline.connect(page_gameplay, ExplorationAssets.C_CLICK_PALY_TITLE, key="page_mainline->page_gameplay")
+page_gameplay.connect(page_mainline, ExplorationAssets.C_CLICK_MAIN_TITLE, key="page_gameplay->page_mainline")
+
+# 大地图通用态 -> tab 桥接边:page_exploration 是入口桥 + 导航缓存页,
+# tab 页必须从这里可达才能从庭院方向进入,也保证 tab 页能切回通用态。
+page_exploration.connect(page_mainline, ExplorationAssets.C_CLICK_MAIN_TITLE, key="page_exploration->page_mainline")
+page_exploration.connect(page_gameplay, ExplorationAssets.C_CLICK_PALY_TITLE, key="page_exploration->page_gameplay")
+
+# tab 页继承大地图全部出口(回庭院、各区域入口等),此后 page_exploration 新增出边自动跟随
+inherit_transitions(page_exploration, page_mainline, page_gameplay)

+ 12 - 0
tasks/Exploration/res/click.json

@@ -52,5 +52,17 @@
     "roiFront": "0,0,111,12",
     "roiBack": "0,0,111,12",
     "description": "随机点"
+  },
+  {
+    "itemName": "click_main_title",
+    "roiFront": "1070,174,77,28",
+    "roiBack": "1070,174,77,28",
+    "description": "点击探索大地图主线tab标题"
+  },
+  {
+    "itemName": "click_paly_title",
+    "roiFront": "1178,172,77,28",
+    "roiBack": "1178,172,77,28",
+    "description": "点击探索大地图玩法tab标题"
   }
 ]

+ 18 - 0
tasks/Exploration/res/image.json

@@ -250,5 +250,23 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "探索章节切换文件夹图标(移植自mine)"
+  },
+  {
+    "itemName": "check_main_title",
+    "imageName": "res_check_main_title.png",
+    "roiFront": "1150,457,32,32",
+    "roiBack": "1069,222,113,336",
+    "method": "Template matching",
+    "threshold": 0.85,
+    "description": "探索大地图主线tab标题锚点(章字)"
+  },
+  {
+    "itemName": "check_play_title",
+    "imageName": "res_check_play_title.png",
+    "roiFront": "1073,214,40,32",
+    "roiBack": "1065,210,190,316",
+    "method": "Template matching",
+    "threshold": 0.85,
+    "description": "探索大地图玩法tab标题锚点(御魂)"
   }
 ]

BIN=BIN
tasks/Exploration/res/res_check_main_title.png


BIN=BIN
tasks/Exploration/res/res_check_play_title.png


+ 4 - 3
tasks/GameUi/navigator.py

@@ -766,7 +766,7 @@ class GameUi(BaseTask, GameUiAssets):
         return True
 
     def goto_page(self, destination: Page, confirm_wait: float = 0, skip_first_screenshot: bool = True,
-                  timeout: int = 30) -> bool | None:
+                  timeout: int = 30, *, accepted_pages: tuple[Page, ...] = ()) -> bool | None:
         """导航到目标页面。
 
         Args:
@@ -774,6 +774,7 @@ class GameUi(BaseTask, GameUiAssets):
             confirm_wait: 到达目标页面后额外等待的确认时间。
             skip_first_screenshot: 是否复用当前截图。
             timeout: 无有效进展超时时间,单位秒。
+            accepted_pages: 可直接继续任务的其他页面,识别到后无需转往目标页。
 
         Returns:
             是否成功到达目标页面。
@@ -824,9 +825,9 @@ class GameUi(BaseTask, GameUiAssets):
                 last_detected_page_key = current.key
                 reset_repeated_transition_failures()
 
-            if current == destination:
+            if current == destination or any(current.key == page.key for page in accepted_pages):
                 # current 来自 _refresh_current_page,其返回已是两帧稳定确认的结果,无需再次 confirm。
-                return self._finalize_arrival(destination, confirm_wait, start_time)
+                return self._finalize_arrival(current, confirm_wait, start_time)
 
             path = self._build_path(current, destination)
             if not path:

+ 10 - 5
tasks/HeroTest/script_task.py

@@ -302,30 +302,35 @@ class ScriptTask(GameUi, GeneralBattle, HeroTestAssets, SwitchSoul):
 
     def init_pages(self):
         """初始化页面"""
+        # 运行时改链只能改 session 页面副本: navigator bootstrap 时已把全局页面深拷贝了一份,
+        # 之后对 pages.* 的修改 session 看不到, _build_path 会找不到边而返回 None
+        hero_test_page = self.navigator.resolve_page(pages.page_hero_test)
+        if hero_test_page is None:
+            raise RuntimeError(f'Resolve session page failed: {pages.page_hero_test.key}')
         match self.conf.herotest.layer:
             case Layer.YANWU:
                 self.page_hero_mode = self.navigator.add_page(
                     pages.Page(self.I_CHECK_HERO1_EXP, key="page_hero_mode", name="page_hero_mode", register=False)
                 )
-                pages.page_hero_test.connect(self.page_hero_mode, self.I_GBB, key="page_hero_test->page_hero_mode")
+                hero_test_page.connect(self.page_hero_mode, self.I_GBB, key="page_hero_test->page_hero_mode")
             case Layer.MIJING:
                 self.page_hero_mode = self.navigator.add_page(
                     pages.Page(self.I_CHECK_HERO1_SKILL, key="page_hero_mode", name="page_hero_mode", register=False)
                 )
-                pages.page_hero_test.connect(self.page_hero_mode, self.I_BCMJ, key="page_hero_test->page_hero_mode")
+                hero_test_page.connect(self.page_hero_mode, self.I_BCMJ, key="page_hero_test->page_hero_mode")
             case Layer.CHUANCHENG:
                 self.page_hero_mode = self.navigator.add_page(
                     pages.Page(self.I_CHECK_HERO2_EXP, key="page_hero_mode", name="page_hero_mode", register=False)
                 )
-                pages.page_hero_test.connect(self.page_hero_mode, self.I_ENTER_CCSL, key="page_hero_test->page_hero_mode")
+                hero_test_page.connect(self.page_hero_mode, self.I_ENTER_CCSL, key="page_hero_test->page_hero_mode")
             case Layer.MENGXU:
                 self.page_hero_mode = self.navigator.add_page(
                     pages.Page(self.I_CHECK_HERO2_SKILL, key="page_hero_mode", name="page_hero_mode", register=False)
                 )
-                pages.page_hero_test.connect(self.page_hero_mode, self.I_ENTER_MXMJ, key="page_hero_test->page_hero_mode")
+                hero_test_page.connect(self.page_hero_mode, self.I_ENTER_MXMJ, key="page_hero_test->page_hero_mode")
             case _:
                 raise ValueError(f'Unknown Layer {Layer}')
-        self.page_hero_mode.connect(pages.page_hero_test, self.I_BACK_YOLLOW, key="page_hero_mode->page_hero_test")
+        self.page_hero_mode.connect(hero_test_page, self.I_BACK_YOLLOW, key="page_hero_mode->page_hero_test")
 
 
 if __name__ == "__main__":

+ 25 - 0
tasks/OtherWorldTwilight/assets.py

@@ -0,0 +1,25 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+from module.atom.ocr import RuleOcr
+from module.atom.list import RuleList
+
+# This file was automatically generated by ./dev_tools/assets_extract.py.
+# Don't modify it manually.
+class OtherWorldTwilightAssets: 
+
+
+	# Image Rule Assets
+	# 逢魔之时前往彼世逢魔标志 
+	I_DE_TO_OTHER_WORLD = RuleImage(roi_front=(485,130,84,94), roi_back=(416,82,228,225), threshold=0.8, method="Template matching", file="./tasks/OtherWorldTwilight/owt/owt_de_to_other_world.png")
+	# 挑战标志 
+	I_OWT_FIRE = RuleImage(roi_front=(1142,603,82,74), roi_back=(1088,561,181,159), threshold=0.8, method="Template matching", file="./tasks/OtherWorldTwilight/owt/owt_owt_fire.png")
+	# 组队标志 
+	I_OWT_TEAM = RuleImage(roi_front=(959,605,82,74), roi_back=(905,561,181,159), threshold=0.8, method="Template matching", file="./tasks/OtherWorldTwilight/owt/owt_owt_team.png")
+	# 锁定阵容标志 
+	I_OWT_LOCK = RuleImage(roi_front=(679,650,20,30), roi_back=(593,633,228,87), threshold=0.8, method="Template matching", file="./tasks/OtherWorldTwilight/owt/owt_owt_lock.png")
+	# 解锁阵容标志 
+	I_OWT_UNLOCK = RuleImage(roi_front=(679,650,20,30), roi_back=(593,633,228,87), threshold=0.8, method="Template matching", file="./tasks/OtherWorldTwilight/owt/owt_owt_unlock.png")
+
+

+ 47 - 0
tasks/OtherWorldTwilight/config.py

@@ -0,0 +1,47 @@
+# This Python file uses the following encoding: utf-8
+# @author AzurTian
+from datetime import timedelta, time
+
+from pydantic import Field, field_validator
+from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig, GreenMarkEnum
+from tasks.Component.GeneralInvite.config_invite import InviteConfig
+from tasks.Component.SwitchSoul.switch_soul_config import SwitchSoulConfig
+from tasks.Component.config_base import ConfigBase, Time, dynamic_hide
+from tasks.Component.config_scheduler import Scheduler
+from tasks.Orochi.config import UserStatus
+
+
+class OtherWorldTwilightConfig(ConfigBase):
+    # 身份
+    user_status: UserStatus = Field(default=UserStatus.LEADER, description='user_status_help')
+    # 限制时间
+    limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
+    # 限制次数
+    limit_count: int = Field(default=30, description='limit_count_help')
+
+    @property
+    def limit_time_v(self) -> timedelta:
+        if isinstance(self.limit_time, time):
+            return timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
+                             seconds=self.limit_time.second)
+        return self.limit_time
+
+
+class OWTBattleConfig(GeneralBattleConfig):
+    hide_fields = dynamic_hide('preset_enable', 'preset_group', 'preset_team', 'green_mark', 'green_mark_type')
+
+    # pydantic v2 默认不校验默认值, validator 拦不到 CHOOSE, 必须直接给 NAME
+    green_mark_type: GreenMarkEnum = Field(default=GreenMarkEnum.NAME, description='green_mark_type_help')
+
+    @field_validator('green_mark_type')
+    @classmethod
+    def green_mark_type_validator(cls, v):
+        return GreenMarkEnum.NAME
+
+
+class OtherWorldTwilight(ConfigBase):
+    scheduler: Scheduler = Field(default_factory=Scheduler)
+    other_world_twilight_config: OtherWorldTwilightConfig = Field(default_factory=OtherWorldTwilightConfig)
+    invite_config: InviteConfig = Field(default_factory=InviteConfig)
+    general_battle_config: OWTBattleConfig = Field(default_factory=OWTBattleConfig)
+    switch_soul: SwitchSoulConfig = Field(default_factory=SwitchSoulConfig)

+ 47 - 0
tasks/OtherWorldTwilight/owt/image.json

@@ -0,0 +1,47 @@
+[
+  {
+    "itemName": "de_to_other_world",
+    "imageName": "owt_de_to_other_world.png",
+    "roiFront": "485,130,84,94",
+    "roiBack": "416,82,228,225",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "逢魔之时前往彼世逢魔标志"
+  },
+  {
+    "itemName": "owt_fire",
+    "imageName": "owt_owt_fire.png",
+    "roiFront": "1142,603,82,74",
+    "roiBack": "1088,561,181,159",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "挑战标志"
+  },
+  {
+    "itemName": "owt_team",
+    "imageName": "owt_owt_team.png",
+    "roiFront": "959,605,82,74",
+    "roiBack": "905,561,181,159",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "组队标志"
+  },
+  {
+    "itemName": "owt_lock",
+    "imageName": "owt_owt_lock.png",
+    "roiFront": "679,650,20,30",
+    "roiBack": "593,633,228,87",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "锁定阵容标志"
+  },
+  {
+    "itemName": "owt_unlock",
+    "imageName": "owt_owt_unlock.png",
+    "roiFront": "679,650,20,30",
+    "roiBack": "593,633,228,87",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "解锁阵容标志"
+  }
+]

BIN=BIN
tasks/OtherWorldTwilight/owt/owt_de_to_other_world.png


BIN=BIN
tasks/OtherWorldTwilight/owt/owt_owt_fire.png


BIN=BIN
tasks/OtherWorldTwilight/owt/owt_owt_lock.png


BIN=BIN
tasks/OtherWorldTwilight/owt/owt_owt_team.png


BIN=BIN
tasks/OtherWorldTwilight/owt/owt_owt_unlock.png


+ 10 - 0
tasks/OtherWorldTwilight/page.py

@@ -0,0 +1,10 @@
+from tasks.GameUi.default_pages import page_demon_encounter
+from tasks.GameUi.matcher import any_of
+from tasks.GameUi.page_definition import Page
+from tasks.GlobalGame.assets import GlobalGameAssets
+from tasks.OtherWorldTwilight.assets import OtherWorldTwilightAssets
+
+page_owt = Page(any_of(OtherWorldTwilightAssets.I_OWT_FIRE, OtherWorldTwilightAssets.I_OWT_TEAM))
+page_owt.connect(page_demon_encounter, GlobalGameAssets.I_UI_BACK_YELLOW, key="page_owt->page_demon_encounter")
+page_demon_encounter.connect(page_owt, OtherWorldTwilightAssets.I_DE_TO_OTHER_WORLD,
+                             key="page_demon_encounter->page_owt")

+ 198 - 0
tasks/OtherWorldTwilight/script_task.py

@@ -0,0 +1,198 @@
+# This Python file uses the following encoding: utf-8
+# @author AzurTian
+from time import sleep
+from datetime import datetime
+
+from module.base.timer import Timer
+
+from tasks.Component.GeneralBattle.general_battle import GeneralBattle
+from tasks.Component.GeneralInvite.general_invite import GeneralInvite
+from tasks.Component.GeneralRoom.general_room import GeneralRoom
+from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
+from tasks.GameUi.game_ui import GameUi
+from module.logger import logger
+from module.exception import TaskEnd
+from tasks.GameUi.page import (
+    page_main, page_battle, page_battle_prepare, page_reward, page_shikigami_records,
+)
+from tasks.OtherWorldTwilight.assets import OtherWorldTwilightAssets
+from tasks.OtherWorldTwilight.page import page_owt
+from tasks.OtherWorldTwilight.config import OtherWorldTwilight
+from tasks.Orochi.config import UserStatus
+
+
+class ScriptTask(GeneralBattle, GeneralInvite, GeneralRoom, GameUi, SwitchSoul, OtherWorldTwilightAssets):
+
+    conf: OtherWorldTwilight = None
+
+    def run(self) -> bool:
+        self.conf = self.config.other_world_twilight
+        if self.conf.switch_soul.enable:
+            self.goto_page(page_shikigami_records)
+            self.run_switch_soul(self.conf.switch_soul.switch_group_team)
+        if self.conf.switch_soul.enable_switch_by_name:
+            self.goto_page(page_shikigami_records)
+            self.run_switch_soul_by_name(self.conf.switch_soul.group_name, self.conf.switch_soul.team_name)
+        success = True
+        match self.conf.other_world_twilight_config.user_status:
+            case UserStatus.LEADER: success = self.run_leader()
+            case UserStatus.MEMBER: success = self.run_member()
+            case UserStatus.ALONE: self.run_alone()
+            case _: logger.error('Unknown user status')
+        self.goto_page(page_main)
+        if success:
+            self.set_next_run('OtherWorldTwilight', finish=True, success=True)
+        else:
+            self.set_next_run('OtherWorldTwilight', finish=True, success=False)
+        raise TaskEnd('OtherWorldTwilight')
+
+    def run_leader(self):
+        logger.info('Start run leader')
+        self.goto_page(page_owt)
+        self.check_lock(self.conf.general_battle_config.lock_team_enable, self.I_OWT_LOCK, self.I_OWT_UNLOCK)
+        # 创建队伍
+        logger.info('Create team')
+        self.ui_click(self.I_OWT_TEAM, self.I_CHECK_TEAM, interval=1)
+        # 创建房间
+        if not self.create_room():
+            logger.warning('Create room failed')
+            return False
+        self.ensure_private()
+        if not self.create_ensure():
+            logger.warning('Create ensure failed')
+            return False
+        # 邀请队友
+        success = True
+        is_first = True
+        # 这个时候我已经进入房间了哦
+        while 1:
+            self.screenshot()
+            # 无论胜利与否, 都会出现是否邀请一次队友
+            # 区别在于,失败的话不会出现那个勾选默认邀请的框
+            if self.check_and_invite(self.conf.invite_config.default_invite):
+                continue
+            if self.current_count >= self.conf.other_world_twilight_config.limit_count:
+                if self.is_in_room():
+                    logger.info('Count limit out')
+                    break
+            if datetime.now() - self.start_time >= self.conf.other_world_twilight_config.limit_time_v:
+                if self.is_in_room():
+                    logger.info('Time limit out')
+                    break
+            # 如果没有进入房间那就不需要后面的邀请
+            if not self.is_in_room(False):
+                if self.is_room_dead():
+                    logger.warning('Task failed')
+                    success = False
+                    break
+                continue
+            # 点击挑战
+            if not is_first:
+                if self.run_invite(config=self.conf.invite_config):
+                    self.run_general_battle(config=self.conf.general_battle_config)
+                else:
+                    # 邀请失败,退出任务
+                    logger.warning('Invite failed and exit this task')
+                    success = False
+                    break
+            # 第一次会邀请队友
+            if is_first:
+                if not self.run_invite(config=self.conf.invite_config, is_first=True):
+                    logger.warning('Invite failed and exit this task')
+                    success = False
+                    break
+                else:
+                    is_first = False
+                    self.run_general_battle(config=self.conf.general_battle_config)
+
+        # 当结束或者是失败退出循环的时候只有两个UI的可能,在房间或者是在组队界面
+        # 两者都是幂等的,不在对应界面时直接返回
+        self.exit_room()
+        self.exit_team()
+        return success
+
+    def run_member(self):
+        logger.info('Start run member')
+        self.goto_page(page_main)
+        # 进入战斗流程
+        self.device.stuck_record_add('BATTLE_STATUS_S')
+        while 1:
+            self.screenshot()
+            if self.current_count >= self.conf.other_world_twilight_config.limit_count:
+                logger.info('Count limit out')
+                break
+            if datetime.now() - self.start_time >= self.conf.other_world_twilight_config.limit_time_v:
+                logger.info('Time limit out')
+                break
+            if self.check_then_accept():
+                continue
+            if self.is_in_room(False):
+                self.device.stuck_record_clear()
+                if self.wait_battle(wait_time=self.conf.invite_config.wait_time):
+                    self.run_general_battle(config=self.conf.general_battle_config)
+                else:
+                    break
+            # 队长秒开的时候,检测是否加入到战斗中
+            if self.is_in_battle(False):
+                self.run_general_battle(config=self.conf.general_battle_config)
+
+        # 有一种情况是本来要退出的,但是队长邀请了进入的战斗的加载界面
+        while 1:
+            if self.appear(self.I_CHECK_MAIN) or self.appear(self.I_OWT_FIRE):
+                break
+            # 可能在房间就退出,可能还在战斗中就退出战斗,两者都是幂等的
+            self.exit_room()
+            self.exit_battle()
+        return True
+
+    def run_alone(self):
+        logger.info('Start run alone')
+        self.goto_page(page_owt)
+        self.check_lock(self.conf.general_battle_config.lock_team_enable, self.I_OWT_LOCK, self.I_OWT_UNLOCK)
+        unknown_page_timer = Timer(10)
+        while 1:
+            if self.current_count >= self.conf.other_world_twilight_config.limit_count:
+                logger.info('Count limit out')
+                break
+            if datetime.now() - self.start_time >= self.conf.other_world_twilight_config.limit_time_v:
+                logger.info('Time limit out')
+                break
+            self.screenshot()
+            current_page = self.get_current_page(False)
+            # session 返回的 Page 是 clone,与模块级 page_owt 不是同一对象,
+            # 必须用 == (Page.__eq__ 比 key),is 恒为 False
+            if current_page is None:
+                sleep(0.5)
+            elif current_page == page_owt:
+                unknown_page_timer.clear()
+                self.appear_then_click(self.I_OWT_FIRE, interval=1.2)
+            elif current_page in (page_battle_prepare, page_battle, page_reward):
+                unknown_page_timer.clear()
+                self.run_general_battle(self.conf.general_battle_config)
+            else:
+                # 未知页面, 可能是从别处进来的, 超时后拉回彼世逢魔页面
+                if not unknown_page_timer.started():
+                    unknown_page_timer.start()
+                elif unknown_page_timer.reached():
+                    logger.warning(f'Unknown page: {current_page}, goto page_owt')
+                    self.goto_page(page_owt)
+                    unknown_page_timer.clear()
+
+    def is_room_dead(self) -> bool:
+        # 如果在探索界面或者是出现在组队界面,那就是可能房间死了
+        sleep(0.5)
+        if self.appear(self.I_MATCHING) or self.appear(self.I_CHECK_EXPLORATION):
+            sleep(0.5)
+            if self.appear(self.I_MATCHING) or self.appear(self.I_CHECK_EXPLORATION):
+                return True
+        return False
+
+
+if __name__ == '__main__':
+    from module.config.config import Config
+    from module.device.device import Device
+    c = Config('oas1')
+    d = Device(c)
+    t = ScriptTask(c, d)
+
+    t.run()

+ 2 - 5
tasks/TrueOrochi/assets.py

@@ -58,10 +58,7 @@ class TrueOrochiAssets:
 	I_ST_CREATE_ROOM = RuleImage(roi_front=(528,482,223,62), roi_back=(528,482,223,62), threshold=0.8, method="Template matching", file="./tasks/TrueOrochi/st/st_st_create_room.png")
 	# 头像框 
 	I_ST_FRAME = RuleImage(roi_front=(571,442,135,65), roi_back=(571,442,135,65), threshold=0.8, method="Template matching", file="./tasks/TrueOrochi/st/st_st_frame.png")
-
-
-	# Ocr Rule Assets
-	# 本周剩余奖励次数 
-	O_TIMES = RuleOcr(roi=(461,388,40,26), area=(461,388,40,26), mode="DigitCounter", method="Default", keyword="", name="times")
+	# 玩法tab八岐大蛇模块,在场说明本周还有次数 
+	I_ST_MODULE = RuleImage(roi_front=(1111,322,84,22), roi_back=(1068,210,191,313), threshold=0.85, method="Template matching", file="./tasks/TrueOrochi/st/st_module.png")
 
 

+ 0 - 1
tasks/TrueOrochi/config.py

@@ -30,7 +30,6 @@ class TrueOrochiConfig(BaseModel):
     find_true_orochi: bool = Field(default=True, description='find_true_orochi_help')
     # green_enable: bool = Field(default=False, description='green_enable_help')
     # green_mark_type: GreenMarkType = Field(default=GreenMarkType.LEFT_1, description='green_mark_type_help')
-    current_success: int = Field(default=0, description='current_success_help')
 
 class TrueOrochi(ConfigBase):
     scheduler: TrueOrochiScheduler = Field(default_factory=TrueOrochiScheduler)

+ 12 - 35
tasks/TrueOrochi/script_task.py

@@ -2,7 +2,7 @@
 # @author runhey
 # github https://github.com/runhey
 from time import sleep
-from datetime import datetime, time
+from datetime import datetime
 
 from module.logger import logger
 from module.exception import TaskEnd, GameStuckError
@@ -16,6 +16,7 @@ from tasks.Orochi.script_task import ScriptTask as OrochiScriptTask
 from tasks.Orochi.config import Layer
 from tasks.Orochi.page import page_orochi
 from tasks.GameUi.page import page_main, page_shikigami_records
+from tasks.Exploration.page import page_gameplay
 from tasks.TrueOrochi.assets import TrueOrochiAssets
 
 
@@ -25,9 +26,10 @@ class ScriptTask(OrochiScriptTask, TrueOrochiAssets):
     
         conf = self.config.true_orochi.true_orochi_config
 
-        if conf.current_success >= 2:
-            # 超过两次就说明这周打完了没有必要再打了
-            logger.warning('This week is full')
+        # 玩法tab的八岐大蛇模块在场说明本周还有次数,消失说明本周已打完
+        self.goto_page(page_gameplay)
+        if not self.appear(self.I_ST_MODULE):
+            logger.warning('True orochi module absent, no attempts left this week')
             self.check_times(True)
             raise TaskEnd('TrueOrochi')
 
@@ -91,7 +93,7 @@ class ScriptTask(OrochiScriptTask, TrueOrochiAssets):
         # 检查是否还有真蛇入口,支持存储两次
         self.goto_page(page_orochi)
         sleep(0.5)
-        if conf.current_success < 2 and self.check_true_orochi(True):
+        if self.check_true_orochi(True):
             battle = True
             logger.info('Find another true orochi entry, continue')
             self.run_true_orochi_battle()
@@ -110,13 +112,6 @@ class ScriptTask(OrochiScriptTask, TrueOrochiAssets):
             if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
                 continue
             if self.appear_then_click(self.I_ST_FIRE, interval=4):
-                # 修正已经挑战的次数, 注意这个是战斗开始之前的次数
-                current, current_success, total = self.O_TIMES.ocr(self.device.image)
-                if current_success < 0 or current_success > 2:
-                    continue
-                logger.info(f'current: {current}, current_success: {current_success}, total: {total}')
-                conf.current_success = current_success
-                self.config.save()
                 continue
             if self.appear_then_click(self.I_FIND_TS, interval=1):
                 continue
@@ -192,31 +187,13 @@ class ScriptTask(OrochiScriptTask, TrueOrochiAssets):
 
     def check_times(self, battle: bool):
         """
-        后续的次数和时间设置
-        :param battle: 本次是否挑战了真蛇
-        :param current_success: 这周的成功次数
+        根据是否有战斗结果设置下次运行时间
+        :param battle:
         :return:
         """
-        now = datetime.now()
-        now_year, now_week_number, now_weekday = now.isocalendar()
-        if battle:
-            # 只有真正打过才加一次数
-            logger.info('Add current_success by 1')
-            self.config.true_orochi.true_orochi_config.current_success += 1
-            self.config.true_orochi.true_orochi_config.current_success = min(2, self.config.true_orochi.true_orochi_config.current_success)
-            next_run = now + self.config.true_orochi.scheduler.success_interval
-        else:
-            logger.info('Battle skipped or not found True Orochi')
-            next_run = now + self.config.true_orochi.scheduler.failure_interval
-        next_run_year, next_run_week_number, next_run_weekday = next_run.isocalendar()
-        # 如果下次运行的时间是下一周,那么就重置成功次数
-        if now_week_number != next_run_week_number:
-            logger.info('Reset current_success')
-            self.config.true_orochi.true_orochi_config.current_success = 0
-
-        self.config.save()
-        self.set_next_run(task='TrueOrochi', target=next_run)
-        # self.set_next_run('TrueOrochi', finish=True, success=True)
+        interval = self.config.true_orochi.scheduler.success_interval if battle \
+            else self.config.true_orochi.scheduler.failure_interval
+        self.set_next_run(task='TrueOrochi', target=datetime.now() + interval)
 
     def run_true_orochi(self) -> bool:
         pass

+ 9 - 0
tasks/TrueOrochi/st/image.json

@@ -124,5 +124,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "头像框"
+  },
+  {
+    "itemName": "st_module",
+    "imageName": "st_module.png",
+    "roiFront": "1111,322,84,22",
+    "roiBack": "1068,210,191,313",
+    "method": "Template matching",
+    "threshold": 0.85,
+    "description": "玩法tab八岐大蛇模块,在场说明本周还有次数"
   }
 ]

+ 0 - 11
tasks/TrueOrochi/st/ocr.json

@@ -1,11 +0,0 @@
-[
-  {
-    "itemName": "times",
-    "roiFront": "461,388,40,26",
-    "roiBack": "461,388,40,26",
-    "mode": "DigitCounter",
-    "method": "Default",
-    "keyword": "",
-    "description": "本周剩余奖励次数"
-  }
-]

BIN=BIN
tasks/TrueOrochi/st/st_module.png