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

Merge pull request #1851 from runhey/dev

Dev
huangrunheng 1 месяц назад
Родитель
Сommit
967a0120b0
39 измененных файлов с 1173 добавлено и 95 удалено
  1. 3 0
      .gitignore
  2. 18 0
      tasks/Component/SwitchOnmyoji/switch_onmyoji.py
  3. 12 3
      tasks/Exploration/solo.py
  4. 39 21
      tasks/FrogBoss/assets.py
  5. 1 0
      tasks/FrogBoss/config.py
  6. BIN
      tasks/FrogBoss/fb/fb_bet_failure.png
  7. BIN
      tasks/FrogBoss/fb/fb_bet_left.png
  8. BIN
      tasks/FrogBoss/fb/fb_bet_right.png
  9. BIN
      tasks/FrogBoss/fb/fb_bet_success.png
  10. BIN
      tasks/FrogBoss/fb/fb_bet_success_box.png
  11. BIN
      tasks/FrogBoss/fb/fb_betted.png
  12. BIN
      tasks/FrogBoss/fb/fb_failure_left.png
  13. BIN
      tasks/FrogBoss/fb/fb_failure_right.png
  14. BIN
      tasks/FrogBoss/fb/fb_frog_boss_enter.png
  15. BIN
      tasks/FrogBoss/fb/fb_frog_boss_rest.png
  16. BIN
      tasks/FrogBoss/fb/fb_frog_check.png
  17. BIN
      tasks/FrogBoss/fb/fb_frog_last_lose.png
  18. BIN
      tasks/FrogBoss/fb/fb_frog_last_select_blue.png
  19. BIN
      tasks/FrogBoss/fb/fb_frog_last_select_red.png
  20. BIN
      tasks/FrogBoss/fb/fb_frog_last_win.png
  21. BIN
      tasks/FrogBoss/fb/fb_frog_log.png
  22. BIN
      tasks/FrogBoss/fb/fb_frog_log_check.png
  23. BIN
      tasks/FrogBoss/fb/fb_frog_log_close.png
  24. BIN
      tasks/FrogBoss/fb/fb_next_competition.png
  25. BIN
      tasks/FrogBoss/fb/fb_success_left.png
  26. BIN
      tasks/FrogBoss/fb/fb_success_right.png
  27. 29 29
      tasks/FrogBoss/fb/image.json
  28. 77 5
      tasks/FrogBoss/fb/image2.json
  29. 15 6
      tasks/FrogBoss/fb/ocr.json
  30. 233 0
      tasks/FrogBoss/frog_oas.py
  31. 2 0
      tasks/FrogBoss/oas_sources.py
  32. 42 0
      tasks/FrogBoss/record_reader.py
  33. 142 23
      tasks/FrogBoss/script_task.py
  34. 97 0
      tasks/FrogBoss/test_betting_flow.py
  35. 215 0
      tasks/FrogBoss/test_frog_oas.py
  36. 14 4
      tasks/HeroTest/script_task.py
  37. 7 4
      tasks/WeeklyTrifles/script_task.py
  38. 122 0
      tests/test_hero_test_skill_fallback.py
  39. 105 0
      tests/test_switch_onmyoji.py

+ 3 - 0
.gitignore

@@ -272,3 +272,6 @@ console.bat
 .vscode/*
 tasks/AutoCheckinBigGod/frida-server-17.6.2-android-x86_64
 oas.bat
+
+# Per-instance FrogBoss prediction and result history
+data/frog_oas/

+ 18 - 0
tasks/Component/SwitchOnmyoji/switch_onmyoji.py

@@ -1,4 +1,6 @@
 from module.atom.image import RuleImage
+from module.base.timer import Timer
+from module.exception import ScriptError
 from tasks.Component.SwitchOnmyoji.assets import SwitchOnmyojiAssets
 from tasks.Component.SwitchOnmyoji.config import Onmyoji
 from tasks.base_task import BaseTask
@@ -6,6 +8,10 @@ from module.logger import logger
 
 
 class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
+    # 上限用来给两个 while 循环兜底:资源坐标过期或页面不对时不再无限点,
+    # 改为抛出带上下文的 ScriptError,让上层决定重启还是人工接管。
+    SWITCH_TAB_TIMEOUT = 20
+    SWITCH_BATTLE_TIMEOUT = 20
 
     def switch_onmyoji(self, onmyoji: Onmyoji):
         """
@@ -29,7 +35,14 @@ class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
         :param battle_dict: 角色与战斗图标的映射
         :param check_img: 检查是否回到主界面的图标
         """
+        # 两个循环都必须在超时后抛出,而不是继续点击
+        tab_timer = Timer(self.SWITCH_TAB_TIMEOUT).start()
         while True:
+            if tab_timer.reached():
+                raise ScriptError('Switch onmyoji: cannot reach the role list, '
+                                  'the onmyoji tab was not opened after '
+                                  f'{self.SWITCH_TAB_TIMEOUT}s. '
+                                  'Check whether the onmyoji/hero assets still match the game UI')
             self.screenshot()
             if any(self.appear(battle_icon) for battle_icon in battle_dict.values()):
                 break
@@ -37,7 +50,12 @@ class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
         battle_img = battle_dict.get(role, None)
         if not battle_img:
             raise ValueError('Incorrect role type')
+        battle_timer = Timer(self.SWITCH_BATTLE_TIMEOUT).start()
         while True:
+            if battle_timer.reached():
+                raise ScriptError(f'Switch onmyoji: cannot select {role}, '
+                                  'the role list stayed unconfirmed after '
+                                  f'{self.SWITCH_BATTLE_TIMEOUT}s')
             self.screenshot()
             if self.appear(check_img, interval=0.8):
                 break

+ 12 - 3
tasks/Exploration/solo.py

@@ -2,6 +2,7 @@
 # @author runhey
 # github https://github.com/runhey
 from time import sleep
+from copy import deepcopy
 from cached_property import cached_property
 
 from module.logger import logger
@@ -134,7 +135,6 @@ class SoloExploration(BaseExploration):
         while 1:
             self.screenshot()
             scene = self.get_current_scene()
-            logger.info(f'[run_leader] Current scene: {scene.name}')  # TODO 2026.06.22 之后删掉这个刷屏的
             # 探索大世界
             if scene == Scene.WORLD:
                 # 打开右边箭头
@@ -337,6 +337,15 @@ class SoloExploration(BaseExploration):
                 friend_class[i] = '跨区'
         logger.info(f'Friend class: {friend_class}')
 
+        # 76e2a874(#1509) 把 I_FLAG_2_ON 的 roi 改到了 tab 标签栏上方的空白区
+        # (472,82,32,11) / (454,74,56,26),导致第 2 个 tab 的选中态永远匹配不上,
+        # while index == 1 死循环点满 10 次触发 GameTooManyClickError。
+        # 这里深拷贝一份并还原成 439be142(#1443) 的 roi,不改动原资源。
+        # https://github.com/runhey/OnmyojiAutoScript/issues/1844
+        flag_2_on = deepcopy(self.I_FLAG_2_ON)
+        flag_2_on.roi_front = [471, 128, 54, 18]
+        flag_2_on.roi_back = (471, 128, 54, 18)
+
         is_select: bool = False  # 是否选中了好友
         if find_mode == FindMode.RECENT_FRIEND:
             logger.info('Find recent friend')
@@ -347,7 +356,7 @@ class SoloExploration(BaseExploration):
             recent_index = friend_class.index('最近')
             while recent_index == 1:
                 self.screenshot()
-                if self.appear(self.I_FLAG_2_ON):
+                if self.appear(flag_2_on):
                     break
                 if self.appear_then_click(self.I_FLAG_2_OFF, interval=1):
                     continue
@@ -378,7 +387,7 @@ class SoloExploration(BaseExploration):
                     continue
             while index == 1:
                 self.screenshot()
-                if self.I_FLAG_2_ON.match_mean_color(self.device.image, self.INVITE_FLAG_ON, 10):
+                if flag_2_on.match_mean_color(self.device.image, self.INVITE_FLAG_ON, 10):
                     break
                 if self.click(self.I_FLAG_2_OFF, interval=1):
                     continue

+ 39 - 21
tasks/FrogBoss/assets.py

@@ -12,48 +12,66 @@ class FrogBossAssets:
 
 	# Image Rule Assets
 	# 左边竞猜 
-	I_BET_LEFT = RuleImage(roi_front=(95,308,145,100), roi_back=(58,248,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=(1038,303,146,100), roi_back=(1012,268,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=(593,419,87,50), roi_back=(564,378,140,133), 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=(123,316,100,100), roi_back=(91,254,202,221), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_left.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=(1063,291,100,100), roi_back=(993,242,224,199), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_right.png")
-	# description 
-	I_NEXT_COMPETITION = RuleImage(roi_front=(673,510,42,36), roi_back=(658,488,91,98), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.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")
+	# 开始下一局
+	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=(858,494,78,76), roi_back=(809,427,147,187), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30.png")
+	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=(1000,297,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_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")
+	# 获胜奖励说明弹窗中的竞猜金币
+	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=(93,352,125,54), roi_back=(49,283,1192,161), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_betted.png")
+	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 
-	I_SUCCESS_RIGHT = RuleImage(roi_front=(1048,341,122,116), roi_back=(999,243,201,260), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_right.png")
+	I_SUCCESS_RIGHT = RuleImage(roi_front=(1098,289,122,116), roi_back=(1040,250,201,260), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_right.png")
 	# description 
-	I_FAILURE_LEFT = RuleImage(roi_front=(116,307,100,100), roi_back=(76,256,193,219), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_left.png")
+	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=(496,252,269,72), roi_back=(439,220,400,152), 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=(512,264,260,73), roi_back=(433,214,418,151), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success.png")
+	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")
 
 
 	# Image Rule Assets
 	# description 
-	I_FROG_BOSS_ENTER = RuleImage(roi_front=(1191,391,36,38), roi_back=(1174,135,78,320), threshold=0.7, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_enter.png")
+	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
 	# Ocr-description 
-	O_LEFT_COUNT = RuleOcr(roi=(143,496,69,31), area=(143,496,69,31), mode="Digit", method="Default", keyword="", name="left_count")
+	O_LEFT_COUNT = RuleOcr(roi=(326,469,69,31), area=(326,469,69,31), mode="Digit", method="Default", keyword="", name="left_count")
 	# Ocr-description 
-	O_RIGHT_COUNT = RuleOcr(roi=(1105,497,77,32), area=(1105,497,77,32), mode="Digit", method="Default", keyword="", name="right_count")
+	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=(594,564,91,35), area=(594,564,91,35), mode="Duration", method="Default", keyword="", name="time_remain")
+	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")
 
 

+ 1 - 0
tasks/FrogBoss/config.py

@@ -14,6 +14,7 @@ class Strategy(str, Enum):
     Minority = 'frog_minority'
     Bilibili = 'frog_bilibili'
     Dashen = 'frog_dashen'
+    Oas = 'frog_oas'
     AlwaysRed = 'frog_always_red'
     AlwaysBlue = 'frog_always_blue'
 

BIN
tasks/FrogBoss/fb/fb_bet_failure.png


BIN
tasks/FrogBoss/fb/fb_bet_left.png


BIN
tasks/FrogBoss/fb/fb_bet_right.png


BIN
tasks/FrogBoss/fb/fb_bet_success.png


BIN
tasks/FrogBoss/fb/fb_bet_success_box.png


BIN
tasks/FrogBoss/fb/fb_betted.png


BIN
tasks/FrogBoss/fb/fb_failure_left.png


BIN
tasks/FrogBoss/fb/fb_failure_right.png


BIN
tasks/FrogBoss/fb/fb_frog_boss_enter.png


BIN
tasks/FrogBoss/fb/fb_frog_boss_rest.png


BIN
tasks/FrogBoss/fb/fb_frog_check.png


BIN
tasks/FrogBoss/fb/fb_frog_last_lose.png


BIN
tasks/FrogBoss/fb/fb_frog_last_select_blue.png


BIN
tasks/FrogBoss/fb/fb_frog_last_select_red.png


BIN
tasks/FrogBoss/fb/fb_frog_last_win.png


BIN
tasks/FrogBoss/fb/fb_frog_log.png


BIN
tasks/FrogBoss/fb/fb_frog_log_check.png


BIN
tasks/FrogBoss/fb/fb_frog_log_close.png


BIN
tasks/FrogBoss/fb/fb_next_competition.png


BIN
tasks/FrogBoss/fb/fb_success_left.png


BIN
tasks/FrogBoss/fb/fb_success_right.png


+ 29 - 29
tasks/FrogBoss/fb/image.json

@@ -2,8 +2,8 @@
   {
     "itemName": "bet_left",
     "imageName": "fb_bet_left.png",
-    "roiFront": "95,308,145,100",
-    "roiBack": "58,248,245,195",
+    "roiFront": "288,301,120,102",
+    "roiBack": "222,251,245,195",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "左边竞猜"
@@ -11,8 +11,8 @@
   {
     "itemName": "bet_right",
     "imageName": "fb_bet_right.png",
-    "roiFront": "1038,303,146,100",
-    "roiBack": "1012,268,187,208",
+    "roiFront": "1093,307,118,94",
+    "roiBack": "1048,248,187,208",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "右边竞猜"
@@ -20,8 +20,8 @@
   {
     "itemName": "bet_success_box",
     "imageName": "fb_bet_success_box.png",
-    "roiFront": "593,419,87,50",
-    "roiBack": "564,378,140,133",
+    "roiFront": "713,399,80,45",
+    "roiBack": "661,331,193,182",
     "method": "Template matching",
     "threshold": 0.75,
     "description": "description"
@@ -29,8 +29,8 @@
   {
     "itemName": "success_left",
     "imageName": "fb_success_left.png",
-    "roiFront": "123,316,100,100",
-    "roiBack": "91,254,202,221",
+    "roiFront": "292,306,100,100",
+    "roiBack": "238,243,202,221",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "左边赢了"
@@ -38,8 +38,8 @@
   {
     "itemName": "failure_right",
     "imageName": "fb_failure_right.png",
-    "roiFront": "1063,291,100,100",
-    "roiBack": "993,242,224,199",
+    "roiFront": "1097,303,100,100",
+    "roiBack": "1029,256,224,199",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "右边输了"
@@ -47,17 +47,17 @@
   {
     "itemName": "next_competition",
     "imageName": "fb_next_competition.png",
-    "roiFront": "673,510,42,36",
-    "roiBack": "658,488,91,98",
+    "roiFront": "783,492,28,22",
+    "roiBack": "692,437,157,147",
     "method": "Template matching",
     "threshold": 0.8,
-    "description": "description"
+    "description": "开始下一局"
   },
   {
     "itemName": "gold_30",
     "imageName": "fb_gold_30.png",
-    "roiFront": "858,494,78,76",
-    "roiBack": "809,427,147,187",
+    "roiFront": "862,499,78,76",
+    "roiBack": "831,441,147,187",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "30万金币"
@@ -66,7 +66,7 @@
     "itemName": "bet_sure",
     "imageName": "fb_bet_sure.png",
     "roiFront": "1025,402,100,100",
-    "roiBack": "1000,297,200,226",
+    "roiBack": "972,340,200,226",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "确认竞猜"
@@ -75,16 +75,16 @@
     "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,
-    "description": "description"
+    "description": "获胜奖励说明弹窗中的竞猜金币"
   },
   {
     "itemName": "betted",
     "imageName": "fb_betted.png",
-    "roiFront": "93,352,125,54",
-    "roiBack": "49,283,1192,161",
+    "roiFront": "1093,313,125,54",
+    "roiBack": "207,240,1058,312",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"
@@ -92,8 +92,8 @@
   {
     "itemName": "success_right",
     "imageName": "fb_success_right.png",
-    "roiFront": "1048,341,122,116",
-    "roiBack": "999,243,201,260",
+    "roiFront": "1098,289,122,116",
+    "roiBack": "1040,250,201,260",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"
@@ -101,8 +101,8 @@
   {
     "itemName": "failure_left",
     "imageName": "fb_failure_left.png",
-    "roiFront": "116,307,100,100",
-    "roiBack": "76,256,193,219",
+    "roiFront": "296,303,100,100",
+    "roiBack": "243,245,212,259",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"
@@ -110,8 +110,8 @@
   {
     "itemName": "bet_failure",
     "imageName": "fb_bet_failure.png",
-    "roiFront": "496,252,269,72",
-    "roiBack": "439,220,400,152",
+    "roiFront": "625,277,269,72",
+    "roiBack": "496,222,447,211",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"
@@ -119,10 +119,10 @@
   {
     "itemName": "bet_success",
     "imageName": "fb_bet_success.png",
-    "roiFront": "512,264,260,73",
-    "roiBack": "433,214,418,151",
+    "roiFront": "625,278,260,73",
+    "roiBack": "482,243,521,225",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "description"
   }
-]
+]

+ 77 - 5
tasks/FrogBoss/fb/image2.json

@@ -2,8 +2,8 @@
   {
     "itemName": "frog_boss_enter",
     "imageName": "fb_frog_boss_enter.png",
-    "roiFront": "1191,391,36,38",
-    "roiBack": "1174,135,78,320",
+    "roiFront": "1188,303,36,38",
+    "roiBack": "1169,203,78,320",
     "method": "Template matching",
     "threshold": 0.7,
     "description": "description"
@@ -11,10 +11,82 @@
   {
     "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,
     "description": "休息中"
+  },
+  {
+    "itemName": "frog_check",
+    "imageName": "fb_frog_check.png",
+    "roiFront": "664,31,148,65",
+    "roiBack": "551,4,371,145",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "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": "上一句选择蓝色"
   }
-]
+]

+ 15 - 6
tasks/FrogBoss/fb/ocr.json

@@ -1,8 +1,8 @@
 [
   {
     "itemName": "left_count",
-    "roiFront": "143,496,69,31",
-    "roiBack": "143,496,69,31",
+    "roiFront": "326,469,69,31",
+    "roiBack": "326,469,69,31",
     "mode": "Digit",
     "method": "Default",
     "keyword": "",
@@ -10,8 +10,8 @@
   },
   {
     "itemName": "right_count",
-    "roiFront": "1105,497,77,32",
-    "roiBack": "1105,497,77,32",
+    "roiFront": "1139,472,77,32",
+    "roiBack": "1139,472,77,32",
     "mode": "Digit",
     "method": "Default",
     "keyword": "",
@@ -19,11 +19,20 @@
   },
   {
     "itemName": "time_remain",
-    "roiFront": "594,564,91,35",
-    "roiBack": "594,564,91,35",
+    "roiFront": "705,533,91,35",
+    "roiBack": "705,533,91,35",
     "mode": "Duration",
     "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": "上一句对局时间"
   }
 ]

+ 233 - 0
tasks/FrogBoss/frog_oas.py

@@ -0,0 +1,233 @@
+"""Persistent, outcome-verified weighted voting. Scores are not win probabilities."""
+import json
+import re
+import random
+from datetime import datetime
+from pathlib import Path
+from uuid import uuid4
+
+import cv2
+import requests
+
+from tasks.FrogBoss.oas_sources import DASHEN_UIDS
+
+
+def fingerprint(image):
+    # Only the two lineups: excludes countdown, votes, chest and result text.
+    bits = []
+    for x in (300, 807):
+        crop = image[112:233, x:x + 398]
+        gray = cv2.cvtColor(crop, cv2.COLOR_RGB2GRAY)
+        small = cv2.resize(gray, (33, 8))
+        bits.extend((small[:, 1:] > small[:, :-1]).flatten())
+    return ''.join('1' if bit else '0' for bit in bits)
+
+
+def same_lineup(a, b):
+    return len(a) == len(b) == 512 and sum(x != y for x, y in zip(a, b)) <= 20
+
+
+def parse_side(text):
+    # Ambiguous text is deliberately excluded rather than guessed by word order.
+    red = bool(re.search(r'押红|押左|压红|压左|我红|我左|红优|红方胜|红色胜', text))
+    blue = bool(re.search(r'押蓝|押右|压蓝|压右|我蓝|我右|蓝优|蓝方胜|蓝色胜', text))
+    if re.search(r'不押|不压|别押|别压|不要押|不要压', text):
+        return None
+    return ('LEFT' if red else 'RIGHT') if red != blue else None
+
+
+class OasHistory:
+    def __init__(self, path):
+        self.path = Path(path)
+        self.events = []
+        if self.path.exists():
+            for line in self.path.read_text(encoding='utf-8').splitlines():
+                try:
+                    event = json.loads(line)
+                except ValueError:
+                    continue  # Ignore a truncated final record after interruption.
+                if isinstance(event, dict):
+                    self.events.append(event)
+
+    def append(self, kind, **data):
+        event = dict(version=1, kind=kind, recorded_at=datetime.now().isoformat(), **data)
+        self.path.parent.mkdir(parents=True, exist_ok=True)
+        # Leading newline separates a possible truncated tail from the new event.
+        with self.path.open('a', encoding='utf-8') as stream:
+            stream.write('\n' + json.dumps(event, ensure_ascii=False) + '\n')
+            stream.flush()
+        self.events.append(event)
+        return event
+
+    def reliability(self, source):
+        decisions = {e['id']: e for e in self.events if e.get('kind') == 'decision'}
+        correct = total = 0
+        seen = set()
+        for result in self.events:
+            if result.get('kind') != 'result' or result['id'] in seen:
+                continue
+            seen.add(result['id'])
+            vote = decisions.get(result['id'], {}).get('votes', {}).get(source)
+            if vote in ('LEFT', 'RIGHT'):
+                total += 1
+                correct += vote == result['winner']
+        # Unverified newcomers start neutral; verified sources use raw win rate.
+        return correct / total if total else 0.5
+
+    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.
+        matches = [e for e in self.events if e.get('kind') == 'decision'
+                   and same_lineup(e['signature'], signature)]
+        if len(matches) != 1:
+            self.append('unverified_result', signature=signature, winner=winner,
+                        reason='missing_or_ambiguous_decision')
+            return None
+        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):
+        now = datetime.now()
+        # Re-entry in the same slot reuses the original frozen decision.
+        slot = f'{now.date()}:{now.hour // 2}'
+        for e in reversed(self.events):
+            if e.get('kind') == 'decision' and e['slot'] == slot and same_lineup(e['signature'], signature):
+                return e
+        crowd = ('LEFT' if left > right else 'RIGHT') if left != right and left + right > 0 else None
+        votes = {p['uid']: p['side'] for p in predictions if p.get('side') in ('LEFT', 'RIGHT')}
+        expert_left = sum(v == 'LEFT' for v in votes.values())
+        expert_right = sum(v == 'RIGHT' for v in votes.values())
+        expert_side = ('LEFT' if expert_left > expert_right else 'RIGHT') if expert_left != expert_right else None
+        if crowd:
+            votes['crowd'] = crowd
+        cold_start = not any(e.get('kind') == 'result' for e in self.events)
+        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.
+            for vote in (expert_side, crowd):
+                if vote:
+                    scores[vote] += 1
+        else:
+            for uid, vote in votes.items():
+                scores[vote] += weights[uid]
+        tied = abs(scores['LEFT'] - scores['RIGHT']) < 1e-12
+        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,
+                           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)
+
+
+def fetch_predictions(history):
+    now = datetime.now()
+    used = {(e.get('uid'), e.get('feed_id')) for e in history.events
+            if e.get('kind') == 'fetch' and e.get('accepted')}
+    predictions = []
+    with requests.Session() as session:
+        for uid in DASHEN_UIDS:
+            feed_id = None
+            try:
+                response = session.get('https://inf.ds.163.com/v1/web/feed/basic/getSomeOneFeeds',
+                                       params={'feedTypes': '1,2,3,4,6,7,10,11', 'someOneUid': uid}, timeout=(3, 5))
+                response.raise_for_status()
+                feeds = response.json().get('result', {}).get('feeds', [])
+                if not feeds:
+                    history.append('fetch', uid=uid, accepted=False, reason='no_feed')
+                    continue
+                feed_id = feeds[0]['id']
+                response = session.get('https://inf.ds.163.com/v1/web/feed/basic/facade',
+                                       params={'feedId': feed_id}, timeout=(3, 5))
+                response.raise_for_status()
+                feed = response.json()['result']['feed']
+                content = feed['content']
+                if isinstance(content, str):
+                    content = json.loads(content)
+                body = content['body']['text']
+                raw_time = feed.get('createTime')
+                published = None
+                try:
+                    published = datetime.fromtimestamp(float(raw_time) / 1000)
+                except (TypeError, ValueError, OverflowError, OSError):
+                    pass
+                side = parse_side(body)
+                fresh = published is not None and published.date() == now.date() and published.hour // 2 == now.hour // 2 and published <= now
+                accepted = fresh and side is not None and (uid, feed_id) not in used
+                history.append('fetch', uid=uid, feed_id=feed_id, create_time=raw_time,
+                               body=body, side=side, accepted=accepted,
+                               reason='accepted' if accepted else 'stale_unknown_ambiguous_or_duplicate')
+                if accepted:
+                    predictions.append(dict(uid=uid, side=side, feed_id=feed_id))
+            except (requests.RequestException, ValueError, KeyError, IndexError, TypeError) as exc:
+                history.append('fetch', uid=uid, feed_id=feed_id, accepted=False,
+                               reason='request_or_parse_error', error=str(exc))
+    return predictions

+ 2 - 0
tasks/FrogBoss/oas_sources.py

@@ -0,0 +1,2 @@
+"""UIDs shared with the legacy Dashen strategy; deduplicated for frog_oas."""
+DASHEN_UIDS = ["462382f1127b46c5add1185d88f0ea40","54399446d5084a0e8878dac8f6ff56d0","840742d60e4a43208605ae68ca8c3f64","c3c989fae4074d04b478b8ba47ae4120","aaa923436aa440df9ac1ee3f47387b99","72584a679e2f45b6859566b5523400d5","3d4726d99f2642a485729695b798cb8c","1d2dcbbd7e3d481c8d0f27ba4ff0dc71","21657a558bdd4ddfb6501298350336e7","0e4e0c5a1e494a1fa9a58ac55de689c1","30e383c884f844a18a7a76fe3c1e888f","d9dc2a75497c4a91b2db1e909a36544d","e7107cd3010e418da26672669d8eeb5e","74adeb1bfb2b4cf382edbbb430da2149","e87f855f36f24b34b9d8f8a4fb2d62b2","82de68c7672e4b6da65493fb829b57b6","f6d6bb15d6024200a985752e2ab4c373","06e2bba14a914012bc8064601cfa19ea","8982241de1844638b4bb455139b8dcc0","a9724e98c1cb4a4e931ebc3f467ea73d","e9b0a16325af46628e8dfb9e7942cf1d","b6b5bc8277e34f69aeca018db0081397","74db771d92a54c28ae3e98d19aa565a3","e498e524252041e29999b38e57c4df1d","30b0c2923faa483f95572c324a5bc910","e32aedbdd8da46a5b5b497a16c4b7658"]

+ 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

+ 142 - 23
tasks/FrogBoss/script_task.py

@@ -6,9 +6,11 @@ from datetime import datetime
 import requests
 import re
 import json
+from pathlib import Path
 
-from module.exception import TaskEnd
+from module.exception import GameStuckError, TaskEnd
 from module.logger import logger
+from module.atom.click import RuleClick
 from module.atom.image import RuleImage
 from module.base.timer import Timer
 
@@ -19,14 +21,88 @@ from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
 from tasks.Component.config_base import TimeDelta
 from tasks.FrogBoss.assets import FrogBossAssets
 from tasks.FrogBoss.config import Strategy
+from tasks.FrogBoss.record_reader import read_record_rows
+from tasks.FrogBoss.frog_oas import OasHistory, fetch_predictions, fingerprint
 
 
 class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
-    def run(self):
+    @cached_property
+    def oas_history(self):
+        instance = re.sub(r'[^\w.-]', '_', self.config.config_name)
+        return OasHistory(Path('data/frog_oas') / f'{instance}.jsonl')
+
+    def record_oas_history_page(self):
+        if self.config.model.frog_boss.frog_boss_config.strategy_frog != Strategy.Oas:
+            return
+        timer = Timer(10).start()
+        while not timer.reached():
+            self.screenshot()
+            if self.appear(self.I_FROG_LOG_CHECK):
+                break
+            self.appear_then_click(self.I_FROG_LOG, interval=2)
+        else:
+            raise GameStuckError('FrogBoss record page did not open')
+        try:
+            # Read only the currently visible rows; never scroll the record page.
+            readings = []
+            for _ in range(2):
+                self.screenshot()
+                if not self.appear(self.I_FROG_LOG_CHECK):
+                    break
+                readings.append(read_record_rows(self.device.image, self))
+            if len(readings) != 2 or readings[0] != readings[1]:
+                self.oas_history.append('unverified_result', reason='unstable_record_page')
+                logger.warning('FrogBoss record page readings were not stable')
+            else:
+                for stamp, won, side in dict.fromkeys(readings[0]):
+                    result = self.oas_history.settle_record(stamp, won, selected_side=side)
+                    logger.info(f'frog_oas record result: {result}, time={stamp}, won={won}, selected={side}')
+        finally:
+            timer = Timer(10).start()
+            while not timer.reached():
+                self.screenshot()
+                if not self.appear(self.I_FROG_LOG_CHECK) and self.appear(self.I_FROG_CHECK):
+                    break
+                self.appear_then_click(self.I_FROG_LOG_CLOSE, interval=2)
+            else:
+                raise GameStuckError('FrogBoss record page did not close')
+
+    def enter_frog_boss(self):
+        self.screenshot()
+        if self.appear(self.I_FROG_CHECK) or self.appear(self.I_FROG_LOG_CHECK):
+            return
         self.enter(self.I_FROG_BOSS_ENTER)
+        if not self.wait_until_appear(self.I_FROG_CHECK, wait_time=10):
+            raise GameStuckError('FrogBoss page not detected after entering activity')
+
+    def _try_next_competition_fallback(self, idle_timer):
+        if not self.appear(self.I_FROG_CHECK):
+            idle_timer.reset()
+            return False
+        if idle_timer.reached() and self.appear_then_click(self.I_NEXT_COMPETITION, interval=1):
+            logger.info('FrogBoss idle for 5 seconds; advance via next-competition fallback')
+            idle_timer.reset()
+            return True
+        return False
+
+    def run(self):
+        self.enter_frog_boss()
+        history_checked = False
+        idle_timer = Timer(5).start()
         # 进入主界面
         while 1:
             self.screenshot()
+            if self._try_next_competition_fallback(idle_timer):
+                continue
+
+            if not history_checked and self.config.model.frog_boss.frog_boss_config.strategy_frog == Strategy.Oas:
+                if (self.appear(self.I_FROG_LOG_CHECK) or self.appear(self.I_BETTED)
+                        or self.appear(self.I_FROG_BOSS_REST)
+                        or (self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT))):
+                    self.record_oas_history_page()
+                    history_checked = True
+                    idle_timer.reset()
+                    continue
 
             # 已经下注
             if self.appear(self.I_BETTED):
@@ -42,24 +118,34 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
                 self.detect()
                 while 1:
                     self.screenshot()
+                    if self._try_next_competition_fallback(idle_timer):
+                        continue
+                    # 下一局可能直接进入休息中,而不再显示左右投注入口。
+                    if self.appear(self.I_FROG_BOSS_REST):
+                        break
                     if self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT):
                         break
                     if self.appear_then_click(self.I_BET_SUCCESS_BOX, interval=1):
+                        idle_timer.reset()
                         continue
                     if self.appear_then_click(self.I_REWARD, interval=2):
+                        idle_timer.reset()
                         continue
                     if self.appear_then_click(self.I_NEXT_COMPETITION, interval=4):
+                        idle_timer.reset()
                         continue
                 continue
             # 竞猜失败
             if self.appear(self.I_BET_FAILURE):
                 logger.info('You bet lose')
-                self.ui_click_until_disappear(self.I_NEXT_COMPETITION)
+                if self.ui_click_until_disappear(self.I_NEXT_COMPETITION):
+                    idle_timer.reset()
                 self.detect()
                 continue
             # 正式竞猜
             if self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT):
                 self.do_bet()
+                idle_timer.reset()
                 continue
 
         logger.info('FrogBoss end')
@@ -93,7 +179,6 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
     def do_bet(self):
         logger.hr('do bet', level=2)
         self.screenshot()
-        flag_glod_30 = 0
         count_left = self.O_LEFT_COUNT.ocr(self.device.image)
         count_right = self.O_RIGHT_COUNT.ocr(self.device.image)
         match self.config.model.frog_boss.frog_boss_config.strategy_frog:
@@ -105,6 +190,22 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
                 click_image = self.I_BET_LEFT if count_left > count_right else self.I_BET_RIGHT
             case Strategy.Dashen:
                 click_image = self.get_dashen(count_left, count_right)
+            case Strategy.Oas:
+                signature = fingerprint(self.device.image)
+                predictions = fetch_predictions(self.oas_history)
+                try:
+                    decision = self.oas_history.choose(signature, count_left, count_right, predictions)
+                except ValueError as exc:
+                    raise GameStuckError(str(exc)) from exc
+                logger.info(f'frog_oas decision: {decision}')
+                # Fetching may span a round transition; never click a stale frame.
+                self.screenshot()
+                from tasks.FrogBoss.frog_oas import same_lineup
+                if not same_lineup(signature, fingerprint(self.device.image)):
+                    raise GameStuckError('FrogBoss lineup changed while fetching predictions')
+                if not (self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT)):
+                    raise GameStuckError('FrogBoss betting closed while fetching predictions')
+                click_image = self.I_BET_LEFT if decision['side'] == 'LEFT' else self.I_BET_RIGHT
             case Strategy.AlwaysRed:
                 click_image = self.I_BET_LEFT
             case Strategy.AlwaysBlue:
@@ -113,32 +214,50 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
                 raise ValueError(f'Unknown bet mode: {self.config.model.frog_boss.frog_boss_config.strategy_frog}')
         logger.info(f'You strategy is {self.config.model.frog_boss.frog_boss_config.strategy_frog} and bet on {click_image}')
         self.ui_click_until_disappear(click_image)
-        gold_30_timer = Timer(10)
-        gold_30_timer.start()
-        while 1:
-            self.screenshot()
-            if self.appear(self.I_GOLD_30_CHECK):
-                break
-            if gold_30_timer.reached():
-                logger.info('Gold 30 not appear')
-                break
-            if self.appear_then_click(self.I_GOLD_30, interval=3):
-                continue
-        # 正式下注
+        self.confirm_bet()
+
+    def select_gold_30(self):
+        if not self.appear(self.I_GOLD_30):
+            return False
+        # 袋子下部的奖励图标会打开说明页,只点击匹配位置的上部袋身。
+        x, y, width, height = self.I_GOLD_30.roi_front
+        area = (x + width // 4, y + height // 8, width // 2, height // 3)
+        self.click(RuleClick(
+            roi_front=area, roi_back=area, name='FB_GOLD_30_SELECT',
+        ))
+        return True
+
+    def confirm_bet(self):
         logger.info('Formal bet')
-        while 1:
+        timer = Timer(20).start()
+        gold_selected = False
+        submit_attempts = 0
+        while not timer.reached():
             self.screenshot()
             if self.appear(self.I_BETTED):
-                break
-            if self.appear_then_click(self.I_BET_SURE, interval=2) and flag_glod_30 == 1:
-                continue
-            if self.appear_then_click(self.I_GOLD_30, interval=2):
-                flag_glod_30 = 1
+                return
+            if self.appear(self.I_FROG_BOSS_REST):
+                return
+            # 弹窗后方的金额、鼓面仍能匹配,必须先处理弹窗并重新截图。
+            if self.appear(self.I_GOLD_30_CHECK):
+                logger.info('Close FrogBoss betting reward information')
+                self.click(self.C_REWARD_2, interval=2)
                 continue
             if self.appear_then_click(self.I_UI_CONFIRM, interval=2):
                 continue
             if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=2):
                 continue
+            if not gold_selected:
+                if self.select_gold_30():
+                    gold_selected = True
+                continue
+            if submit_attempts < 3 and self.appear_then_click(self.I_BET_SURE, interval=3):
+                submit_attempts += 1
+                continue
+        raise GameStuckError(
+            f'FrogBoss betting confirmation timeout: gold_selected={gold_selected}, '
+            f'submit_attempts={submit_attempts}'
+        )
 
     def detect(self) -> bool:
         """
@@ -152,7 +271,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             result = False
             logger.info('Right win')
         else:
-            result = True
+            result = None
         return result
 
     def get_bilibili(self) -> RuleImage:

+ 97 - 0
tasks/FrogBoss/test_betting_flow.py

@@ -0,0 +1,97 @@
+import unittest
+from unittest.mock import patch
+
+from module.exception import GameStuckError
+from tasks.FrogBoss.script_task import ScriptTask
+
+
+class FrameTimer:
+    """Bound waits by simulated frames without sleeping or using a device."""
+
+    def __init__(self, *_args):
+        self.frames = 0
+
+    def start(self):
+        return self
+
+    def reached(self):
+        self.frames += 1
+        return self.frames > 12
+
+
+class BettingTask(ScriptTask):
+    def __init__(self, frames):
+        self.frames = iter(frames)
+        self.visible = set()
+        self.clicks = []
+
+    def screenshot(self):
+        self.visible = next(self.frames, self.visible)
+
+    def appear(self, rule):
+        return rule.name in self.visible
+
+    def click(self, rule, interval=None):
+        self.clicks.append(rule)
+        return True
+
+    def appear_then_click(self, rule, interval=None):
+        if not self.appear(rule):
+            return False
+        return self.click(rule, interval=interval)
+
+
+@patch('tasks.FrogBoss.script_task.Timer', FrameTimer)
+class BettingFlowTests(unittest.TestCase):
+    def test_reward_overlay_and_confirmation_hide_clickable_background(self):
+        panel = {ScriptTask.I_GOLD_30.name, ScriptTask.I_BET_SURE.name}
+        task = BettingTask([
+            panel | {ScriptTask.I_GOLD_30_CHECK.name},
+            panel,
+            panel,
+            panel | {ScriptTask.I_UI_CONFIRM.name},
+            {ScriptTask.I_BETTED.name},
+        ])
+        task.confirm_bet()
+        self.assertEqual([rule.name for rule in task.clicks], [
+            ScriptTask.C_REWARD_2.name,
+            'FB_GOLD_30_SELECT',
+            ScriptTask.I_BET_SURE.name,
+            ScriptTask.I_UI_CONFIRM.name,
+        ])
+        selection = task.clicks[1]
+        x, y, width, height = ScriptTask.I_GOLD_30.roi_front
+        sx, sy, sw, sh = selection.roi_front
+        self.assertGreaterEqual(sx, x)
+        self.assertLessEqual(sx + sw, x + width)
+        self.assertGreaterEqual(sy, y)
+        self.assertLess(sy + sh, y + height // 2)
+
+    def test_cannot_submit_before_selecting_amount(self):
+        task = BettingTask([{ScriptTask.I_BET_SURE.name}])
+        with self.assertRaisesRegex(GameStuckError, 'gold_selected=False'):
+            task.confirm_bet()
+        self.assertEqual(task.clicks, [])
+
+    def test_no_response_limits_submit_retries_without_reselecting_amount(self):
+        panel = {ScriptTask.I_GOLD_30.name, ScriptTask.I_BET_SURE.name}
+        task = BettingTask([panel])
+        with self.assertRaisesRegex(GameStuckError, 'submit_attempts=3'):
+            task.confirm_bet()
+        self.assertEqual([rule.name for rule in task.clicks], [
+            'FB_GOLD_30_SELECT',
+            ScriptTask.I_BET_SURE.name,
+            ScriptTask.I_BET_SURE.name,
+            ScriptTask.I_BET_SURE.name,
+        ])
+
+    def test_already_betted_and_rest_end_without_clicking(self):
+        for marker in (ScriptTask.I_BETTED, ScriptTask.I_FROG_BOSS_REST):
+            with self.subTest(marker=marker.name):
+                task = BettingTask([{marker.name}])
+                task.confirm_bet()
+                self.assertEqual(task.clicks, [])
+
+
+if __name__ == '__main__':
+    unittest.main()

+ 215 - 0
tasks/FrogBoss/test_frog_oas.py

@@ -0,0 +1,215 @@
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from tasks.FrogBoss.frog_oas import OasHistory, parse_side, same_lineup
+
+
+class OasTests(unittest.TestCase):
+    def test_persistence_rewards_and_dedup(self):
+        with tempfile.TemporaryDirectory() as directory:
+            path = Path(directory) / 'history.jsonl'
+            store = OasHistory(path)
+            decision = store.choose('0' * 512, 20, 10, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'RIGHT'}])
+            self.assertEqual(store.reliability('a'), .5)
+            self.assertEqual(store.choose('0' * 512, 10, 20, [])['id'], decision['id'])
+            self.assertIsNone(store.settle('1' * 512, 'LEFT'))
+            store.settle('0' * 512, 'LEFT')
+            self.assertIsNone(store.settle('0' * 512, 'LEFT'))
+            reloaded = OasHistory(path)
+            self.assertEqual(reloaded.reliability('a'), 1)
+            self.assertEqual(reloaded.reliability('b'), 0)
+            self.assertEqual(reloaded.reliability('crowd'), 1)
+            second = reloaded.choose('1' * 512, 10, 20, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'LEFT'}])
+            self.assertEqual(second['scores'], {'LEFT': 0, 'RIGHT': .5})
+            self.assertEqual(second['mode'], 'signed_win_rate')
+            reloaded.settle('1' * 512, 'RIGHT')
+            self.assertEqual(reloaded.reliability('a'), .5)
+            self.assertEqual(reloaded.reliability('b'), 0)
+            self.assertEqual(reloaded.reliability('crowd'), 1)
+
+    def test_fallback_and_missing_data(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            self.assertEqual(store.choose('0' * 512, 1, 2, [])['side'], 'RIGHT')
+            self.assertEqual(store.reliability('crowd'), .5)
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='LEFT'):
+                self.assertEqual(store.choose('1' * 512, 0, 0, [])['side'], 'LEFT')
+
+    def test_cold_start_two_equal_groups(self):
+        predictions = [{'uid': str(i), 'side': 'LEFT' if i < 6 else 'RIGHT'} for i in range(9)]
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            agreed = store.choose('0' * 512, 20, 10, predictions)
+            self.assertEqual(agreed['side'], 'LEFT')
+            self.assertEqual(agreed['scores'], {'LEFT': 2, 'RIGHT': 0})
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='RIGHT') as choose:
+                opposed = store.choose('1' * 512, 10, 20, predictions)
+                self.assertEqual(opposed['scores'], {'LEFT': 1, 'RIGHT': 1})
+                self.assertEqual(opposed['side'], 'RIGHT')
+                choose.assert_called_once_with(('LEFT', 'RIGHT'))
+
+    def test_bet_outcome_settlement_enters_weighted_mode(self):
+        for side in ('LEFT', 'RIGHT'):
+            for won in (True, False):
+                with self.subTest(side=side, won=won), tempfile.TemporaryDirectory() as directory:
+                    store = OasHistory(Path(directory) / 'history.jsonl')
+                    left, right = (20, 10) if side == 'LEFT' else (10, 20)
+                    first = store.choose('0' * 512, left, right, [{'uid': 'a', 'side': side}])
+                    result = store.settle('0' * 512, bet_won=won)
+                    expected = side if won else ('RIGHT' if side == 'LEFT' else 'LEFT')
+                    self.assertEqual(result['winner'], expected)
+                    self.assertEqual(result['id'], first['id'])
+                    self.assertEqual(result['source'], 'bet_outcome')
+                    self.assertEqual(store.reliability('a'), float(won))
+                    self.assertIsNone(store.settle('0' * 512, bet_won=won))
+                    reloaded = OasHistory(store.path)
+                    second = reloaded.choose('1' * 512, left, right, [{'uid': 'a', 'side': side}])
+                    self.assertEqual(second['mode'], 'signed_win_rate')
+
+    def test_signed_weights_penalize_wrong_sources_and_leave_newcomers_neutral(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.append('decision', id='previous', slot='2026-09-28:5', signature='1' * 512, votes={
+                'wrong': 'LEFT', 'correct': 'RIGHT', 'crowd': 'LEFT',
+            })
+            store.append('result', id='previous', winner='RIGHT')
+            decision = store.choose('0' * 512, 20, 10, [
+                {'uid': 'wrong', 'side': 'LEFT'},
+                {'uid': 'correct', 'side': 'RIGHT'},
+                {'uid': 'newcomer', 'side': 'LEFT'},
+            ])
+            self.assertEqual(decision['win_rates'], {
+                'wrong': 0, 'correct': 1, 'newcomer': .5, 'crowd': 0,
+            })
+            self.assertEqual(decision['weights'], {
+                'wrong': -.5, 'correct': .5, 'newcomer': 0, 'crowd': -.5,
+            })
+            self.assertEqual(decision['scores'], {'LEFT': -1, 'RIGHT': .5})
+            self.assertEqual(decision['side'], 'RIGHT')
+            self.assertEqual(decision['strategy_version'], 3)
+
+    def test_negative_consensus_can_select_the_opposite_side(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.append('decision', id='previous', slot='2026-09-28:5', signature='1' * 512,
+                         votes={'a': 'LEFT'})
+            store.append('result', id='previous', winner='RIGHT')
+            decision = store.choose('0' * 512, 20, 10, [{'uid': 'a', 'side': 'LEFT'}])
+            self.assertEqual(decision['weights'], {'a': -.5, 'crowd': 0})
+            self.assertEqual(decision['scores'], {'LEFT': -.5, 'RIGHT': 0})
+            self.assertEqual(decision['side'], 'RIGHT')
+
+    def test_signed_weights_use_raw_cumulative_rate_and_randomize_zero_tie(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            for index, winner in enumerate(('LEFT', 'RIGHT', 'RIGHT', 'RIGHT')):
+                store.append('decision', id=f'seed{index}', slot=f'2026-09-28:{5 + index}',
+                             signature='1' * 512, votes={'a': 'LEFT', 'b': 'RIGHT'})
+                store.append('result', id=f'seed{index}', winner=winner)
+            decision = store.choose('0' * 512, 0, 0, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'RIGHT'},
+            ])
+            self.assertEqual(decision['weights'], {'a': -.25, 'b': .25})
+            self.assertEqual(decision['side'], 'RIGHT')
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='LEFT') as choose:
+                tied = store.choose('1' * 512, 0, 0, [
+                    {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'LEFT'},
+                ])
+            self.assertEqual(tied['scores'], {'LEFT': 0, 'RIGHT': 0})
+            self.assertTrue(tied['random_tiebreak'])
+            choose.assert_called_once_with(('LEFT', 'RIGHT'))
+
+    def test_bet_outcome_rejects_missing_or_ambiguous_lineup(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            first = store.choose('0' * 512, 20, 10, [])
+            self.assertIsNone(store.settle('1' * 512, bet_won=True))
+            duplicate = dict(first)
+            for key in ('kind', 'version', 'recorded_at'):
+                duplicate.pop(key)
+            duplicate['id'] = 'another-round'
+            store.append('decision', **duplicate)
+            self.assertIsNone(store.settle('0' * 512, bet_won=True))
+            self.assertFalse(any(e['kind'] == 'result' for e in store.events))
+
+    def test_winner_icons_take_precedence(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.choose('0' * 512, 20, 10, [])
+            result = store.settle('0' * 512, 'RIGHT', bet_won=True)
+            self.assertEqual(result['winner'], 'RIGHT')
+            self.assertEqual(result['source'], 'winner_icons')
+
+    def test_record_page_exact_round_and_dedup(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.append('decision', id='ten', slot='2026-09-30:5', side='LEFT',
+                         votes={'a': 'LEFT', 'crowd': 'LEFT'})
+            store.append('decision', id='twelve', slot='2026-09-30:6', side='RIGHT',
+                         votes={'a': 'RIGHT', 'crowd': 'LEFT'})
+            result = store.settle_record('2026.09.30 12:00', False)
+            self.assertEqual(result['id'], 'twelve')
+            self.assertEqual(result['winner'], 'LEFT')
+            self.assertEqual(result['source'], 'record_page')
+            self.assertEqual(store.reliability('a'), 0)
+            self.assertEqual(store.reliability('crowd'), 1)
+            self.assertIsNone(store.settle_record('2026.09.30 12:00', False))
+            self.assertEqual(len([e for e in store.events if e['kind'] == 'result']), 1)
+            self.assertEqual(store.settle_record('2026.09.30 10:00', True)['winner'], 'LEFT')
+
+    def test_record_page_rejects_invalid_unknown_and_conflict(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.append('decision', id='a', slot='2026-09-30:6', side='LEFT', votes={})
+            for stamp in ('12:00', '2026.09.30 13:00', '2026.09.30 12:30',
+                          '2026.02.30 12:00', '2099.09.30 12:00', '2026.09.29 12:00'):
+                self.assertIsNone(store.settle_record(stamp, True))
+            self.assertIsNone(store.settle_record('2026.09.30 12:00', None))
+            self.assertIsNotNone(store.settle_record('2026.09.30 12:00', True))
+            self.assertIsNone(store.settle_record('2026.09.30 12:00', False))
+            self.assertEqual(store.events[-1]['reason'], 'conflicting_record_result')
+
+    def test_record_page_does_not_guess_between_duplicate_decisions(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            for key in ('a', 'b'):
+                store.append('decision', id=key, slot='2026-09-30:6', side='LEFT', votes={})
+            self.assertIsNone(store.settle_record('2026.09.30 12:00', True))
+            self.assertFalse(any(e['kind'] == 'result' for e in store.events))
+
+    def test_selected_side_verifies_bet_and_keeps_raw_result(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.append('decision', id='a', slot='2026-09-30:6', side='RIGHT',
+                         votes={'a': 'RIGHT', 'crowd': 'LEFT'})
+            result = store.settle_record('2026.09.30 12:00', False, selected_side='RIGHT')
+            self.assertEqual(result['winner'], 'LEFT')
+            self.assertEqual(store.reliability('crowd'), 1)
+            self.assertEqual(store.reliability('a'), 0)
+            self.assertIsNone(store.settle_record('2026.09.30 12:00', False, selected_side='RIGHT'))
+            self.assertEqual(len([e for e in store.events if e['kind'] == 'record']), 1)
+            self.assertIsNone(store.settle_record('2026.09.30 10:00', True, selected_side='LEFT'))
+            self.assertEqual(len([e for e in store.events if e['kind'] == 'record']), 2)
+
+    def test_selected_side_mismatch_does_not_update_weights(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            store.append('decision', id='a', slot='2026-09-30:6', side='LEFT', votes={'a': 'LEFT'})
+            self.assertIsNone(store.settle_record('2026.09.30 12:00', False, selected_side='RIGHT'))
+            self.assertEqual(store.events[-1]['reason'], 'record_bet_side_mismatch')
+            self.assertEqual(store.reliability('a'), .5)
+
+    def test_ambiguous_text_and_signature(self):
+        self.assertEqual(parse_side('本场押红'), 'LEFT')
+        self.assertIsNone(parse_side('不押红,押蓝'))
+        self.assertIsNone(parse_side('押红还是押蓝'))
+        self.assertTrue(same_lineup('0' * 512, '1' * 10 + '0' * 502))
+        self.assertFalse(same_lineup('0' * 512, '1' * 512))
+
+
+if __name__ == '__main__':
+    unittest.main()

+ 14 - 4
tasks/HeroTest/script_task.py

@@ -4,6 +4,7 @@
 from datetime import datetime, timedelta, time
 import random  # type: ignore
 from typing import Callable
+from module.atom.click import RuleClick
 
 from module.logger import logger
 from module.exception import TaskEnd
@@ -128,8 +129,9 @@ class ScriptTask(GameUi, GeneralBattle, HeroTestAssets, SwitchSoul):
                 # https://github.com/runhey/OnmyojiAutoScript/issues/1671
                 if timer.reached_and_reset():
                     if self.appear(self.I_BCMJ_SKILL_ADD_CONFIRM):
-                        logger.warning('No skill selected for 10s, panel still open, retrying')
-                        continue
+                        logger.warning('No skill selected for 10s, panel still open, click a random buff')
+                        self.click_random_buff()
+                        break
                     logger.warning('Skill selection panel closed unexpectedly, exit')
                     break
 
@@ -175,8 +177,9 @@ class ScriptTask(GameUi, GeneralBattle, HeroTestAssets, SwitchSoul):
             self.screenshot()
             if timer.reached_and_reset():
                 if self.appear(self.I_BCMJ_SKILL_ADD_CONFIRM):
-                    logger.warning('No skill selected for 10s, panel still open, retrying')
-                    continue
+                    logger.warning('No skill selected for 10s, panel still open, click a random buff')
+                    self.click_random_buff()
+                    break
                 logger.warning('Skill selection panel closed unexpectedly, exit')
                 break
             if any(self.appear_then_click(ts, interval=1) for ts in target_skills):
@@ -184,6 +187,13 @@ class ScriptTask(GameUi, GeneralBattle, HeroTestAssets, SwitchSoul):
         self.ui_click_until_disappear(self.I_BCMJ_SKILL_ADD_CONFIRM, interval=1.5)
         return True
 
+    def click_random_buff(self):
+        """兜底: 4个buff都未匹配到目标时, 随机点击一个槽位, 避免卡死"""
+        logger.warning('No target buff matched, click a random buff')
+        slot = random.choice([(60, 320, 200, 140), (380, 320, 200, 140),
+                              (700, 320, 200, 140), (1020, 320, 200, 140)])
+        self.click(RuleClick(roi_front=slot, roi_back=slot, name='buff_random'), interval=1)
+
     def switch_hero(self, layer: Layer):
         """切换英杰"""
         self.ui_goto_page(pages.page_hero_test)

+ 7 - 4
tasks/WeeklyTrifles/script_task.py

@@ -91,8 +91,11 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
         self.ui_goto(page_touch_fish)
         self.screenshot()
         if self.appear(self.I_WT_SAVE_ALL):
-            _, cu_tickts, _ = self.O_WT_LUCKY_TICKETS.ocr(self.device.image)
+            cu_tickts, _, _ = self.O_WT_LUCKY_TICKETS.ocr(self.device.image)
+            logger.info(f"当前的福运御守数量:{cu_tickts}")
             cost_tickts = self.O_WT_SAVE_COST.ocr(self.device.image)
+            logger.info(f"全部存储需要花费的福运御守数量:{cost_tickts}")
+            not_save_flag = True
             get_timer = Timer(7)
             get_timer.start()
             while 1:
@@ -105,9 +108,9 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
                     continue
                 if self.appear_then_click(self.I_WT_HAPPY_GET):
                     continue
-                if cu_tickts >= cost_tickts:
+                if cu_tickts >= cost_tickts and not_save_flag:
                     self.appear_then_click(self.I_WT_SAVE_ALL)
-                    cu_tickts = 0
+                    not_save_flag = False
                     continue
                 if self.appear_then_click(self.I_WT_TF_CONFIRM):
                     continue
@@ -116,7 +119,7 @@ class ScriptTask(GameUi, WeeklyTriflesAssets):
                 ):
                     logger.info('Touch fish save success')
                     break
-                if cu_tickts < cost_tickts:
+                if cu_tickts < cost_tickts and not_save_flag:
                     logger.warning('Touch fish tickts not enough, exit!')
                     break
                 if get_timer.reached():

+ 122 - 0
tests/test_hero_test_skill_fallback.py

@@ -0,0 +1,122 @@
+"""Exercise HeroTest selection loops without a Config, Device or running game."""
+
+import itertools
+import unittest
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from module.atom.click import RuleClick
+from tasks.HeroTest.config import SkillMode
+from tasks.HeroTest.script_task import ScriptTask
+
+
+class ScriptedHeroTest(ScriptTask):
+    def __init__(self, *, mode=SkillMode.PVE, panel_visible=True, close_on_frame=None):
+        # Skip BaseTask.__init__, which requires a real Config and Device.
+        self.conf = SimpleNamespace(herotest=SimpleNamespace(skill_mode=mode))
+        self.panel_visible = panel_visible
+        self.close_on_frame = close_on_frame
+        self.frames = 0
+        self.visible_skills = []
+        self.attempted_skills = []
+        self.events = []
+
+    def screenshot(self):
+        self.frames += 1
+        if self.frames > 3:
+            raise AssertionError('Skill selection kept retrying after the timeout')
+        if self.frames == self.close_on_frame:
+            self.panel_visible = False
+
+    def wait_until_appear(self, button, **kwargs):
+        return self.appear(button)
+
+    def appear(self, button, **kwargs):
+        return button is self.I_BCMJ_SKILL_ADD_CONFIRM and self.panel_visible
+
+    def appear_then_click(self, button, **kwargs):
+        if button is self.I_BCMJ_SKILL_ADD_CONFIRM:
+            if not self.panel_visible:
+                return False
+            self.events.append(('confirm', button))
+            self.panel_visible = False
+            return True
+        self.attempted_skills.append(button)
+        if any(button is skill for skill in self.visible_skills):
+            self.events.append(('preferred', button))
+            return True
+        return False
+
+    def click(self, button, **kwargs):
+        self.events.append(('fallback', button))
+        return True
+
+    def ui_click_until_disappear(self, button, **kwargs):
+        self.appear_then_click(button)
+
+
+class HeroTestSkillFallbackTests(unittest.TestCase):
+    def setUp(self):
+        timer_patch = patch('tasks.HeroTest.script_task.Timer')
+        timer = timer_patch.start()
+        self.addCleanup(timer_patch.stop)
+        # Allow one normal recognition attempt, then keep reporting a timeout.
+        self.expired = timer.return_value.start.return_value.reached_and_reset
+
+    def run_selection(self, task, method):
+        self.expired.side_effect = itertools.chain([False], itertools.repeat(True))
+        return getattr(task, method)()
+
+    def assert_fallback_then_confirm(self, task, method):
+        self.assertTrue(self.run_selection(task, method))
+        self.assertEqual([event for event, _ in task.events], ['fallback', 'confirm'])
+        self.assertIsInstance(task.events[0][1], RuleClick)
+        self.assertEqual(task.frames, 2)
+
+    def test_hero1_unrecognized_skills_fall_back_then_confirm(self):
+        self.assert_fallback_then_confirm(ScriptedHeroTest(), 'hero1_skill_wait')
+
+    def test_hero2_unrecognized_skills_fall_back_then_confirm(self):
+        self.assert_fallback_then_confirm(ScriptedHeroTest(), 'hero2_skill_wait')
+
+    def test_empty_hero2_pvp_priority_list_does_not_retry_forever(self):
+        task = ScriptedHeroTest(mode=SkillMode.PVP)
+        self.assert_fallback_then_confirm(task, 'hero2_skill_wait')
+
+    def test_hero1_recognized_skills_keep_their_priority(self):
+        task = ScriptedHeroTest()
+        task.visible_skills = [task.I_BCMJ_SKILL_ADD2, task.I_BCMJ_BLESS]
+        self.assertTrue(self.run_selection(task, 'hero1_skill_wait'))
+        self.assertEqual([event for event, _ in task.events], ['preferred', 'confirm'])
+        self.assertIs(task.events[0][1], task.I_BCMJ_SKILL_ADD2)
+        self.assertEqual(len(task.attempted_skills), 2)
+        self.assertEqual(task.frames, 1)
+
+    def test_hero2_recognized_skills_keep_their_priority(self):
+        task = ScriptedHeroTest()
+        task.visible_skills = [task.I_HERO2_SKILL2, task.I_HERO2_SKILL3]
+        self.assertTrue(self.run_selection(task, 'hero2_skill_wait'))
+        self.assertEqual([event for event, _ in task.events], ['preferred', 'confirm'])
+        self.assertIs(task.events[0][1], task.I_HERO2_SKILL2)
+        self.assertEqual(len(task.attempted_skills), 2)
+        self.assertEqual(task.frames, 1)
+
+    def test_no_panel_does_not_click(self):
+        for method in ('hero1_skill_wait', 'hero2_skill_wait'):
+            with self.subTest(method=method):
+                task = ScriptedHeroTest(panel_visible=False)
+                self.assertFalse(self.run_selection(task, method))
+                self.assertEqual(task.events, [])
+                self.assertEqual(task.frames, 0)
+
+    def test_panel_closed_at_timeout_does_not_click_randomly(self):
+        for method in ('hero1_skill_wait', 'hero2_skill_wait'):
+            with self.subTest(method=method):
+                task = ScriptedHeroTest(close_on_frame=2)
+                self.run_selection(task, method)
+                self.assertEqual(task.events, [])
+                self.assertEqual(task.frames, 2)
+
+
+if __name__ == '__main__':
+    unittest.main()

+ 105 - 0
tests/test_switch_onmyoji.py

@@ -0,0 +1,105 @@
+"""SwitchOnmyoji must have a bounded exit path.
+
+Both loops in `SwitchOnmyoji.switch_role` used to be unconditional `while True`.
+When the onmyoji/hero tab cannot be reached (stale asset coordinates after a
+game UI update, emulator showing a different page, ...), they kept clicking
+forever until the global `GameStuckError` watchdog fired roughly two minutes
+later, discarding all context about what actually went wrong.
+
+These tests pin the exit conditions: a loop that never finds its target has to
+raise a named, catchable `ScriptError` instead of spinning, and the happy path
+must keep working unchanged.
+"""
+import pytest
+
+from module.base.timer import Timer
+from module.exception import ScriptError
+from tasks.Component.SwitchOnmyoji.config import Onmyoji
+from tasks.Component.SwitchOnmyoji.switch_onmyoji import SwitchOnmyoji
+
+
+class ScriptedSwitch(SwitchOnmyoji):
+    """Double that replays a fixed sequence of `appear` results.
+
+    `screenshot` and every click are no-ops, so the test exercises the real
+    loop control flow of `switch_role` without a Config, a Device or a game.
+    """
+
+    def __init__(self, appear_results, timeout=0):
+        # deliberately skip BaseTask.__init__: it needs a real Config/Device
+        self._appear_results = list(appear_results)
+        self._appear_calls = 0
+        self.switch_clicks = 0
+        self.battle_clicks = 0
+        self.ui_clicks = 0
+        # override the real 20s guards so the test does not have to wait
+        self.SWITCH_TAB_TIMEOUT = timeout
+        self.SWITCH_BATTLE_TIMEOUT = timeout
+
+    def _next_appear(self, button):
+        self._appear_calls += 1
+        if not self._appear_results:
+            return False
+        return self._appear_results.pop(0)
+
+    def screenshot(self):
+        pass
+
+    def appear(self, button, interval=None, **kwargs):
+        return self._next_appear(button)
+
+    def appear_then_click(self, button, interval=None, **kwargs):
+        self.switch_clicks += 1
+        return True
+
+    def click(self, button, interval=None, **kwargs):
+        self.battle_clicks += 1
+        return True
+
+    def ui_click(self, button1, button2, interval=None, **kwargs):
+        self.ui_clicks += 1
+        return True
+
+
+def test_switch_role_raises_when_battle_list_never_appears():
+    task = ScriptedSwitch(appear_results=[])
+
+    with pytest.raises(ScriptError):
+        task.switch_role(role=None, battle_dict={'x': object()}, check_img=object())
+
+
+def test_switch_role_raises_when_check_icon_never_appears():
+    # battle icon visible, confirm icon never does
+    task = ScriptedSwitch(appear_results=[True])
+
+    with pytest.raises(ScriptError):
+        task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+
+def test_switch_role_still_switches_when_the_flow_is_healthy():
+    # appear order: battle icon, then confirm icon -> no extra clicks needed
+    task = ScriptedSwitch(appear_results=[True, True])
+
+    task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.battle_clicks == 0
+    assert task.ui_clicks == 0
+
+
+def test_switch_role_clicks_the_battle_icon_when_confirm_icon_is_absent():
+    # appear order: battle icon, not-confirm, battle icon -> ui_click back path
+    task = ScriptedSwitch(appear_results=[True, False, True])
+
+    task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.ui_clicks == 1
+
+
+def test_timeouts_are_not_shared_between_instances():
+    a = ScriptedSwitch(appear_results=[])
+    b = ScriptedSwitch(appear_results=[])
+
+    assert a.SWITCH_TAB_TIMEOUT is not None
+    assert b.SWITCH_TAB_TIMEOUT is not None