浏览代码

Merge upstream dev and validate navigation updates

Merge runhey/OnmyojiAutoScript dev at ff594d1c, preserving the local battle strategy, login, costume, and weekly task fixes.

Resolve touch-fish navigation changes. Fix navigation timeout on failed route replanning, battle configuration and named green marks, task-scoped scene assets and mask caches, FrogBoss history recovery, and OtherWorldTwilight recovery/counting.

Validation: 133 pytest tests passed. Changed task modules import successfully; Python/JSON syntax, new image references, and diff checks passed.
unknown 1 月之前
父节点
当前提交
d77215f44e
共有 100 个文件被更改,包括 1183 次插入 和 471 次删除
  1. 6 6
      .github/aw/actions-lock.json
  2. 5 0
      .github/aw/logs/.gitignore
  3. 23 23
      .github/workflows/agentics-maintenance.yml
  4. 0 1
      .github/workflows/issue-handle-bug.lock.yml
  5. 0 1
      .github/workflows/issue-handle-enhancement.lock.yml
  6. 0 1
      .github/workflows/issue-handle-other.lock.yml
  7. 0 1
      .github/workflows/issue-handle-question.lock.yml
  8. 0 1
      .github/workflows/issue-triage.lock.yml
  9. 0 1
      .github/workflows/pr-review-checklist.lock.yml
  10. 0 1
      .github/workflows/pr-review-intent.lock.yml
  11. 0 1
      .github/workflows/weekly-report.lock.yml
  12. 11 1
      assets/i18n/zh-CN.json
  13. 3 2
      config/template.json
  14. 10 2
      dev_tools/assets_test.py
  15. 132 11
      module/atom/image.py
  16. 1 1
      module/config/config_manual.py
  17. 1 1
      module/config/config_menu.py
  18. 2 0
      module/config/config_model.py
  19. 2 0
      module/config/i18n/zh_CN.xml
  20. 1 1
      module/server/annotator_rule_schema.py
  21. 17 1
      module/server/app.py
  22. 4 8
      tasks/AbyssShadows/script_task.py
  23. 3 3
      tasks/ActivityShikigami/page.py
  24. 2 4
      tasks/ActivityShikigami/script_task.py
  25. 1 2
      tasks/ActivityShikigami/script_test.py
  26. 3 6
      tasks/AreaBoss/script_task.py
  27. 12 22
      tasks/BondlingFairyland/script_task.py
  28. 2 4
      tasks/BudokaiTournament/script_task.py
  29. 1 2
      tasks/CollectiveMissions/script_task.py
  30. 3 2
      tasks/Component/Buy/buy.py
  31. 6 1
      tasks/Component/Costume/config.py
  32. 54 7
      tasks/Component/Costume/costume_base.py
  33. 4 8
      tasks/Component/Costume/costume_test_shikigami.py
  34. 1 2
      tasks/Component/CostumeBattle/costume_test_battle.py
  35. 15 0
      tasks/Component/CostumeBattleScene/assets.py
  36. 二进制
      tasks/Component/CostumeBattleScene/bs1/bs1_reward_1.png
  37. 11 0
      tasks/Component/CostumeBattleScene/bs1/image.json
  38. 18 2
      tasks/Component/GeneralBattle/assets.py
  39. 6 1
      tasks/Component/GeneralBattle/battle.py
  40. 77 28
      tasks/Component/GeneralBattle/battle_wait.py
  41. 10 0
      tasks/Component/GeneralBattle/config_general_battle.py
  42. 24 0
      tasks/Component/GeneralBattle/gb/click.json
  43. 二进制
      tasks/Component/GeneralBattle/gb/gb_battle_state_info.png
  44. 二进制
      tasks/Component/GeneralBattle/gb/gb_gb_check_team_exit.png
  45. 二进制
      tasks/Component/GeneralBattle/gb/gb_gb_skin_confirm.png
  46. 二进制
      tasks/Component/GeneralBattle/gb/gb_over_ghost.png
  47. 37 1
      tasks/Component/GeneralBattle/gb/image.json
  48. 9 0
      tasks/Component/GeneralBattle/gb/ocr.json
  49. 109 38
      tasks/Component/GeneralBattle/general_battle.py
  50. 1 2
      tasks/Component/RightActivity/right_activity.py
  51. 3 3
      tasks/Component/SwitchAccount/switch_account.py
  52. 3 3
      tasks/DailyTrifles/page.py
  53. 8 15
      tasks/DailyTrifles/script_task.py
  54. 14 3
      tasks/Delegation/script_task.py
  55. 16 8
      tasks/DemonEncounter/assets.py
  56. 32 8
      tasks/DemonEncounter/demon/click.json
  57. 二进制
      tasks/DemonEncounter/demon/demon_de_box_center.png
  58. 10 1
      tasks/DemonEncounter/demon/image.json
  59. 1 1
      tasks/DemonEncounter/demon/ocr.json
  60. 89 51
      tasks/DemonEncounter/script_task.py
  61. 4 8
      tasks/DemonRetreat/script_task.py
  62. 3 4
      tasks/Dokan/script_task.py
  63. 9 11
      tasks/Duel/script_task.py
  64. 4 8
      tasks/DyeTrials/script_task.py
  65. 9 32
      tasks/EternitySea/script_task.py
  66. 2 4
      tasks/EvoZone/assets.py
  67. 2 2
      tasks/EvoZone/o/image.json
  68. 8 17
      tasks/EvoZone/script_task.py
  69. 5 10
      tasks/ExperienceYoukai/script_task.py
  70. 11 3
      tasks/Exploration/assets.py
  71. 15 13
      tasks/Exploration/base.py
  72. 44 0
      tasks/Exploration/page.py
  73. 12 0
      tasks/Exploration/res/click.json
  74. 28 1
      tasks/Exploration/res/image.json
  75. 二进制
      tasks/Exploration/res/res_check_main_title.png
  76. 二进制
      tasks/Exploration/res/res_check_play_title.png
  77. 二进制
      tasks/Exploration/res/res_e_open_folder.png
  78. 5 18
      tasks/FallenSun/script_task.py
  79. 1 2
      tasks/FloatParade/script_task.py
  80. 25 11
      tasks/FrogBoss/assets.py
  81. 二进制
      tasks/FrogBoss/fb/fb_bet_failure.png
  82. 二进制
      tasks/FrogBoss/fb/fb_bet_left.png
  83. 二进制
      tasks/FrogBoss/fb/fb_bet_right.png
  84. 二进制
      tasks/FrogBoss/fb/fb_bet_success_box.png
  85. 二进制
      tasks/FrogBoss/fb/fb_failure_right.png
  86. 二进制
      tasks/FrogBoss/fb/fb_frog_boss_rest.png
  87. 二进制
      tasks/FrogBoss/fb/fb_frog_last_lose.png
  88. 二进制
      tasks/FrogBoss/fb/fb_frog_last_select_blue.png
  89. 二进制
      tasks/FrogBoss/fb/fb_frog_last_select_red.png
  90. 二进制
      tasks/FrogBoss/fb/fb_frog_last_win.png
  91. 二进制
      tasks/FrogBoss/fb/fb_frog_log.png
  92. 二进制
      tasks/FrogBoss/fb/fb_frog_log_check.png
  93. 二进制
      tasks/FrogBoss/fb/fb_frog_log_close.png
  94. 二进制
      tasks/FrogBoss/fb/fb_next_competition.png
  95. 二进制
      tasks/FrogBoss/fb/fb_success_left.png
  96. 9 23
      tasks/FrogBoss/fb/image.json
  97. 66 6
      tasks/FrogBoss/fb/image2.json
  98. 9 0
      tasks/FrogBoss/fb/ocr.json
  99. 67 5
      tasks/FrogBoss/frog_oas.py
  100. 42 0
      tasks/FrogBoss/record_reader.py

+ 6 - 6
.github/aw/actions-lock.json

@@ -1,14 +1,14 @@
 {
   "entries": {
-    "github/gh-aw-actions/setup-cli@v0.88.2": {
+    "github/gh-aw-actions/setup-cli@v0.89.21": {
       "repo": "github/gh-aw-actions/setup-cli",
-      "version": "v0.88.2",
-      "sha": "9271a1804551c0dc4fb0085a97979950aa2f8489"
+      "version": "v0.89.21",
+      "sha": "924af5fdc64061cfbf66fb584c8b07e2ac230c60"
     },
-    "github/gh-aw-actions/setup@v0.88.2": {
+    "github/gh-aw-actions/setup@v0.89.21": {
       "repo": "github/gh-aw-actions/setup",
-      "version": "v0.88.2",
-      "sha": "9271a1804551c0dc4fb0085a97979950aa2f8489"
+      "version": "v0.89.21",
+      "sha": "924af5fdc64061cfbf66fb584c8b07e2ac230c60"
     }
   }
 }

+ 5 - 0
.github/aw/logs/.gitignore

@@ -0,0 +1,5 @@
+# Ignore all downloaded workflow logs
+*
+
+# But keep the .gitignore file itself
+!.gitignore

+ 23 - 23
.github/workflows/agentics-maintenance.yml

@@ -1,4 +1,4 @@
-# This file was automatically generated by pkg/workflow/maintenance_workflow.go (v0.88.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
+# This file was automatically generated by pkg/workflow/maintenance_workflow.go (v0.89.21). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md
 #
 #    ___                   _   _
 #   / _ \                 | | (_)
@@ -94,7 +94,7 @@ jobs:
       discussions: write
     steps:
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -115,7 +115,7 @@ jobs:
       issues: write
     steps:
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -136,7 +136,7 @@ jobs:
       pull-requests: write
     steps:
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -158,7 +158,7 @@ jobs:
       actions: write
     steps:
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -189,7 +189,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -206,9 +206,9 @@ jobs:
             await main();
 
       - name: Install gh-aw
-        uses: github/gh-aw-actions/setup-cli@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup-cli@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
-          version: v0.88.2
+          version: v0.89.21
 
       - name: Run operation
         uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
@@ -240,7 +240,7 @@ jobs:
       pull-requests: write
     steps:
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -291,7 +291,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -341,7 +341,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -358,9 +358,9 @@ jobs:
             await main();
 
       - name: Install gh-aw
-        uses: github/gh-aw-actions/setup-cli@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup-cli@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
-          version: v0.88.2
+          version: v0.89.21
 
       - name: Create missing labels
         uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
@@ -391,7 +391,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -408,9 +408,9 @@ jobs:
             await main();
 
       - name: Install gh-aw
-        uses: github/gh-aw-actions/setup-cli@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup-cli@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
-          version: v0.88.2
+          version: v0.89.21
 
       - name: Restore activity report logs cache
         id: activity_report_logs_cache
@@ -498,7 +498,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -515,9 +515,9 @@ jobs:
             await main();
 
       - name: Install gh-aw
-        uses: github/gh-aw-actions/setup-cli@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup-cli@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
-          version: v0.88.2
+          version: v0.89.21
 
       - name: Restore forecast report logs cache
         id: forecast_report_logs_cache
@@ -594,7 +594,7 @@ jobs:
       issues: write
     steps:
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -635,7 +635,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Scripts
-        uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
           destination: ${{ runner.temp }}/gh-aw/actions
 
@@ -652,9 +652,9 @@ jobs:
             await main();
 
       - name: Install gh-aw
-        uses: github/gh-aw-actions/setup-cli@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2
+        uses: github/gh-aw-actions/setup-cli@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
         with:
-          version: v0.88.2
+          version: v0.89.21
 
       - name: Validate workflows and file issue on findings
         uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0

文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/issue-handle-bug.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/issue-handle-enhancement.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/issue-handle-other.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/issue-handle-question.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/issue-triage.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/pr-review-checklist.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/pr-review-intent.lock.yml


文件差异内容过多而无法显示
+ 0 - 1
.github/workflows/weekly-report.lock.yml


+ 11 - 1
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": "睡眠开始时间",
@@ -138,7 +140,15 @@
   "enable_ap100_anti_detect": "100体爬塔防检测",
   "enable_ap100_anti_detect_help": "100体爬塔战斗过程是否随机点击或滑动",
   "costume_battle_15": "灵狐寄愿",
+  "costume_battle_scene_default": "默认",
+  "costume_battle_scene_1": "鎏金圣域",
+  "costume_battle_scene_type": "战斗场景",
+  "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": "仅当绿标按式神名匹配时生效,填写目标式神名"
 }

+ 3 - 2
config/template.json

@@ -74,7 +74,8 @@
       "costume_theme_type": "costume_theme_default",
       "costume_shikigami_type": "costume_shikigami_default",
       "costume_sign_type": "costume_sign_default",
-      "costume_battle_type": "costume_battle_default"
+      "costume_battle_type": "costume_battle_default",
+      "costume_battle_scene_type": "costume_battle_scene_default"
     },
     "team_flow": {
       "enable": false,
@@ -1578,4 +1579,4 @@
       "team_name": ""
     }
   }
-}
+}

+ 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, cv2.error):
+                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():

+ 4 - 8
tasks/AbyssShadows/script_task.py

@@ -96,12 +96,10 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AbyssShadowsAssets):
         cfg: AbyssShadows = self.config.abyss_shadows
 
         if cfg.switch_soul_config.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(cfg.switch_soul_config.switch_group_team)
         if cfg.switch_soul_config.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(cfg.switch_soul_config.group_name, cfg.switch_soul_config.team_name)
         today = datetime.now().weekday()
         if today not in [4, 5, 6]:
@@ -303,17 +301,15 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AbyssShadowsAssets):
     def goto_main(self):
         ''' 保持好习惯,一个任务结束了就返回庭院,方便下一任务的开始或者是出错重启
         '''
-        self.ui_get_current_page()
         logger.info("Exiting abyss_shadows")
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
     def goto_abyss_shadows(self) -> bool:
         ''' 进入狭间
         :return bool
         '''
-        self.ui_get_current_page()
         logger.info("Entering abyss_shadows")
-        self.ui_goto(page_guild)
+        self.goto_page(page_guild)
         
         while 1:
             self.screenshot()

+ 3 - 3
tasks/ActivityShikigami/page.py

@@ -19,9 +19,9 @@ from tasks.base_task import BaseTask as BT
 
 # 爬塔活动主要界面
 page_climb_act = Page(asa.I_TO_BATTLE_MAIN)
-page_climb_act.additional = [gga.I_UI_REWARD, asa.I_SKIP_BUTTON, asa.I_CONFIRM_SKIP, asa.I_RED_EXIT]
-page_climb_act.link(button=G.I_BACK_Y, destination=page_main)
-page_main.link(button=[asa.I_SHI, RAA.I_TOGGLE_BUTTON], destination=page_climb_act)
+page_climb_act.add_enter_success_hooks(gga.I_UI_REWARD, asa.I_SKIP_BUTTON, asa.I_CONFIRM_SKIP, asa.I_RED_EXIT)
+page_climb_act.connect(page_main, G.I_BACK_Y, key="page_climb_act->page_main")
+page_main.connect(page_climb_act, [asa.I_SHI, RAA.I_TOGGLE_BUTTON], key="page_main->page_climb_act")
 
 # page_act_list_climb_act.link(button=G.I_ACT_LIST_GOTO_ACT, destination=page_climb_act)
 # # 爬塔活动副界面

+ 2 - 4
tasks/ActivityShikigami/script_task.py

@@ -153,8 +153,7 @@ class ScriptTask(StateMachine, GameUi, Battle, BaseActivity, SwitchSoul, Activit
         #
         for climb_type in self.conf.general_climb.run_sequence_v:
             # 进入到活动的主页面,不是具体的战斗页面
-            self.ui_get_current_page()
-            self.ui_goto(game.page_climb_act)
+            self.goto_page(game.page_climb_act)
             try:
                 method_func = getattr(self, f'_run_{climb_type}')
                 method_func()
@@ -168,8 +167,7 @@ class ScriptTask(StateMachine, GameUi, Battle, BaseActivity, SwitchSoul, Activit
 
         # 返回庭院
         logger.hr("Exit Shikigami", 2)
-        self.ui_get_current_page(False)
-        self.ui_goto(game.page_main)
+        self.goto_page(game.page_main)
         if self.conf.general_climb.active_souls_clean:
             self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
         self.set_next_run(task="ActivityShikigami", success=True)

+ 1 - 2
tasks/ActivityShikigami/script_test.py

@@ -13,8 +13,7 @@ from tasks.ActivityShikigami.script_task import ScriptTask
 class ImplScriptTask(ScriptTask, ABC):
     def test_battle_main(self) -> bool:
         # 从别的地方到活动主页面
-        self.ui_get_current_page()
-        self.ui_goto(page_climb_act)
+        self.goto_page(page_climb_act)
         # 从活动主页面到默认战斗页面
         self.ui_click(self.I_TO_BATTLE_MAIN, stop=self.I_CHECK_BATTLE_MAIN, interval=1)
         # 从默认战斗页面到式神录 再返回

+ 3 - 6
tasks/AreaBoss/script_task.py

@@ -48,18 +48,15 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
         con = self.config.area_boss.boss
 
         if self.config.area_boss.switch_soul.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(self.config.area_boss.switch_soul.switch_group_team)
 
         if self.config.area_boss.switch_soul.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(self.config.area_boss.switch_soul.group_name,
                                          self.config.area_boss.switch_soul.team_name)
 
-        self.ui_get_current_page()
-        self.ui_goto(page_area_boss)
+        self.goto_page(page_area_boss)
 
         # 已挑战鬼王数量
         boss_fought = 0

+ 12 - 22
tasks/BondlingFairyland/script_task.py

@@ -41,23 +41,21 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
 
         if cong.bondling_config.check_enable:
             logger.hr('第一步, 检查契忆数量', 2)
-            self.ui_get_current_page()
-            self.ui_goto(page_mall, confirm_wait=2.5)
+            self.goto_page(page_mall, confirm_wait=2.5)
             self.ui_click(self.I_MALL_SCCALES, self.I_MALL_SCCALES_CHECK)
             self.ui_click(self.I_MALL_BONDLINGS_SURE, self.I_MALL_BONDLINGS_ON)
             MAX_COUNT = cong.bondling_config.limit_num
             cu, re, total = self.O_BL_CHECK_MONEY.ocr(self.device.image)
             if cu >= MAX_COUNT:
                 logger.info(f'契忆数量: {cu} 大于 {MAX_COUNT}')
-                self.ui_get_current_page()
-                self.ui_goto(page_main)
+                self.goto_page(page_main)
                 self.set_next_run(task='BondlingFairyland', finish=True, success=True)
                 raise TaskEnd
             logger.info(f'契忆数量: {cu} 小于 {MAX_COUNT}, 继续任务')
         logger.hr('第二步, 切换御魂', 2)
         self.switch_soul()
         logger.hr('第三步, 前往契灵主界面', 2)
-        self.ui_goto_page(page_bondling_fairyland)
+        self.goto_page(page_bondling_fairyland)
         logger.hr('第四步, 开始战斗准备', 2)
         self.current_count = 0
         self.limit_count = cong.bondling_config.limit_count  # 默认limit_count值
@@ -68,7 +66,7 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
             if cong.bondling_config.user_status != UserStatus.ALONE:
                 raise ValueError(f'Now is model1, but user status is not alone, current: {cong.bondling_config.user_status.value}')
             self.run_search(cong.bondling_config)
-            self.ui_goto_page(page_main)
+            self.goto_page(page_main)
             self.set_next_run(task='BondlingFairyland', finish=True, success=True)
             raise TaskEnd
         match cong.bondling_config.user_status:
@@ -79,8 +77,7 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
                 self.limit_count //= 2
                 self.run_member()
                 self.current_count = 0
-                self.ui_get_current_page()
-                self.ui_goto(page_bondling_fairyland)
+                self.goto_page(page_bondling_fairyland)
                 self.switch_ball()
             case UserStatus.LEADER | UserStatus.ALONE:
                 self.switch_ball()
@@ -191,20 +188,17 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
         if self.exit_team():
             pass
 
-        self.ui_get_current_page()
-        self.ui_goto(page_bondling_fairyland)
+        self.goto_page(page_bondling_fairyland)
         # 引用配置
         if UserStatus.handoff1 == self.config.bondling_fairyland.bondling_config.user_status:
             self.current_count = 0
             self.run_member()
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         self.set_next_run(task='BondlingFairyland', finish=True, success=True)
         raise TaskEnd
 
     def run_member(self):
         logger.hr('Start run member', 2)
-        self.ui_get_current_page()
         # 开始等待队长拉人
         wait_time = self.config.bondling_fairyland.invite_config.wait_time
         wait_timer = Timer(wait_time.minute * 60)
@@ -260,8 +254,7 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
                 pass
                 # 引用配置
         if UserStatus.MEMBER == self.config.bondling_fairyland.bondling_config.user_status:
-            self.ui_get_current_page()
-            self.ui_goto(page_main)
+            self.goto_page(page_main)
             self.set_next_run(task='BondlingFairyland', finish=True, success=True)
             raise TaskEnd
 
@@ -278,8 +271,7 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
         capture_setting_checked = False
         while 1:
             if not self.in_search_ui(screenshot=True):
-                self.ui_get_current_page()
-                self.ui_goto(page_bondling_fairyland)
+                self.goto_page(page_bondling_fairyland)
                 continue
             if bondling_config.bondling_mode != BondlingMode.MODE1:
                 if self.ball_click(current_ball_index):
@@ -324,8 +316,7 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
                 self.appear_then_click(self.I_BACK_Y, interval=1)
         logger.info('BondlingFairyland task finished')
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         self.set_next_run(task='BondlingFairyland', finish=True, success=True)
         raise TaskEnd
 
@@ -810,7 +801,7 @@ class ScriptTask(GameUi, GeneralInvite, GeneralRoom, BondlingBattle, SwitchSoul,
             return
         bondling_config = cong.bondling_config
         bondling_switch_soul = cong.bondling_switch_soul
-        self.ui_goto_page(page_shikigami_records)
+        self.goto_page(page_shikigami_records)
         # 单刷探查配置
         if bondling_config.bondling_mode == BondlingMode.MODE1:
             type_str, (group, team) = bondling_switch_soul.get_switch_by_name('search_switch')
@@ -864,8 +855,7 @@ if __name__ == '__main__':
     device = Device(config)
     t = ScriptTask(config, device)
     t.run()
-    t.ui_get_current_page()
-    t.ui_goto(page_bondling_fairyland)
+    t.goto_page(page_bondling_fairyland)
     # image = task.screenshot()
 
     # con = config.bondling_fairyland

+ 2 - 4
tasks/BudokaiTournament/script_task.py

@@ -238,8 +238,7 @@ class ScriptTask(Foot):
         #
         for climb_type in self.conf.run_sequence():
             # 进入到活动的主页面,不是具体的战斗页面
-            self.ui_get_current_page()
-            self.ui_goto(game.page_climb_act)
+            self.goto_page(game.page_climb_act)
             try:
                 if getattr(self.conf.daily_training, f'limit_{self.climb_type}') > 0:
                     method_func = getattr(self, f'_run_{climb_type}')
@@ -254,8 +253,7 @@ class ScriptTask(Foot):
 
         # 返回庭院
         logger.hr("Exit BudokaiTournament", 2)
-        self.ui_get_current_page(False)
-        self.ui_goto(game.page_main)
+        self.goto_page(game.page_main)
         if self.conf.daily_training.active_souls_clean:
             self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
         self.set_next_run(task="BudokaiTournament", success=True)

+ 1 - 2
tasks/CollectiveMissions/script_task.py

@@ -46,8 +46,7 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
         return rule
 
     def run(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_guild)
+        self.goto_page(page_guild)
         rule = self.config.collective_missions.missions_config.missions_rule
         self.ui_click(self.I_CM_SHRINE, self.I_CM_CM)
         self.ui_click(self.I_CM_CM, self.I_CM_RECORDS)

+ 3 - 2
tasks/Component/Buy/buy.py

@@ -77,7 +77,7 @@ class Buy(BaseTask, BuyAssets):
         return True
 
     def buy_more(self, start_click: Union[RuleImage, RuleOcr, RuleClick],
-                 number: int = None):
+                 number: int = None) -> bool:
         """
         购买多个物品
         :param start_click:
@@ -93,7 +93,7 @@ class Buy(BaseTask, BuyAssets):
             if try_click_count >= 5:
                 logger.warning(f'Buy_more failed, try_click_count: {try_click_count}')
                 logger.warning('Close the purchase')
-                return
+                return False
 
             if isinstance(start_click, RuleImage):
                 if self.appear_then_click(start_click, interval=1):
@@ -162,6 +162,7 @@ class Buy(BaseTask, BuyAssets):
 
             if self.click(self.C_BUY_MORE, interval=2):
                 continue
+        return True
 
     def buy_check_money(self, target: RuleOcr, minimum: int):
         """

+ 6 - 1
tasks/Component/Costume/config.py

@@ -79,6 +79,11 @@ class BattleType(str, Enum):
     COSTUME_BATTLE_14 = 'costume_battle_14'  # 茸茨跃动
     COSTUME_BATTLE_15 = 'costume_battle_15'  # 灵狐寄愿
 
+# 战斗场景
+class BattleSceneType(str, Enum):
+    COSTUME_BATTLE_SCENE_DEFAULT = 'costume_battle_scene_default'  # 默认
+    COSTUME_BATTLE_SCENE_1 = 'costume_battle_scene_1'  # 鎏金圣域
+
 
 class CostumeConfig(BaseModel):
     # 皮肤配置
@@ -89,6 +94,7 @@ class CostumeConfig(BaseModel):
     costume_shikigami_type: ShikigamiType = Field(default=ShikigamiType.COSTUME_SHIKIGAMI_DEFAULT, description='costume_shikigami_type_help')
     costume_sign_type: SignType = Field(default=SignType.COSTUME_SIGN_DEFAULT, description='costume_sign_type_help')
     costume_battle_type: BattleType = Field(default=BattleType.COSTUME_BATTLE_DEFAULT, description='costume_battle_type_help')
+    costume_battle_scene_type: BattleSceneType = Field(default=BattleSceneType.COSTUME_BATTLE_SCENE_DEFAULT, description='costume_battle_scene_type_help')
 
     @field_validator('costume_realm_type', mode='before')
     @classmethod
@@ -103,4 +109,3 @@ class CostumeConfig(BaseModel):
 
 
 
-

+ 54 - 7
tasks/Component/Costume/costume_base.py

@@ -2,16 +2,23 @@
 # @author runhey
 # github https://github.com/runhey
 
+from copy import deepcopy
+
 from module.atom.image import RuleImage
 from module.atom.gif import RuleGif
 from module.logger import logger
+from module.server.i18n import I18n
 
-from tasks.Component.Costume.config import (MainType, CostumeConfig, RealmType,
-                                            ThemeType, ShikigamiType, SignType, BattleType, CarpBannerType)
+from tasks.Component.Costume.config import (
+    MainType, CostumeConfig, RealmType,
+    ThemeType, ShikigamiType, SignType,
+    BattleType, BattleSceneType, CarpBannerType
+)
 from tasks.Component.Costume.assets import CostumeAssets
 from tasks.Component.CostumeBattle.assets import CostumeBattleAssets
 from tasks.Component.CostumeShikigami.assets import CostumeShikigamiAssets
 from tasks.Component.CostumeCarpBanner.assets import CostumeCarpBannerAssets
+from tasks.Component.CostumeBattleScene.assets import CostumeBattleSceneAssets
 
 # 庭院皮肤
 # 主界面皮肤(使用字典推导式动态生成)
@@ -66,6 +73,13 @@ battle_theme_model = {
     } for i in range(1, 16)
 }
 
+# 战斗场景皮肤。图片资源待补充,先保留空映射。
+battle_scene_model = {
+    BattleSceneType.COSTUME_BATTLE_SCENE_1: {
+        'I_REWARD': 'I_REWARD_1',
+    },
+}
+
 # 幕间主题
 shikigami_costume_model = {
     getattr(ShikigamiType, f"COSTUME_SHIKIGAMI_{i}"): {
@@ -93,9 +107,12 @@ class CostumeBase:
     def check_costume(self, config: CostumeConfig=None):
         if config is None:
             config: CostumeConfig = self.config.model.global_game.costume_config
+        current_task = self.get_task_name()
+        logger.info(f'Current task: {current_task}')
         self.check_costume_main(config.costume_main_type)
         self.check_costume_carpbanner(config.costume_carpbanner_type)
         self.check_costume_battle(config.costume_battle_type)
+        self.check_costume_battle_scene(config.costume_battle_scene_type)
         self.check_costume_shikigami(config.costume_shikigami_type)
 
     def replace_img(self,
@@ -118,13 +135,18 @@ class CostumeBase:
         asset_before_object._kp = None
         asset_before_object._des = None
         asset_before_object._match_init = False
-        for name in ('name', 'kp', 'des', 'is_template_match', 'is_sift_flann'):
+        asset_before_object._mask = None
+        asset_before_object._mask_loaded = False
+        asset_before_object.last_score = -1.0
+        asset_before_object.last_scale = None
+        for name in ('name', 'kp', 'des', 'is_template_match', 'is_sift_flann',
+                     'is_masked_template_match', 'is_multi_scale_template_match'):
             asset_before_object.__dict__.pop(name, None)
 
     def check_costume_main(self, main_type: MainType):
         if main_type == MainType.COSTUME_MAIN:
             return
-        logger.info(f'Switch main costume to {main_type}')
+        logger.info(f'Switch main costume to {main_type} ({I18n.trans_zh_cn(main_type)})')
         costume_assets = CostumeAssets()
         for key, value in main_costume_model[main_type].items():
             if isinstance(value, list):
@@ -139,7 +161,7 @@ class CostumeBase:
     def check_costume_carpbanner(self, carpbanner_type: CarpBannerType):
         if carpbanner_type == CarpBannerType.COSTUME_CARPBANNER_DEFAULT:
             return
-        logger.info(f'Switch carp banner theme {carpbanner_type} (override realm assets)')
+        logger.info(f'Switch carp banner theme {carpbanner_type} (override realm assets) ({I18n.trans_zh_cn(carpbanner_type)})')
         carpbanner_assets = CostumeCarpBannerAssets()
         model = carpbanner_costume_model.get(carpbanner_type, {})
         for key, value in model.items():
@@ -153,7 +175,7 @@ class CostumeBase:
     def check_costume_battle(self, battle_type: BattleType):
         if battle_type == BattleType.COSTUME_BATTLE_DEFAULT:
             return
-        logger.info(f'Switch battle theme {battle_type}')
+        logger.info(f'Switch battle theme {battle_type} ({I18n.trans_zh_cn(battle_type)})')
         costume_battle_assets = CostumeBattleAssets()
         for key, value in battle_theme_model[battle_type].items():
             if not hasattr(costume_battle_assets, value):
@@ -166,10 +188,35 @@ class CostumeBase:
             else:
                 self.replace_img(key, assert_value)
 
+    def check_costume_battle_scene(self, scene_type: BattleSceneType):
+        # Scene skins only apply to selected tasks; never mutate the shared battle assets.
+        for key, original in self.__dict__.pop('_battle_scene_original_assets', {}).items():
+            setattr(self, key, original)
+        if scene_type == BattleSceneType.COSTUME_BATTLE_SCENE_DEFAULT:
+            return
+        logger.info(f'Switch battle scene skin {scene_type} ({I18n.trans_zh_cn(scene_type)})')
+        current_task = self.get_task_name()
+        allowed_tasks = {
+            'Orochi',
+        }
+        if current_task not in allowed_tasks:
+            return
+
+        costume_assets = CostumeBattleSceneAssets()
+        for key, value in battle_scene_model.get(scene_type, {}).items():
+            if not hasattr(self, key) or not hasattr(costume_assets, value):
+                # 尚未采集完成的资产,跳过
+                continue
+            assert_value: RuleImage = getattr(costume_assets, value)
+            original = getattr(self, key)
+            self.__dict__.setdefault('_battle_scene_original_assets', {})[key] = original
+            setattr(self, key, deepcopy(original))
+            self.replace_img(key, assert_value)
+
     def check_costume_shikigami(self, shikigami_type: ShikigamiType):
         if shikigami_type == ShikigamiType.COSTUME_SHIKIGAMI_DEFAULT:
             return
-        logger.info(f'Switch shikigami theme {shikigami_type}')
+        logger.info(f'Switch shikigami theme {shikigami_type} ({I18n.trans_zh_cn(shikigami_type)})')
         shikigami_assets = CostumeShikigamiAssets()
         model = shikigami_costume_model.get(shikigami_type, {})
         for key, value in model.items():

+ 4 - 8
tasks/Component/Costume/costume_test_shikigami.py

@@ -22,8 +22,7 @@ class ScriptTask(GameUi, SwitchSoul, SwitchSoulAssets, SoulsTidyAssets):
 
     def run(self):
         # 定位并进入式神录
-        self.ui_get_current_page()
-        self.ui_goto(page_shikigami_records)
+        self.goto_page(page_shikigami_records)
 
         # 关键识别点统计
         images_count = [
@@ -84,8 +83,7 @@ class ScriptTask(GameUi, SwitchSoul, SwitchSoulAssets, SoulsTidyAssets):
         logger.hr('Switch Soul Test - All Groups')
         
         # 进入式神录
-        self.ui_get_current_page()
-        self.ui_goto(page_shikigami_records)
+        self.goto_page(page_shikigami_records)
         
         # 点击预设按钮
         self.click_preset()
@@ -111,8 +109,7 @@ class ScriptTask(GameUi, SwitchSoul, SwitchSoulAssets, SoulsTidyAssets):
         logger.hr('Souls Tidy Donation Test')
         
         # 进入式神录
-        self.ui_get_current_page()
-        self.ui_goto(page_shikigami_records)
+        self.goto_page(page_shikigami_records)
         
         # 进入御魂界面
         souls_tidy_task = SoulsTidyTask(self.config, self.device)
@@ -150,8 +147,7 @@ class ScriptTask(GameUi, SwitchSoul, SwitchSoulAssets, SoulsTidyAssets):
         souls_tidy_task.back_records()
         
         # 退出式神录
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         logger.info('Souls Tidy Donation Test completed')
 
 

+ 1 - 2
tasks/Component/CostumeBattle/costume_test_battle.py

@@ -13,8 +13,7 @@ from tasks.Component.Costume.config import BattleType
 class ScriptTask(ScriptTaskBase):
 
     def run(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_kekkai_toppa)
+        self.goto_page(page_kekkai_toppa)
 
         self.attack()
 

+ 15 - 0
tasks/Component/CostumeBattleScene/assets.py

@@ -0,0 +1,15 @@
+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 CostumeBattleSceneAssets:
+
+
+	# Image Rule Assets
+	#
+	I_REWARD_1 = RuleImage(roi_front=(551,505,165,84), roi_back=(451,413,372,226), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeBattleScene/bs1/bs1_reward_1.png")

二进制
tasks/Component/CostumeBattleScene/bs1/bs1_reward_1.png


+ 11 - 0
tasks/Component/CostumeBattleScene/bs1/image.json

@@ -0,0 +1,11 @@
+[
+  {
+    "itemName": "reward_1",
+    "imageName": "bs1_reward_1.png",
+    "roiFront": "551,505,165,84",
+    "roiBack": "451,413,372,226",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": ""
+  }
+]

+ 18 - 2
tasks/Component/GeneralBattle/assets.py

@@ -64,6 +64,14 @@ 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")
+	# 左边随机点击
+	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")
 
 
 	# Image Rule Assets
@@ -135,6 +143,14 @@ class GeneralBattleAssets:
 	I_PRESET_WIT_NUMBER = RuleImage(roi_front=(40,655,37,37), roi_back=(9,636,100,74), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gb/gb_preset_wit_number.png")
 	# 战斗信息标识 
 	I_BATTLE_INFO = RuleImage(roi_front=(230,12,37,39), roi_back=(210,1,147,72), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gb/gb_battle_info.png")
+	# 战斗状态信息(移植自mine)
+	I_BATTLE_STATE_INFO = RuleImage(roi_front=(725,51,67,31), roi_back=(483,18,337,102), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gb/gb_battle_state_info.png")
+	# 皮肤确认弹窗(移植自mine)
+	I_GB_SKIN_CONFIRM = RuleImage(roi_front=(594,447,90,55), roi_back=(594,447,90,55), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gb/gb_gb_skin_confirm.png")
+	# 队伍退出确认弹窗(移植自mine)
+	I_GB_CHECK_TEAM_EXIT = RuleImage(roi_front=(507,288,270,54), roi_back=(411,233,452,247), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gb/gb_gb_check_team_exit.png")
+	# 契灵结算弹窗(移植自mine)
+	I_OVER_GHOST = RuleImage(roi_front=(697,409,89,32), roi_back=(697,409,89,32), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralBattle/gb/gb_over_ghost.png")
 
 
 	# Image Rule Assets
@@ -157,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
@@ -248,5 +266,3 @@ class GeneralBattleAssets:
 	I_END_FIX_2 = RuleImage(roi_front=(800,251,100,33), roi_back=(32,90,1137,547), threshold=0.85, method="Template matching", file="./tasks/Component/GeneralBattle/gw/gw_end_fix_2.png")
 	#  
 	I_END_FIX_3 = RuleImage(roi_front=(871,278,150,49), roi_back=(119,66,1136,620), threshold=0.85, method="Template matching", file="./tasks/Component/GeneralBattle/gw/gw_end_fix_3.png")
-
-

+ 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

@@ -76,6 +76,7 @@
 import random
 import time
 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
@@ -1344,39 +1347,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": "下边随机点击"
   }
 ]

二进制
tasks/Component/GeneralBattle/gb/gb_battle_state_info.png


二进制
tasks/Component/GeneralBattle/gb/gb_gb_check_team_exit.png


二进制
tasks/Component/GeneralBattle/gb/gb_gb_skin_confirm.png


二进制
tasks/Component/GeneralBattle/gb/gb_over_ghost.png


+ 37 - 1
tasks/Component/GeneralBattle/gb/image.json

@@ -304,5 +304,41 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "战斗信息标识"
+  },
+  {
+    "itemName": "battle_state_info",
+    "imageName": "gb_battle_state_info.png",
+    "roiFront": "725,51,67,31",
+    "roiBack": "483,18,337,102",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "战斗状态信息(移植自mine)"
+  },
+  {
+    "itemName": "gb_skin_confirm",
+    "imageName": "gb_gb_skin_confirm.png",
+    "roiFront": "594,447,90,55",
+    "roiBack": "594,447,90,55",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "皮肤确认弹窗(移植自mine)"
+  },
+  {
+    "itemName": "gb_check_team_exit",
+    "imageName": "gb_gb_check_team_exit.png",
+    "roiFront": "507,288,270,54",
+    "roiBack": "411,233,452,247",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "队伍退出确认弹窗(移植自mine)"
+  },
+  {
+    "itemName": "over_ghost",
+    "imageName": "gb_over_ghost.png",
+    "roiFront": "697,409,89,32",
+    "roiBack": "697,409,89,32",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "契灵结算弹窗(移植自mine)"
   }
-]
+]

+ 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": "绿标区域"
   }
 ]

+ 109 - 38
tasks/Component/GeneralBattle/general_battle.py

@@ -3,16 +3,18 @@
 # github https://github.com/runhey
 import time
 import random
+import difflib
 from time import sleep
 
 import cv2
 from module.base.timer import Timer
+from module.config.utils import convert_to_underscore
 
 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
@@ -41,7 +43,11 @@ class GeneralBattle(BattleWait, GeneralBuff):
         self.battle_before(buff, config)
         # 绿标
         if self.is_in_battle(False):
-            self.green_mark(config.green_enable, config.green_mark)
+            self.green_mark(
+                config.green_enable, config.green_mark,
+                green_mark_type=config.green_mark_type,
+                green_mark_name=config.green_mark_name,
+            )
         # 战中设置
         win = self.battle_wait(random_click_swipt_enable=config.random_click_swipt_enable)
         if win:
@@ -317,47 +323,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):
         """
@@ -670,3 +707,37 @@ if __name__ == '__main__':
     unselected_color = get_unselect_color(self.C_PRESET_TEAM_1, self.C_PRESET_TEAM_2, self.C_PRESET_TEAM_3,
                                           size=color_size
                                           )
+
+
+def run_task_or_default_general_battle(task) -> bool:
+    """
+    超时或异常时接管战斗的兜底函数
+    https://github.com/runhey/OnmyojiAutoScript/issues/1884
+    """
+    # Config exposes task groups, not a top-level general_battle_config.
+    # Some tasks initialize conf themselves; navigation also runs before run().
+    sources = [getattr(task, 'conf', None)]
+    task_name = getattr(getattr(task.config, 'model', None), 'running_task', '')
+    if not task_name:
+        task_name = getattr(getattr(task, 'navigator', None), 'task_category', '')
+    if isinstance(task_name, str) and task_name:
+        sources.append(getattr(task.config, convert_to_underscore(task_name), None))
+    sources.append(task.config)
+    config = next((
+        candidate for source in sources
+        if isinstance(candidate := getattr(source, 'general_battle_config', None), GeneralBattleConfig)
+    ), None)
+
+    # Reuse task overrides, counters and asset customizations. Do not catch
+    # exceptions from the battle itself and accidentally start a second run.
+    run_battle = getattr(task, 'run_general_battle', None)
+    if callable(run_battle):
+        return run_battle(config=config)
+
+    class DefaultGeneralBattle(GeneralBattle):
+        def get_task_name(self):
+            # Costume setup validates the scheduler task against its owner.
+            return task.get_task_name()
+
+    gb = DefaultGeneralBattle(config=task.config, device=task.device)
+    return gb.run_general_battle(config=config)

+ 1 - 2
tasks/Component/RightActivity/right_activity.py

@@ -12,8 +12,7 @@ from tasks.Component.RightActivity.assets import RightActivityAssets
 
 class RightActivity(GameUi, RightActivityAssets):
     def enter(self, target: RuleImage):
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
         self.ui_click(self.I_TOGGLE_BUTTON, target, interval=2)
         self.ui_click_until_disappear(target, interval=3)

+ 3 - 3
tasks/Component/SwitchAccount/switch_account.py

@@ -35,11 +35,11 @@ class SwitchAccount(LoginAccount, ExitGame, GameUi, SwitchAccountAssets):
     def switchAccount(self):
         logger.info("start switchAccount %s-%s", self.to_account_info.character, self.to_account_info.svr)
         # 判断所处界面
-        curPage = self.ui_get_current_page()
+        curPage = self.get_current_page()
 
         if curPage != page_login and curPage != page_main:
-            self.ui_goto(page_main)
-            curPage = self.ui_get_current_page()
+            self.goto_page(page_main)
+            curPage = self.get_current_page()
         if curPage == page_main:
             self.exitGame()
 

+ 3 - 3
tasks/DailyTrifles/page.py

@@ -1,8 +1,8 @@
 from tasks.DailyTrifles.assets import DailyTriflesAssets
-from tasks.GameUi.assets import GameUiAssets
 from tasks.GameUi.page import Page, page_mall
+from tasks.GlobalGame.assets import GlobalGameAssets
 
 # 商店礼包屋页面
 page_store_gift_room = Page(DailyTriflesAssets.I_GIFT_RECOMMEND)
-page_store_gift_room.link(button=GameUiAssets.I_BACK_Y, destination=page_mall)
-page_mall.link(button=DailyTriflesAssets.I_ROOM_GIFT, destination=page_store_gift_room)
+page_store_gift_room.connect(page_mall, GlobalGameAssets.I_UI_BACK_YELLOW, key="page_store_gift_room->page_mall")
+page_mall.connect(page_store_gift_room, DailyTriflesAssets.I_ROOM_GIFT, key="page_mall->page_store_gift_room")

+ 8 - 15
tasks/DailyTrifles/script_task.py

@@ -43,8 +43,7 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
         raise TaskEnd('DailyTrifles')
 
     def run_one_summon(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_summon)
+        self.goto_page(page_summon)
         config=self.config.daily_trifles.trifles_config
         if config.summon_type == SummonType.default:
             self.summon_one(draw_mystery_pattern=config.draw_mystery_pattern)
@@ -82,10 +81,8 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
 
             for i in range(len(list)):
                 sleep(1)
-                self.ui_get_current_page()
-                self.ui_goto(page_main)
-                self.ui_get_current_page()
-                self.ui_goto(page_summon)
+                self.goto_page(page_main)
+                self.goto_page(page_summon)
                 self.appear_then_click(self.I_UI_BACK_RED, interval=1)
                 x, y = list[i].coord()
                 self.device.click(x, y)
@@ -154,8 +151,7 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
         pass
 
     def run_luck_msg(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_friends)
+        self.goto_page(page_friends)
         while 1:
             self.screenshot()
             if self.appear(self.I_LUCK_TITLE):
@@ -184,8 +180,7 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
         self.ui_click(self.I_UI_BACK_RED, self.I_CHECK_MAIN)
 
     def run_friend_love(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_friends)
+        self.goto_page(page_friends)
         while 1:
             self.screenshot()
             if self.appear(self.I_L_LOVE):
@@ -214,8 +209,7 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
         self.ui_click(self.I_UI_BACK_RED, self.I_CHECK_MAIN)
 
     def run_store(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_mall, confirm_wait=3)
+        self.goto_page(page_mall, confirm_wait=3)
 
         if self.config.daily_trifles.trifles_config.store_sign:
             self.run_store_sign()
@@ -223,12 +217,11 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
             self.run_buy_sushi()
 
         self.ui_click(self.I_UI_BACK_YELLOW, self.I_CHECK_MALL, interval=2.4, timeout=8)
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
     def run_store_sign(self):
 
-        self.ui_goto_page(page_store_gift_room)
+        self.goto_page(page_store_gift_room)
         self.screenshot()
         self.appear_then_click(self.I_GIFT_RECOMMEND, interval=1)
         logger.info('Enter store sign')

+ 14 - 3
tasks/Delegation/script_task.py

@@ -17,8 +17,7 @@ from tasks.Delegation.assets import DelegationAssets
 class ScriptTask(GameUi, DelegationAssets):
 
     def run(self):
-        self.ui_get_current_page()
-        self.ui_goto(page_delegation)
+        self.goto_page(page_delegation)
         self.check_reward()
         con: DelegationConfig = self.config.delegation.delegation_config
         if con.miyoshino_painting:
@@ -122,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
 

+ 16 - 8
tasks/DemonEncounter/assets.py

@@ -60,14 +60,22 @@ class DemonEncounterAssets:
 
 
 	# Click Rule Assets
-	# 从下开始数第一个 
-	C_DE_1 = RuleClick(roi_front=(1211,478,61,58), roi_back=(1211,478,61,58), name="de_1")
+	# 从下开始数第一个(点击区已收缩, 仅包住内部图形)
+	C_DE_1 = RuleClick(roi_front=(1222,497,39,25), roi_back=(1222,497,39,25), name="de_1")
 	# 2 
-	C_DE_2 = RuleClick(roi_front=(1196,409,55,56), roi_back=(1196,409,55,56), name="de_2")
+	C_DE_2 = RuleClick(roi_front=(1204,424,39,31), roi_back=(1204,424,39,31), name="de_2")
 	# 3 
-	C_DE_3 = RuleClick(roi_front=(1225,344,53,55), roi_back=(1225,344,53,55), name="de_3")
+	C_DE_3 = RuleClick(roi_front=(1234,364,32,22), roi_back=(1234,364,32,22), name="de_3")
 	# 第四个 
-	C_DE_4 = RuleClick(roi_front=(1200,282,56,53), roi_back=(1200,282,56,53), name="de_4")
+	C_DE_4 = RuleClick(roi_front=(1214,297,34,27), roi_back=(1214,297,34,27), name="de_4")
+	# 灯笼1类型识别搜索区(须容纳完整灯笼图案, 仅供check_lantern匹配, 不用于点击)
+	C_DE_MATCH_1 = RuleClick(roi_front=(1211,478,61,58), roi_back=(1211,478,61,58), name="de_match_1")
+	# 灯笼2类型识别搜索区
+	C_DE_MATCH_2 = RuleClick(roi_front=(1196,409,55,56), roi_back=(1196,409,55,56), name="de_match_2")
+	# 灯笼3类型识别搜索区
+	C_DE_MATCH_3 = RuleClick(roi_front=(1225,344,53,55), roi_back=(1225,344,53,55), name="de_match_3")
+	# 灯笼4类型识别搜索区
+	C_DE_MATCH_4 = RuleClick(roi_front=(1200,282,56,53), roi_back=(1200,282,56,53), name="de_match_4")
 
 
 	# Image Rule Assets
@@ -96,6 +104,8 @@ class DemonEncounterAssets:
 	I_DE_BALLOON = RuleImage(roi_front=(1214,295,28,27), roi_back=(1198,269,81,266), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_balloon.png")
 	# 右侧的宝箱 
 	I_DE_BOX = RuleImage(roi_front=(1210,295,34,33), roi_back=(1183,278,96,277), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_box.png")
+	# 地图中央未购买的宝箱展示
+	I_DE_BOX_CENTER = RuleImage(roi_front=(618,325,45,34), roi_back=(547,264,190,157), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_box_center.png")
 	# 挑战某一个后的封印图片 
 	I_DE_DEFEAT_2 = RuleImage(roi_front=(1211,422,28,35), roi_back=(1211,422,28,35), threshold=0.7, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_defeat_2.png")
 	# description 
@@ -126,7 +136,7 @@ class DemonEncounterAssets:
 	# 计数已经开启多少的 
 	O_DE_COUNTER = RuleOcr(roi=(1204,685,48,34), area=(1204,685,48,34), mode="DigitCounter", method="Default", keyword="", name="de_counter")
 	# 现世逢魔顶部今日挑战次数X/1的最小识别区, 0/1表示已打过直接结束 
-	O_DE_CHALLENGE_COUNT = RuleOcr(roi=(705,68,45,36), area=(705,68,45,36), mode="Full", method="Default", keyword="", name="de_challenge_count")
+	O_DE_CHALLENGE_COUNT = RuleOcr(roi=(705,68,45,36), area=(705,68,45,36), mode="DigitCounter", method="Default", keyword="", name="de_challenge_count")
 
 
 	# Click Rule Assets
@@ -149,5 +159,3 @@ class DemonEncounterAssets:
 	O_LETTER_ANSWER_2 = RuleOcr(roi=(428,350,438,74), area=(428,350,438,74), mode="Single", method="Default", keyword="", name="letter_answer_2")
 	# 回答三 
 	O_LETTER_ANSWER_3 = RuleOcr(roi=(428,439,443,72), area=(428,439,443,72), mode="Single", method="Default", keyword="", name="letter_answer_3")
-
-

+ 32 - 8
tasks/DemonEncounter/demon/click.json

@@ -1,26 +1,50 @@
 [
   {
     "itemName": "de_1",
-    "roiFront": "1211,478,61,58",
-    "roiBack": "1211,478,61,58",
+    "roiFront": "1222,497,39,25",
+    "roiBack": "1222,497,39,25",
     "description": "从下开始数第一个"
   },
   {
     "itemName": "de_2",
-    "roiFront": "1196,409,55,56",
-    "roiBack": "1196,409,55,56",
+    "roiFront": "1204,424,39,31",
+    "roiBack": "1204,424,39,31",
     "description": "2"
   },
   {
     "itemName": "de_3",
-    "roiFront": "1225,344,53,55",
-    "roiBack": "1225,344,53,55",
+    "roiFront": "1234,364,32,22",
+    "roiBack": "1234,364,32,22",
     "description": "3"
   },
   {
     "itemName": "de_4",
+    "roiFront": "1214,297,34,27",
+    "roiBack": "1214,297,34,27",
+    "description": "第四个"
+  },
+  {
+    "itemName": "de_match_1",
+    "roiFront": "1211,478,61,58",
+    "roiBack": "1211,478,61,58",
+    "description": "灯笼1类型识别搜索区(须容纳完整灯笼图案, 仅供check_lantern匹配, 不用于点击)"
+  },
+  {
+    "itemName": "de_match_2",
+    "roiFront": "1196,409,55,56",
+    "roiBack": "1196,409,55,56",
+    "description": "灯笼2类型识别搜索区"
+  },
+  {
+    "itemName": "de_match_3",
+    "roiFront": "1225,344,53,55",
+    "roiBack": "1225,344,53,55",
+    "description": "灯笼3类型识别搜索区"
+  },
+  {
+    "itemName": "de_match_4",
     "roiFront": "1200,282,56,53",
     "roiBack": "1200,282,56,53",
-    "description": "第四个"
+    "description": "灯笼4类型识别搜索区"
   }
-]
+]

二进制
tasks/DemonEncounter/demon/demon_de_box_center.png


+ 10 - 1
tasks/DemonEncounter/demon/image.json

@@ -79,5 +79,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "50勾玉购买"
+  },
+  {
+    "itemName": "de_box_center",
+    "imageName": "demon_de_box_center.png",
+    "roiFront": "618,325,45,34",
+    "roiBack": "547,264,190,157",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "地图中央未购买的宝箱展示"
   }
-]
+]

+ 1 - 1
tasks/DemonEncounter/demon/ocr.json

@@ -12,7 +12,7 @@
     "itemName": "de_challenge_count",
     "roiFront": "705,68,45,36",
     "roiBack": "705,68,45,36",
-    "mode": "Full",
+    "mode": "DigitCounter",
     "method": "Default",
     "keyword": "",
     "description": "现世逢魔顶部今日挑战次数X/1的最小识别区, 0/1表示已打过直接结束"

+ 89 - 51
tasks/DemonEncounter/script_task.py

@@ -3,20 +3,19 @@
 # github https://github.com/runhey
 import time
 from time import sleep
-import re
 
 from enum import Enum
 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
@@ -41,14 +40,13 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
         if not self.check_time():
             logger.warning('Time is not right')
             raise TaskEnd('DemonEncounter')
-        self.ui_get_current_page()
         # 切换御魂
         soul_config = self.config.demon_encounter.demon_soul_config
         best_soul_config = self.config.demon_encounter.best_demon_soul_config
         if soul_config.enable or best_soul_config.enable:
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.checkout_soul()
-        self.ui_goto(page_demon_encounter_realworld)
+        self.goto_page(page_demon_encounter_realworld)
         # 顶部"今日挑战次数:X/1"检测, 0/1表示今日已打过, 直接结束
         if self.check_challenge_done():
             logger.info('Challenge count 0/1, already challenged today')
@@ -62,16 +60,16 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
 
     def check_challenge_done(self) -> bool:
         """
-        OCR识别现世逢魔顶部"今日挑战次数:X/1"
-        :return: True表示0/1今日已打过
+        OCR识别现世逢魔顶部"今日挑战次数:剩余/总", 支持老号X/1与新号X/2
+        DigitCounter 返回 (current, remain, total), current 即剩余次数
+        :return: True表示剩余=0, 今日已打过
         """
-        results = self.O_DE_CHALLENGE_COUNT.detect_and_ocr(self.device.image)
-        text = ''.join(r.ocr_text for r in results)
-        m = re.search(r'([01])\s*/\s*1', text)
-        if not m:
-            logger.warning(f'Challenge count not recognized: [{text}], continue by default')
-            return False
-        return m.group(1) == '0'
+        current, _remain, total = self.O_DE_CHALLENGE_COUNT.ocr(self.device.image)
+        if total > 0:
+            logger.info(f'Demon encounter challenge count: {current}/{total}')
+            return current == 0
+        logger.warning('Challenge count not recognized, assume attempts remain')
+        return False
 
     def checkout_soul(self):
         """
@@ -95,40 +93,77 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
         logger.hr('Start boss battle', 1)
 
         def find_boss():
-            find_btn_clicked = False
-            timer_find_boss = Timer(10 * 60)
-            timer_find_boss.start()
-            while 1:
+            search_button = self.I_DE_BOSS_BEST if self.best_demon_enable else self.I_DE_BOSS
+            boss_name = 'best boss' if self.best_demon_enable else 'normal boss'
+
+            # 每轮搜索前若中央有未购买的宝箱展示, 先点左下角定位(小指针)把它挪开;
+            # 一整轮(2次搜索)都没找到则重进逢魔之时清状态, 最多3轮。
+            for reenter_round in range(1, 4):
                 self.screenshot()
-                if self.appear(self.I_BOSS_FIRE) or self.appear(self.I_BEST_BOSS_FIRE):
-                    break
-                if timer_find_boss.reached():
-                    logger.warning('find boss timeout')
-                    self.set_next_run(task='DemonEncounter', success=False, finish=True, server=False)
-                    raise TaskEnd('DemonEncounter')
-                if self.appear(self.I_JADE_50):
-                    # 没找到boss但地图中央出现宝箱,导致点击宝箱出现50勾玉购买界面
-                    self.ui_click_until_smt_disappear(self.I_DE_FIND, self.I_JADE_50, interval=1)
-                    continue
-                if find_btn_clicked and self.click(self.C_DM_BOSS_CLICK, interval=5):
-                    find_btn_clicked = False
-                    continue
-                if self.best_demon_enable:
+                if self.appear(self.I_DE_BOX_CENTER):
+                    logger.info(
+                        f'Box display at map center, click location to reset view '
+                        f'(round {reenter_round}/3)'
+                    )
+                    self.appear_then_click(self.I_DE_LOCATION, interval=2)
+                    time.sleep(1)
+
+                # 最多重新执行三轮“逢魔/极逢魔 -> 地图中央首领”的完整流程。
+                for search_attempt in range(1, 4):
                     self.device.click_record_clear()
-                    if self.appear(self.I_DE_BOSS_BEST) and (not find_btn_clicked):
-                        self.device.click_record_remove(self.I_DE_BOSS_BEST)
-                        if self.click(self.I_DE_BOSS_BEST, interval=4):
-                            logger.info("Finding best boss...")
-                            find_btn_clicked = True
-                        continue
-                else:
-                    if self.appear(self.I_DE_BOSS) and (not find_btn_clicked):
-                        self.device.click_record_remove(self.I_DE_BOSS)
-                        if self.click(self.I_DE_BOSS, interval=4):
-                            logger.info("Finding normal boss...")
-                            find_btn_clicked = True
+                    self.screenshot()
+                    if self.appear(self.I_BOSS_FIRE) or self.appear(self.I_BEST_BOSS_FIRE):
+                        return True
+                    # 没找到boss但地图中央出现宝箱, 导致点击宝箱出现50勾玉购买界面(事后补救)
+                    if self.appear(self.I_JADE_50):
+                        self.ui_click_until_smt_disappear(self.I_DE_FIND, self.I_JADE_50, interval=1)
                         continue
-            return True
+                    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}/3 '
+                        f'(re-enter round {reenter_round}/3)...'
+                    )
+                    time.sleep(1)
+
+                    # 每轮点击地图中央框选的红色“集结”区域至多三次,
+                    # 每次等待集结挑战标志5秒。
+                    for center_attempt in range(1, 4):
+                        self.click(self.C_DM_BOSS_CLICK, interval=2)
+                        deadline = time.monotonic() + 5
+                        while time.monotonic() < deadline:
+                            self.screenshot()
+                            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}/3'
+                                )
+                                return True
+                            time.sleep(0.2)
+                        logger.warning(
+                            f'{boss_name} gather did not appear after center click '
+                            f'{center_attempt}/3'
+                        )
+
+                    # 本轮失败,返回逢魔地图,重新点击逢魔/极逢魔进行下一轮搜寻。
+                    self.screenshot()
+                    if self.appear(self.I_UI_BACK_RED):
+                        self.appear_then_click(self.I_UI_BACK_RED, interval=2)
+                        deadline = time.monotonic() + 5
+                        while time.monotonic() < deadline:
+                            self.screenshot()
+                            if self.appear(search_button):
+                                break
+                            time.sleep(0.2)
+
+                # 3次搜索都没找到: 重进地图清状态, 最多3轮
+                logger.info(f'Boss not found, re-enter demon encounter map (round {reenter_round}/3)')
+                self.goto_page(page_town)
+                self.goto_page(page_demon_encounter_realworld)
+
+            raise GameStuckError(
+                f'Cannot enter {boss_name} after 3 re-enter rounds'
+            )
 
         def enter_boss():
             logger.info('trying to enter boss...')
@@ -294,11 +329,13 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
         :param index: 四个灯笼,从1开始
         :return:
         """
+        # 分类模板的搜索区(须容纳完整灯笼图案), 与点击区 C_DE_* 分离:
+        # 点击区只包住内部图形, 模板放不进搜索区会全部误判成 battle
         match_roi = {
-            1: self.C_DE_1.roi_front,
-            2: self.C_DE_2.roi_front,
-            3: self.C_DE_3.roi_front,
-            4: self.C_DE_4.roi_front,
+            1: self.C_DE_MATCH_1.roi_front,
+            2: self.C_DE_MATCH_2.roi_front,
+            3: self.C_DE_MATCH_3.roi_front,
+            4: self.C_DE_MATCH_4.roi_front,
         }
         match_empty = {
             1: self.I_DE_DEFEAT_1,
@@ -423,9 +460,10 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
                     break
                 # 如果没有出现红色关闭按钮,说明答题结束
                 if not self.appear(self.I_LETTER_CLOSE):
-                    time.sleep(1.8)
+                    time.sleep(2.5)
                     self.screenshot()
                     if not self.appear(self.I_LETTER_CLOSE):
+                        self.ui_reward_appear_click()
                         logger.warning('Answer finish')
                         return
 

+ 4 - 8
tasks/DemonRetreat/script_task.py

@@ -49,12 +49,10 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DemonRetreatAssets, AbyssSha
             raise TaskEnd
 
         if cfg.switch_soul_config.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(cfg.switch_soul_config.switch_group_team)
         if cfg.switch_soul_config.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(cfg.switch_soul_config.group_name, cfg.switch_soul_config.team_name)
 
         # 进入妖怪退治
@@ -105,9 +103,8 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DemonRetreatAssets, AbyssSha
         进入首领退治
         """
         cfg: DemonRetreat = self.config.demon_retreat
-        self.ui_get_current_page()
         logger.info("Entering demon_retreat")
-        self.ui_goto(page_guild)
+        self.goto_page(page_guild)
 
         goto_demon_retreat_num = 0
         while 1:
@@ -262,9 +259,8 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DemonRetreatAssets, AbyssSha
     def goto_main(self):
         ''' 保持好习惯,一个任务结束了就返回庭院,方便下一任务的开始或者是出错重启
         '''
-        self.ui_get_current_page()
         logger.info("Exiting DemonRetreat")
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
 
 

+ 3 - 4
tasks/Dokan/script_task.py

@@ -511,8 +511,8 @@ class ScriptTask(ExtendGreenMark, GameUi, SwitchSoul, DokanSceneDetector):
             if self.appear(self.I_RYOU_DOKAN_DOKAN_QUIT):
                 self.click(self.I_RYOU_DOKAN_DOKAN_QUIT, interval=3)
                 continue
-            if self.appear(self.I_BACK_BL):
-                self.click(self.I_BACK_BL, interval=3)
+            if self.appear(self.I_UI_BACK_BLUE):
+                self.click(self.I_UI_BACK_BLUE, interval=3)
                 continue
             if self.appear(self.I_BACK_Y):
                 self.click(self.I_BACK_Y, interval=3)
@@ -533,8 +533,7 @@ class ScriptTask(ExtendGreenMark, GameUi, SwitchSoul, DokanSceneDetector):
                 self.ui_click_until_disappear(self.I_RYOU_DOKAN, interval=1)
                 continue
             if not in_dokan:
-                self.ui_get_current_page()
-                self.ui_goto(page_guild)
+                self.goto_page(page_guild)
                 continue
         self.device.screenshot_interval_set()
         return True

+ 9 - 11
tasks/Duel/script_task.py

@@ -45,26 +45,26 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DuelAssets, SwitchOnmyoji):
             self.screenshot()
             self.check_and_get_reward()
             if not self.duel_main():
-                self.ui_goto_page(page_duel)
+                self.goto_page(page_duel)
                 continue
             if not self.can_start_duel():
                 break
             self.start_duel()
         logger.info('Duel battle end')
         self.set_next_run(task='Duel', success=True, finish=True)
-        self.ui_goto_page(page_main)
+        self.goto_page(page_main)
         # 调起花合战
         self.set_next_run(task='TalismanPass', target=datetime.now())
         raise TaskEnd('Duel')
 
     def prepare_duel(self):
         """斗技准备工作(切换御魂or阴阳师...), 最后回到斗技主界面"""
-        self.ui_goto_page(page_main)
+        self.goto_page(page_main)
         self.switch_soul()
         if self.conf.duel_config.switch_enabled:
-            self.ui_goto_page(page_onmyodo)
+            self.goto_page(page_onmyodo)
             self.switch_onmyoji(self.conf.duel_config.switch_onmyoji)
-        self.ui_goto_page(page_duel)
+        self.goto_page(page_duel)
         self.switch_all_soul()
         self.current_score = self.conf.duel_celeb_config.initial_score
 
@@ -108,7 +108,7 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DuelAssets, SwitchOnmyoji):
         logger.info(f'battle result: {battle_ret}')
         logger.info(f'battle count:{self.current_count} | win:{self.battle_win_count} failure:{self.battle_lose_count}')
         logger.info(f'battle time: {task_run_time_seconds} / {self.limit_time}')
-        self.ui_goto_page(page_duel)
+        self.goto_page(page_duel)
 
     def enter_battle(self):
         """点击开始战斗(一直到出现战斗准备界面)"""
@@ -174,7 +174,7 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DuelAssets, SwitchOnmyoji):
                 ret_timer.reset()
                 continue
             if ret_timer.started() and ret_timer.reached():  # 兜底逻辑, 已经结算了但是还没有到斗技主界面
-                self.ui_goto_page(page_duel)
+                self.goto_page(page_duel)
                 break
             if self.is_battle_win():
                 ret = True
@@ -255,12 +255,10 @@ class ScriptTask(GameUi, GeneralBattle, SwitchSoul, DuelAssets, SwitchOnmyoji):
     def switch_soul(self):
         """从式神录界面切换御魂"""
         if self.conf.switch_soul.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            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.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(self.conf.switch_soul.group_name, self.conf.switch_soul.team_name)
 
     def duel_main(self, screenshot=False) -> bool:

+ 4 - 8
tasks/DyeTrials/script_task.py

@@ -24,21 +24,17 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, DyeTrialsAssets):
 
         # 自动换御魂
         if cfg.switch_soul_config.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(cfg.switch_soul_config.switch_group_team)
         if cfg.switch_soul_config.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(cfg.switch_soul_config.group_name, cfg.switch_soul_config.team_name)
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
         self.get_all()
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
         self.set_next_run(task='DyeTrials', success=True, finish=True)
         raise TaskEnd('DyeTrials')

+ 9 - 32
tasks/EternitySea/script_task.py

@@ -7,7 +7,7 @@ from module.exception import TaskEnd
 from module.base.timer import Timer
 from module.logger import logger
 
-from tasks.GameUi.game_ui import GameUi, Page
+from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.page import page_soul_zones, page_shikigami_records
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
 from tasks.Component.GeneralRoom.general_room import GeneralRoom
@@ -29,13 +29,11 @@ class ScriptTask(
 
     def _two_teams_switch_sous(self, config):
         if config.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(config.switch_group_team)
 
         if config.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(config.group_name, config.team_name)
 
     def run(self) -> None:
@@ -46,7 +44,7 @@ class ScriptTask(
             case UserStatus.MEMBER: success = self.run_member()
             case UserStatus.ALONE: success = self.run_alone()
             case _: logger.error('Unknown user status')
-
+        self.goto_page(page_main)
         if success:
             self.set_next_run(self.task_name, finish=True, success=True)
         else:
@@ -57,7 +55,7 @@ class ScriptTask(
 
     def run_leader(self):
         logger.info('Start run leader')
-        self._navigate_to_soul_zones()
+        self.goto_page(page_soul_zones)
         self._enter_eternity_sea()
         layer = self._task_config.eternity_sea_config.layer
         self.check_layer(layer)
@@ -135,8 +133,7 @@ class ScriptTask(
         # 永生之海选层界面无HOME按钮且页面系统识别不了, 点返回箭头回到御魂副本选择界面
         self._back_to_soul_zones()
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
         if not success:
             return False
@@ -166,7 +163,7 @@ class ScriptTask(
         timer = Timer(15).start()
         while not timer.reached():
             self.screenshot()
-            if self.ui_page_appear(page_soul_zones):
+            if self.match_page_once(page_soul_zones):
                 return
             if self.appear_then_click(self.I_GI_SURE, interval=1):
                 continue
@@ -180,7 +177,6 @@ class ScriptTask(
 
     def run_member(self):
         logger.info('Start run member')
-        self.ui_get_current_page()
         # self.ui_goto(page_soul_zones)
         # self.orochi_enter()
         # self.check_lock(self.config.orochi.general_battle_config.lock_team_enable)
@@ -222,14 +218,13 @@ class ScriptTask(
             if self.exit_battle():
                 pass
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         return True
 
 
     def run_alone(self) -> bool:
         logger.info("Start run alone")
-        self._navigate_to_soul_zones()
+        self.goto_page(page_soul_zones)
         self._enter_eternity_sea()
 
         if self._task_config.general_battle_config.lock_team_enable == False:
@@ -271,16 +266,6 @@ class ScriptTask(
                 return True
         return False
 
-    def eternitysea_enter(self) -> bool:
-        logger.info('Enter EternitySea')
-        while True:
-            self.screenshot()
-            if self.appear(self.I_FORM_TEAM):
-                return True
-            if self.appear_then_click(self.I_ETERNITY_SEA, interval=1):
-                continue
-
-
     def _is_in_eternity_sea(self) -> bool:
         self.screenshot()
         return self.appear(self.I_ETERNITY_SEA_FIRE)
@@ -304,14 +289,6 @@ class ScriptTask(
             if self.appear_then_click(self.I_BACK_BOTTOM, interval=1):
                 continue
 
-    def _navigate_to_soul_zones(self) -> None:
-        self.ui_get_current_page()
-        self.ui_goto(page_soul_zones)
-
-    def _navigate_to_game_page(self, destination: Page) -> None:
-        self.ui_get_current_page()
-        self.ui_goto(destination)
-
     @property
     def _task_config(self) -> EternitySea:
         return self.config.model.eternity_sea

+ 2 - 4
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")
 	# 式神录 
@@ -42,5 +42,3 @@ class EvoZoneAssets:
 	# Ocr Rule Assets
 	# Ocr-description 
 	O_O_TEST_OCR = RuleOcr(roi=(128,114,349,564), area=(128,114,349,564), mode="Full", method="Default", keyword="", name="o_test_ocr")
-
-

+ 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 - 17
tasks/EvoZone/script_task.py

@@ -31,16 +31,13 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
                                                seconds=limit_time.second)
         con = self.config.evo_zone
         if con.switch_soul_config.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(con.switch_soul_config.switch_group_team)
         if con.switch_soul_config.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(con.switch_soul_config.group_name, con.switch_soul_config.team_name)
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         config: EvoZone = self.config.evo_zone
         if config.evo_zone_config.soul_buff_enable:
             self.open_buff()
@@ -126,9 +123,8 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
 
     def run_leader(self):
         logger.info('Start run leader')
-        self.ui_get_current_page()
         # self.ui_goto(page_soul_zones)
-        self.ui_goto(page_awake_zones)
+        self.goto_page(page_awake_zones)
         self.evozone_enter()
         layer = self.config.evo_zone.evo_zone_config.layer
         logger.info("test0")
@@ -215,8 +211,7 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
         if self.exit_team():
             pass
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
         if not success:
             return False
@@ -224,7 +219,6 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
 
     def run_member(self):
         logger.info('Start run member')
-        self.ui_get_current_page()
         # self.ui_goto(page_soul_zones)
         # self.evozone_enter()
         # self.check_lock(self.config.evo_zone.general_battle_config.lock_team_enable)
@@ -269,14 +263,12 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
             if self.exit_battle():
                 pass
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         return True
 
     def run_alone(self):
         logger.info('Start run alone')
-        self.ui_get_current_page()
-        self.ui_goto(page_awake_zones)
+        self.goto_page(page_awake_zones)
         self.evozone_enter()
         layer = self.config.evo_zone.evo_zone_config.layer
         self.check_layer(layer)
@@ -322,8 +314,7 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
             if self.appear_then_click(self.I_BACK_Y, interval=1):
                 continue
 
-        self.ui_current = page_awake_zones
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
     def run_wild(self):
         logger.error('Wild mode is not implemented')

+ 5 - 10
tasks/ExperienceYoukai/script_task.py

@@ -23,21 +23,18 @@ class ScriptTask(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, SwitchSoul,
     def run(self):
         # 切换御魂
         if self.config.experience_youkai.switch_soul.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(self.config.experience_youkai.switch_soul.switch_group_team)
 
         if self.config.experience_youkai.switch_soul.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(self.config.experience_youkai.switch_soul.group_name,
                                          self.config.experience_youkai.switch_soul.team_name)
 
         # 开启加成
         con = self.config.experience_youkai.experience_youkai
         if con.buff_exp_50_click or con.buff_exp_100_click:
-            self.ui_get_current_page()
-            self.ui_goto(page_main)
+            self.goto_page(page_main)
             self.open_buff()
             if con.buff_exp_50_click:
                 self.exp_50()
@@ -46,8 +43,7 @@ class ScriptTask(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, SwitchSoul,
             self.close_buff()
         count = 0
         while count < 2:
-            self.ui_get_current_page()
-            self.ui_goto(page_team)
+            self.goto_page(page_team)
             self.check_zones('经验妖怪')
             # 开始
             if not self.create_room():
@@ -104,8 +100,7 @@ class ScriptTask(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, SwitchSoul,
                 return False
 
     def experience_exit(self, con):
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         if con.buff_exp_50_click or con.buff_exp_100_click:
             self.open_buff()
             if con.buff_exp_50_click:

+ 11 - 3
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
@@ -107,8 +111,10 @@ class ExplorationAssets:
 	I_GET_REWARD = RuleImage(roi_front=(464,231,339,44), roi_back=(464,231,339,44), threshold=0.8, method="Template matching", file="./tasks/Exploration/res/res_get_reward.png")
 	# description 
 	I_RED_CLOSE = RuleImage(roi_front=(1027,129,41,42), roi_back=(1021,121,54,55), threshold=0.6, method="Template matching", file="./tasks/Exploration/res/res_red_close.png")
-	# description 
+	# description
 	I_E_EXIT_CONFIRM = RuleImage(roi_front=(694,380,163,49), roi_back=(694,380,163,49), threshold=0.8, method="Template matching", file="./tasks/Exploration/res/res_e_exit_confirm.png")
+	# 探索章节切换文件夹图标(移植自mine)
+	I_E_OPEN_FOLDER = RuleImage(roi_front=(1241,114,22,28), roi_back=(1212,88,68,123), threshold=0.8, method="Template matching", file="./tasks/Exploration/res/res_e_open_folder.png")
 	# 宝箱 
 	I_TREASURE_BOX_CLICK = RuleImage(roi_front=(31,543,27,24), roi_back=(11,520,378,65), threshold=0.65, method="Template matching", file="./tasks/Exploration/res/res_treasure_box_click.png")
 	# 困28滚动到最后 
@@ -125,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
@@ -162,5 +172,3 @@ class ExplorationAssets:
 	S_SWIPE_SHIKI_TO_LEFT = RuleSwipe(roi_front=(890,587,21,21), roi_back=(351,584,21,21), mode="default", name="swipe_shiki_to_left")
 	# 滑动一个式神的宽度 
 	S_SWIPE_SHIKI_TO_LEFT_ONE = RuleSwipe(roi_front=(977,582,21,21), roi_back=(889,584,21,22), mode="default", name="swipe_shiki_to_left_one")
-
-

+ 15 - 13
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
 
@@ -89,21 +90,18 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
     def pre_process(self):
         explorationConfig = self._config
         if explorationConfig.switch_soul_config.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(explorationConfig.switch_soul_config.switch_group_team)
 
         if explorationConfig.switch_soul_config.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(explorationConfig.switch_soul_config.group_name,
                                          explorationConfig.switch_soul_config.team_name)
 
         # 开启加成
         con = self.config.exploration.exploration_config
         if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
-            self.ui_get_current_page()
-            self.ui_goto(page_main)
+            self.goto_page(page_main)
             self.open_buff()
             if con.buff_gold_50_click:
                 self.gold_50()
@@ -115,16 +113,15 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
                 self.exp_100()
             self.close_buff()
 
-        self.ui_get_current_page()
-        # 探索页面
-        self.ui_goto(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)
         if self.appear(self.I_UI_BACK_RED):
             self.ui_click_until_disappear(self.I_UI_BACK_RED)
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         con = self._config.exploration_config
         if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
             self.open_buff()
@@ -138,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
@@ -356,7 +358,7 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
             self.ui_click_until_disappear(self.I_UI_CANCEL)
         if self.appear(self.I_UI_CANCEL_SAMLL):
             self.ui_click_until_disappear(self.I_UI_CANCEL_SAMLL)
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
         if con.buff_gold_50_click or con.buff_gold_100_click or con.buff_exp_50_click or con.buff_exp_100_click:
             self.open_buff()
             self.gold_50(is_open=False)

+ 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标题"
   }
 ]

+ 28 - 1
tasks/Exploration/res/image.json

@@ -241,5 +241,32 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "战斗中的队友标识"
+  },
+  {
+    "itemName": "e_open_folder",
+    "imageName": "res_e_open_folder.png",
+    "roiFront": "1241,114,22,28",
+    "roiBack": "1212,88,68,123",
+    "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标题锚点(御魂)"
   }
-]
+]

二进制
tasks/Exploration/res/res_check_main_title.png


二进制
tasks/Exploration/res/res_check_play_title.png


二进制
tasks/Exploration/res/res_e_open_folder.png


+ 5 - 18
tasks/FallenSun/script_task.py

@@ -25,14 +25,12 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
     def run(self) -> bool:
         # 御魂切换方式一
         if self.config.fallen_sun.switch_soul.enable:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul(self.config.fallen_sun.switch_soul.switch_group_team)
 
         # 御魂切换方式二
         if self.config.fallen_sun.switch_soul.enable_switch_by_name:
-            self.ui_get_current_page()
-            self.ui_goto(page_shikigami_records)
+            self.goto_page(page_shikigami_records)
             self.run_switch_soul_by_name(self.config.fallen_sun.switch_soul.group_name,
                                          self.config.fallen_sun.switch_soul.team_name)
 
@@ -42,8 +40,6 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
         self.limit_count: int = limit_count
         self.limit_time: timedelta = timedelta(hours=limit_time.hour, minutes=limit_time.minute, seconds=limit_time.second)
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
         config: FallenSun = self.config.fallen_sun
 
         success = True
@@ -105,8 +101,7 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
 
     def run_leader(self):
         logger.info('Start run leader')
-        self.ui_get_current_page()
-        self.ui_goto(page_soul_zones)
+        self.goto_page(page_soul_zones)
         self.fallen_sun_enter()
         layer = self.config.fallen_sun.fallen_sun_config.layer
         self.check_layer(layer)
@@ -190,8 +185,6 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
         if self.exit_team():
             pass
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
 
         if not success:
             return False
@@ -199,7 +192,6 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
 
     def run_member(self):
         logger.info('Start run member')
-        self.ui_get_current_page()
         # self.ui_goto(page_soul_zones)
         # self.fallen_sun_enter()
         # self.check_lock(self.config.fallen_sun.general_battle_config.lock_team_enable)
@@ -245,14 +237,11 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
                 pass
 
 
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
         return True
 
     def run_alone(self):
         logger.info('Start run alone')
-        self.ui_get_current_page()
-        self.ui_goto(page_soul_zones)
+        self.goto_page(page_soul_zones)
         self.fallen_sun_enter()
         layer = self.config.fallen_sun.fallen_sun_config.layer
         self.check_layer(layer)
@@ -295,13 +284,11 @@ class ScriptTask(GeneralBattle, GeneralInvite, GeneralBuff, GeneralRoom, GameUi,
             self.screenshot()
             if not self.appear(self.I_FORM_TEAM):
                 break
-            if self.appear_then_click(self.I_BACK_BL, interval=2):
+            if self.appear_then_click(self.I_UI_BACK_BLUE, interval=2):
                 continue
             if self.appear_then_click(self.I_UI_BACK_YELLOW, interval=2):
                 continue
 
-        self.ui_current = page_soul_zones
-        self.ui_goto(page_main)
 
     def run_wild(self):
         logger.error('Wild mode is not implemented')

+ 1 - 2
tasks/FloatParade/script_task.py

@@ -41,8 +41,7 @@ class ScriptTask(RightActivity, FloatParadeAssets, TalismanPassAssets):
         self.get_flower(con.level_reward1, con.level_reward2) # 第一种
 
         # main page
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+        self.goto_page(page_main)
 
         self.set_next_run(task='FloatParade', success=True, finish=True)
         raise TaskEnd('FloatParade')

+ 25 - 11
tasks/FrogBoss/assets.py

@@ -12,23 +12,23 @@ class FrogBossAssets:
 
 	# Image Rule Assets
 	# 左边竞猜 
-	I_BET_LEFT = RuleImage(roi_front=(271,303,145,100), roi_back=(222,251,245,195), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_left.png")
+	I_BET_LEFT = RuleImage(roi_front=(288,301,120,102), roi_back=(222,251,245,195), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_left.png")
 	# 右边竞猜 
-	I_BET_RIGHT = RuleImage(roi_front=(1070,302,146,100), roi_back=(1048,248,187,208), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_right.png")
+	I_BET_RIGHT = RuleImage(roi_front=(1093,307,118,94), roi_back=(1048,248,187,208), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_right.png")
 	# description 
-	I_BET_SUCCESS_BOX = RuleImage(roi_front=(708,394,87,50), roi_back=(661,331,193,182), threshold=0.75, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success_box.png")
+	I_BET_SUCCESS_BOX = RuleImage(roi_front=(713,399,80,45), roi_back=(661,331,193,182), threshold=0.75, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success_box.png")
 	# 左边赢了 
 	I_SUCCESS_LEFT = RuleImage(roi_front=(292,306,100,100), roi_back=(238,243,202,221), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_left.png")
 	# 右边输了 
 	I_FAILURE_RIGHT = RuleImage(roi_front=(1097,303,100,100), roi_back=(1029,256,224,199), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_right.png")
-	# description 
-	I_NEXT_COMPETITION = RuleImage(roi_front=(775,485,42,36), roi_back=(692,437,157,147), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.png")
+	# 开始下一局
+	I_NEXT_COMPETITION = RuleImage(roi_front=(783,492,28,22), roi_back=(692,437,157,147), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.png")
 	# 30万金币 
 	I_GOLD_30 = RuleImage(roi_front=(862,499,78,76), roi_back=(831,441,147,187), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30.png")
 	# 确认竞猜 
 	I_BET_SURE = RuleImage(roi_front=(1025,402,100,100), roi_back=(972,340,200,226), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_sure.png")
-	# description 
-	I_GOLD_30_CHECK = RuleImage(roi_front=(513,196,58,53), roi_back=(402,141,459,489), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30_check.png")
+	# 获胜奖励说明弹窗中的竞猜金币
+	I_GOLD_30_CHECK = RuleImage(roi_front=(513,196,58,53), roi_back=(495,195,104,111), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30_check.png")
 	# description 
 	I_BETTED = RuleImage(roi_front=(1093,313,125,54), roi_back=(207,240,1058,312), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_betted.png")
 	# description 
@@ -36,7 +36,7 @@ class FrogBossAssets:
 	# description 
 	I_FAILURE_LEFT = RuleImage(roi_front=(296,303,100,100), roi_back=(243,245,212,259), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_left.png")
 	# description 
-	I_BET_FAILURE = RuleImage(roi_front=(591,290,269,72), roi_back=(496,222,447,211), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_failure.png")
+	I_BET_FAILURE = RuleImage(roi_front=(625,277,269,72), roi_back=(496,222,447,211), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_failure.png")
 	# description 
 	I_BET_SUCCESS = RuleImage(roi_front=(625,278,260,73), roi_back=(482,243,521,225), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success.png")
 
@@ -45,9 +45,23 @@ class FrogBossAssets:
 	# description 
 	I_FROG_BOSS_ENTER = RuleImage(roi_front=(1188,303,36,38), roi_back=(1169,203,78,320), threshold=0.7, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_enter.png")
 	# 休息中 
-	I_FROG_BOSS_REST = RuleImage(roi_front=(510,274,169,64), roi_back=(492,260,220,113), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_rest.png")
+	I_FROG_BOSS_REST = RuleImage(roi_front=(627,284,169,64), roi_back=(601,259,220,113), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_rest.png")
 	# 竞猜主页面
 	I_FROG_CHECK = RuleImage(roi_front=(664,31,148,65), roi_back=(551,4,371,145), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_check.png")
+	# 进入记录页面
+	I_FROG_LOG = RuleImage(roi_front=(1171,624,43,41), roi_back=(1157,601,83,89), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_log.png")
+	#
+	I_FROG_LOG_CHECK = RuleImage(roi_front=(549,31,192,52), roi_back=(469,0,371,145), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_log_check.png")
+	# 上一局胜
+	I_FROG_LAST_WIN = RuleImage(roi_front=(178,210,61,49), roi_back=(148,147,114,123), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_last_win.png")
+	# 上一局败
+	I_FROG_LAST_LOSE = RuleImage(roi_front=(178,210,61,49), roi_back=(148,147,114,123), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_last_lose.png")
+	# 关闭记录
+	I_FROG_LOG_CLOSE = RuleImage(roi_front=(1188,99,43,41), roi_back=(1166,73,83,89), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_log_close.png")
+	# 上一局选择红色
+	I_FROG_LAST_SELECT_RED = RuleImage(roi_front=(342,149,36,38), roi_back=(327,120,70,77), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_last_select_red.png")
+	# 上一句选择蓝色
+	I_FROG_LAST_SELECT_BLUE = RuleImage(roi_front=(342,149,36,38), roi_back=(327,120,70,77), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_last_select_blue.png")
 
 
 	# Ocr Rule Assets
@@ -57,5 +71,5 @@ class FrogBossAssets:
 	O_RIGHT_COUNT = RuleOcr(roi=(1139,472,77,32), area=(1139,472,77,32), mode="Digit", method="Default", keyword="", name="right_count")
 	# Ocr-description 
 	O_TIME_REMAIN = RuleOcr(roi=(705,533,91,35), area=(705,533,91,35), mode="Duration", method="Default", keyword="", name="time_remain")
-
-
+	# 上一句对局时间
+	O_FROG_LAST_TIME = RuleOcr(roi=(120,154,160,30), area=(120,154,160,30), mode="Single", method="Default", keyword="", name="frog_last_time")

二进制
tasks/FrogBoss/fb/fb_bet_failure.png


二进制
tasks/FrogBoss/fb/fb_bet_left.png


二进制
tasks/FrogBoss/fb/fb_bet_right.png


二进制
tasks/FrogBoss/fb/fb_bet_success_box.png


二进制
tasks/FrogBoss/fb/fb_failure_right.png


二进制
tasks/FrogBoss/fb/fb_frog_boss_rest.png


二进制
tasks/FrogBoss/fb/fb_frog_last_lose.png


二进制
tasks/FrogBoss/fb/fb_frog_last_select_blue.png


二进制
tasks/FrogBoss/fb/fb_frog_last_select_red.png


二进制
tasks/FrogBoss/fb/fb_frog_last_win.png


二进制
tasks/FrogBoss/fb/fb_frog_log.png


二进制
tasks/FrogBoss/fb/fb_frog_log_check.png


二进制
tasks/FrogBoss/fb/fb_frog_log_close.png


二进制
tasks/FrogBoss/fb/fb_next_competition.png


二进制
tasks/FrogBoss/fb/fb_success_left.png


+ 9 - 23
tasks/FrogBoss/fb/image.json

@@ -2,31 +2,28 @@
   {
     "itemName": "bet_left",
     "imageName": "fb_bet_left.png",
-    "roiFront": "271,303,145,100",
+    "roiFront": "288,301,120,102",
     "roiBack": "222,251,245,195",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "左边竞猜"
   },
   {
     "itemName": "bet_right",
     "imageName": "fb_bet_right.png",
-    "roiFront": "1070,302,146,100",
+    "roiFront": "1093,307,118,94",
     "roiBack": "1048,248,187,208",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "右边竞猜"
   },
   {
     "itemName": "bet_success_box",
     "imageName": "fb_bet_success_box.png",
-    "roiFront": "708,394,87,50",
+    "roiFront": "713,399,80,45",
     "roiBack": "661,331,193,182",
     "method": "Template matching",
     "threshold": 0.75,
-    "profile": "Default",
     "description": "description"
   },
   {
@@ -36,7 +33,6 @@
     "roiBack": "238,243,202,221",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "左边赢了"
   },
   {
@@ -46,18 +42,16 @@
     "roiBack": "1029,256,224,199",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "右边输了"
   },
   {
     "itemName": "next_competition",
     "imageName": "fb_next_competition.png",
-    "roiFront": "775,485,42,36",
+    "roiFront": "783,492,28,22",
     "roiBack": "692,437,157,147",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
-    "description": "description"
+    "description": "开始下一局"
   },
   {
     "itemName": "gold_30",
@@ -66,7 +60,6 @@
     "roiBack": "831,441,147,187",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "30万金币"
   },
   {
@@ -76,18 +69,16 @@
     "roiBack": "972,340,200,226",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "确认竞猜"
   },
   {
     "itemName": "gold_30_check",
     "imageName": "fb_gold_30_check.png",
     "roiFront": "513,196,58,53",
-    "roiBack": "402,141,459,489",
+    "roiBack": "495,195,104,111",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
-    "description": "description"
+    "description": "获胜奖励说明弹窗中的竞猜金币"
   },
   {
     "itemName": "betted",
@@ -96,7 +87,6 @@
     "roiBack": "207,240,1058,312",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "description"
   },
   {
@@ -106,7 +96,6 @@
     "roiBack": "1040,250,201,260",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "description"
   },
   {
@@ -116,17 +105,15 @@
     "roiBack": "243,245,212,259",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "bet_failure",
     "imageName": "fb_bet_failure.png",
-    "roiFront": "591,290,269,72",
+    "roiFront": "625,277,269,72",
     "roiBack": "496,222,447,211",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "description"
   },
   {
@@ -136,7 +123,6 @@
     "roiBack": "482,243,521,225",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "description"
   }
-]
+]

+ 66 - 6
tasks/FrogBoss/fb/image2.json

@@ -6,17 +6,15 @@
     "roiBack": "1169,203,78,320",
     "method": "Template matching",
     "threshold": 0.7,
-    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "frog_boss_rest",
     "imageName": "fb_frog_boss_rest.png",
-    "roiFront": "510,274,169,64",
-    "roiBack": "492,260,220,113",
+    "roiFront": "627,284,169,64",
+    "roiBack": "601,259,220,113",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "休息中"
   },
   {
@@ -26,7 +24,69 @@
     "roiBack": "551,4,371,145",
     "method": "Template matching",
     "threshold": 0.8,
-    "profile": "Default",
     "description": "竞猜主页面"
+  },
+  {
+    "itemName": "frog_log",
+    "imageName": "fb_frog_log.png",
+    "roiFront": "1171,624,43,41",
+    "roiBack": "1157,601,83,89",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "进入记录页面"
+  },
+  {
+    "itemName": "frog_log_check",
+    "imageName": "fb_frog_log_check.png",
+    "roiFront": "549,31,192,52",
+    "roiBack": "469,0,371,145",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": ""
+  },
+  {
+    "itemName": "frog_last_win",
+    "imageName": "fb_frog_last_win.png",
+    "roiFront": "178,210,61,49",
+    "roiBack": "148,147,114,123",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "上一局胜"
+  },
+  {
+    "itemName": "frog_last_lose",
+    "imageName": "fb_frog_last_lose.png",
+    "roiFront": "178,210,61,49",
+    "roiBack": "148,147,114,123",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "上一局败"
+  },
+  {
+    "itemName": "frog_log_close",
+    "imageName": "fb_frog_log_close.png",
+    "roiFront": "1188,99,43,41",
+    "roiBack": "1166,73,83,89",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "关闭记录"
+  },
+  {
+    "itemName": "frog_last_select_red",
+    "imageName": "fb_frog_last_select_red.png",
+    "roiFront": "342,149,36,38",
+    "roiBack": "327,120,70,77",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "上一局选择红色"
+  },
+  {
+    "itemName": "frog_last_select_blue",
+    "imageName": "fb_frog_last_select_blue.png",
+    "roiFront": "342,149,36,38",
+    "roiBack": "327,120,70,77",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "上一句选择蓝色"
   }
-]
+]

+ 9 - 0
tasks/FrogBoss/fb/ocr.json

@@ -25,5 +25,14 @@
     "method": "Default",
     "keyword": "",
     "description": "Ocr-description"
+  },
+  {
+    "itemName": "frog_last_time",
+    "roiFront": "120,154,160,30",
+    "roiBack": "120,154,160,30",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "",
+    "description": "上一句对局时间"
   }
 ]

+ 67 - 5
tasks/FrogBoss/frog_oas.py

@@ -74,8 +74,10 @@ class OasHistory:
         # Unverified newcomers start neutral; verified sources use raw win rate.
         return correct / total if total else 0.5
 
-    def settle(self, signature, winner):
-        if winner not in ('LEFT', 'RIGHT'):
+    def settle(self, signature, winner=None, *, bet_won=None):
+        if winner not in ('LEFT', 'RIGHT') and type(bet_won) is not bool:
+            self.append('unverified_result', signature=signature,
+                        reason='missing_winner_and_bet_outcome')
             return None
         # Include already settled records when checking ambiguity: never transfer
         # an old result to a newer decision with an identical lineup.
@@ -88,7 +90,64 @@ class OasHistory:
         decision = matches[0]
         if any(e.get('kind') == 'result' and e['id'] == decision['id'] for e in self.events):
             return None
+        source = 'winner_icons'
+        if winner not in ('LEFT', 'RIGHT'):
+            side = decision.get('side')
+            if side not in ('LEFT', 'RIGHT'):
+                self.append('unverified_result', signature=signature,
+                            reason='missing_bet_side')
+                return None
+            winner = side if bet_won else ('RIGHT' if side == 'LEFT' else 'LEFT')
+            source = 'bet_outcome'
         return self.append('result', id=decision['id'], winner=winner,
+                           source=source, bet_won=bet_won,
+                           outcomes={s: v == winner for s, v in decision['votes'].items()})
+
+    def settle_record(self, time_text, bet_won, selected_side=None):
+        """Associate the latest visible record by exact date and round, never lineup."""
+        match = re.fullmatch(r'\s*(\d{4})[./-](\d{1,2})[./-](\d{1,2})\s+(\d{1,2})[::](\d{2})\s*', str(time_text))
+        played = None
+        if match:
+            try:
+                played = datetime(*map(int, match.groups()))
+            except ValueError:
+                pass
+        if (played is None or played.hour not in range(10, 24, 2)
+                or played.minute != 0 or played > datetime.now()
+                or type(bet_won) is not bool):
+            self.append('unverified_result', time_text=str(time_text),
+                        reason='invalid_record_time_or_outcome')
+            return None
+        slot = f'{played.date()}:{played.hour // 2}'
+        if selected_side in ('LEFT', 'RIGHT'):
+            observed_winner = selected_side if bet_won else ('RIGHT' if selected_side == 'LEFT' else 'LEFT')
+            observations = [e for e in self.events if e.get('kind') == 'record' and e.get('slot') == slot]
+            if any(e['winner'] != observed_winner or e['selected_side'] != selected_side for e in observations):
+                self.append('unverified_result', slot=slot, reason='conflicting_record_observation')
+                return None
+            if not observations:
+                self.append('record', slot=slot, winner=observed_winner,
+                            selected_side=selected_side, bet_won=bet_won, time_text=str(time_text))
+        matches = [e for e in self.events if e.get('kind') == 'decision' and e.get('slot') == slot]
+        if len(matches) != 1 or matches[0].get('side') not in ('LEFT', 'RIGHT'):
+            self.append('unverified_result', slot=slot,
+                        reason='missing_or_ambiguous_record_decision')
+            return None
+        decision = matches[0]
+        side = selected_side if selected_side is not None else decision['side']
+        if side not in ('LEFT', 'RIGHT') or side != decision['side']:
+            self.append('unverified_result', slot=slot, selected_side=selected_side,
+                        reason='record_bet_side_mismatch')
+            return None
+        winner = side if bet_won else ('RIGHT' if side == 'LEFT' else 'LEFT')
+        previous = [e for e in self.events if e.get('kind') == 'result' and e.get('id') == decision['id']]
+        if previous:
+            if any(e['winner'] != winner for e in previous):
+                self.append('unverified_result', slot=slot, winner=winner,
+                            reason='conflicting_record_result')
+            return None
+        return self.append('result', id=decision['id'], slot=slot, winner=winner,
+                           source='record_page', bet_won=bet_won, selected_side=side,
                            outcomes={s: v == winner for s, v in decision['votes'].items()})
 
     def choose(self, signature, left, right, predictions):
@@ -106,7 +165,9 @@ class OasHistory:
         if crowd:
             votes['crowd'] = crowd
         cold_start = not any(e.get('kind') == 'result' for e in self.events)
-        weights = {} if cold_start else {uid: self.reliability(uid) for uid in votes}
+        win_rates = {} if cold_start else {uid: self.reliability(uid) for uid in votes}
+        # A source below 50% penalizes its predicted side; newcomers are neutral.
+        weights = {uid: rate - 0.5 for uid, rate in win_rates.items()}
         scores = {'LEFT': 0.0, 'RIGHT': 0.0}
         if cold_start:
             # Two equal votes: the expert majority as a whole and the crowd.
@@ -120,8 +181,9 @@ class OasHistory:
         side = random.choice(('LEFT', 'RIGHT')) if tied else max(scores, key=scores.get)
         return self.append('decision', id=uuid4().hex, slot=slot, signature=signature,
                            left=left, right=right, votes=votes, weights=weights,
-                           scores=scores, side=side, strategy_version=2,
-                           mode='cold_start' if cold_start else 'win_rate',
+                           win_rates=win_rates,
+                           scores=scores, side=side, strategy_version=3,
+                           mode='cold_start' if cold_start else 'signed_win_rate',
                            expert_counts={'LEFT': expert_left, 'RIGHT': expert_right},
                            expert_side=expert_side, crowd_side=crowd, random_tiebreak=tied)
 

+ 42 - 0
tasks/FrogBoss/record_reader.py

@@ -0,0 +1,42 @@
+"""Read complete visible record rows, anchored on the selected red/blue emblem."""
+from copy import copy
+
+import cv2
+
+
+def read_record_rows(image, assets):
+    # Only the user's selected-side column; the enemy column is excluded.
+    x0, y0, x1, y1 = 320, 145, 405, 625
+    source = image[y0:y1, x0:x1]
+    candidates = []
+    for side, rule in (('LEFT', assets.I_FROG_LAST_SELECT_RED),
+                       ('RIGHT', assets.I_FROG_LAST_SELECT_BLUE)):
+        scores = cv2.matchTemplate(source, rule.image, cv2.TM_CCOEFF_NORMED)
+        while scores.size:
+            _, score, _, (x, y) = cv2.minMaxLoc(scores)
+            if score <= rule.threshold:
+                break
+            candidates.append((y + y0, side, score))
+            scores[max(0, y - 25):y + 26, :] = -1
+    rows = []
+    for y, side, score in sorted(candidates):
+        if any(abs(y - other[0]) < 25 for other in candidates if other[1] != side):
+            continue
+        offset = y - assets.I_FROG_LAST_SELECT_RED.roi_front[1]
+        # Partial rows at either boundary are ignored to avoid mixing records.
+        if 154 + offset < 145 or 270 + offset > 625:
+            continue
+        def matches(rule):
+            x, ry, w, h = rule.roi_back
+            crop = image[ry + offset:ry + offset + h, x:x + w]
+            return cv2.minMaxLoc(cv2.matchTemplate(crop, rule.image, cv2.TM_CCOEFF_NORMED))[1] > rule.threshold
+        won, lost = matches(assets.I_FROG_LAST_WIN), matches(assets.I_FROG_LAST_LOSE)
+        if won == lost:
+            continue
+        ocr = copy(assets.O_FROG_LAST_TIME)
+        x, ry, w, h = ocr.roi
+        ocr.roi = (x, ry + offset, w, h)
+        ocr.area = ocr.roi
+        stamp = str(ocr.ocr(image)).strip()
+        rows.append((stamp, won, side))
+    return rows

部分文件因为文件数量过多而无法显示