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

Merge pull request #1850 from xylolit-mu/pr

fix(FrogBoss):修复对弈竞猜相关资源,激活oas策略客制化权重。
huangrunheng 1 месяц назад
Родитель
Сommit
f870b43ac2

+ 25 - 9
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,7 @@ 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")
 
 

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_box.png


BIN
tasks/FrogBoss/fb/fb_failure_right.png


BIN
tasks/FrogBoss/fb/fb_frog_boss_rest.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


+ 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

+ 106 - 29
tasks/FrogBoss/script_task.py

@@ -10,6 +10,7 @@ from pathlib import Path
 
 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
 
@@ -20,6 +21,7 @@ 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
 
 
@@ -29,28 +31,78 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
         instance = re.sub(r'[^\w.-]', '_', self.config.config_name)
         return OasHistory(Path('data/frog_oas') / f'{instance}.jsonl')
 
-    def record_oas_result(self):
+    def record_oas_history_page(self):
         if self.config.model.frog_boss.frog_boss_config.strategy_frog != Strategy.Oas:
             return
-        winner = self.detect()
-        if winner is not None:
-            result = self.oas_history.settle(
-                fingerprint(self.device.image), 'LEFT' if winner else 'RIGHT')
-            logger.info(f'frog_oas result: {result}')
+        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):
+        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):
@@ -63,29 +115,37 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             # 竞猜成功
             if self.appear(self.I_BET_SUCCESS):
                 logger.info('You bet win')
-                self.record_oas_result()
                 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.record_oas_result()
-                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')
@@ -119,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:
@@ -155,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:
         """

+ 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()

+ 153 - 2
tasks/FrogBoss/test_frog_oas.py

@@ -24,8 +24,8 @@ class OasTests(unittest.TestCase):
             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': 1, 'RIGHT': 1})
-            self.assertEqual(second['mode'], 'win_rate')
+            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)
@@ -52,6 +52,157 @@ class OasTests(unittest.TestCase):
                 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('不押红,押蓝'))