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

fix(Exploration): scroll toward the selected chapter

Choose the scroll direction from visible chapter numbers and extend gestures to traverse the new chapter list within the retry limit. Synchronize swipe JSON and generated rules, and add chapter-selection regression coverage.
unknown 1 месяц назад
Родитель
Сommit
84e014a4c0

+ 2 - 2
tasks/Exploration/assets.py

@@ -161,9 +161,9 @@ class ExplorationAssets:
 
 	# Swipe Rule Assets
 	# 向上滑动章节 
-	S_SWIPE_LEVEL_UP = RuleSwipe(roi_front=(1142,328,21,21), roi_back=(1143,444,21,21), mode="default", name="swipe_level_up")
+	S_SWIPE_LEVEL_UP = RuleSwipe(roi_front=(1143,225,21,21), roi_back=(1143,495,21,21), mode="default", name="swipe_level_up")
 	# 向下滑动章节 
-	S_SWIPE_LEVEL_DOWN = RuleSwipe(roi_front=(1143,486,21,21), roi_back=(1143,367,21,23), mode="default", name="swipe_level_down")
+	S_SWIPE_LEVEL_DOWN = RuleSwipe(roi_front=(1143,495,21,21), roi_back=(1143,225,21,21), mode="default", name="swipe_level_down")
 	# 往左滑动 
 	S_SWIPE_BACKGROUND_RIGHT = RuleSwipe(roi_front=(1093,148,21,21), roi_back=(397,140,21,21), mode="default", name="swipe_background_right")
 	# 往右滑动 

+ 16 - 9
tasks/Exploration/base.py

@@ -13,7 +13,7 @@ from tasks.Component.GeneralRoom.general_room import GeneralRoom
 from tasks.Component.GeneralInvite.general_invite import GeneralInvite
 from tasks.Component.ReplaceShikigami.replace_shikigami import ReplaceShikigami
 from tasks.Exploration.assets import ExplorationAssets
-from tasks.Exploration.config import ChooseRarity, AutoRotate, AttackNumber, UpType
+from tasks.Exploration.config import ChooseRarity, AutoRotate, AttackNumber, UpType, ExplorationLevel
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.page import page_shikigami_records, page_main
@@ -140,11 +140,13 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
         # I_E_EXPLORATION_CLICK 不出现、OCR 交集为空 → 一直滑屏卡死。故进选关前无条件确保主线 tab。
         self.goto_page(pages.page_mainline)
 
+        target_level = self.config.exploration.exploration_config.exploration_level
+        level_numbers = {level.value: index for index, level in enumerate(ExplorationLevel)}
+        target_number = level_numbers[target_level]
+        # 新版列表按章节递增排列;OCR 暂时为空时沿用上一次方向。
+        swipe = self.S_SWIPE_LEVEL_DOWN
         swipeCount = 0
         while 1:
-            # 探索的 config
-            explorationConfig = self.config.exploration
-
             # 判断有无目标章节
             self.screenshot()
             # 获取当前章节名
@@ -153,18 +155,23 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
             # https://github.com/runhey/OnmyojiAutoScript/issues/1540
             text1 = [text.replace("名", "第").replace("书", "第") for text in text1]
             # 判断当前章节有无目标章节
-            result = set(text1).intersection({explorationConfig.exploration_config.exploration_level})
             # 有则跳出检测
-            if self.appear(self.I_E_EXPLORATION_CLICK) or result and len(result) > 0:
+            if self.appear(self.I_E_EXPLORATION_CLICK) or target_level in text1:
                 break
             if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
                 continue
             if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
                 continue
+            visible_numbers = [level_numbers[text] for text in text1 if text in level_numbers]
+            if visible_numbers:
+                if target_number < min(visible_numbers):
+                    swipe = self.S_SWIPE_LEVEL_UP
+                elif target_number > max(visible_numbers):
+                    swipe = self.S_SWIPE_LEVEL_DOWN
             self.device.click_record_clear()
-            self.swipe(self.S_SWIPE_LEVEL_UP)
+            self.swipe(swipe)
             swipeCount += 1
-            debug_info = f"Swiped {swipeCount} times, current exploration level: {text1}"
+            debug_info = f"Swiped {swipeCount} times ({swipe.name}), current exploration level: {text1}"
             logger.info(debug_info)
             if swipeCount >= 15:
                 raise GameStuckError(
@@ -179,7 +186,7 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
                 continue
             if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
                 continue
-            self.O_E_EXPLORATION_LEVEL_NUMBER.keyword = explorationConfig.exploration_config.exploration_level
+            self.O_E_EXPLORATION_LEVEL_NUMBER.keyword = target_level
             if self.ocr_appear_click(self.O_E_EXPLORATION_LEVEL_NUMBER):
                 self.wait_until_appear(self.I_E_EXPLORATION_CLICK, wait_time=3)
             if self.appear(self.I_E_EXPLORATION_CLICK):

+ 5 - 5
tasks/Exploration/res/swipe.json

@@ -1,15 +1,15 @@
 [
   {
     "itemName": "swipe_level_up",
-    "roiFront": "1142,328,21,21",
-    "roiBack": "1143,444,21,21",
+    "roiFront": "1143,225,21,21",
+    "roiBack": "1143,495,21,21",
     "mode": "default",
     "description": "向上滑动章节"
   },
   {
     "itemName": "swipe_level_down",
-    "roiFront": "1143,486,21,21",
-    "roiBack": "1143,367,21,23",
+    "roiFront": "1143,495,21,21",
+    "roiBack": "1143,225,21,21",
     "mode": "default",
     "description": "向下滑动章节"
   },
@@ -41,4 +41,4 @@
     "mode": "default",
     "description": "滑动一个式神的宽度"
   }
-]
+]

+ 127 - 0
tests/tasks/Exploration/test_level_selection.py

@@ -0,0 +1,127 @@
+"""Replay chapter selection against the new ascending chapter list."""
+from types import SimpleNamespace
+
+import pytest
+
+from module.exception import GameStuckError
+from tasks.Exploration.base import BaseExploration
+from tasks.Exploration.config import ExplorationLevel
+from tasks.Exploration.page import page_mainline
+
+
+class ChapterListReplay(BaseExploration):
+    # The supplied 1280x720 screenshot has chapter headings 106 pixels apart.
+    CHAPTER_HEIGHT = 106
+    CHAPTERS = [level.value for level in ExplorationLevel]
+    MAX_OFFSET = len(CHAPTERS) * CHAPTER_HEIGHT - 337
+
+    def __init__(self, monkeypatch, target, *, at_bottom=False, blocked=False,
+                 empty_frames=()):
+        self.config = SimpleNamespace(exploration=SimpleNamespace(
+            exploration_config=SimpleNamespace(exploration_level=target),
+        ))
+        self.offset = self.MAX_OFFSET if at_bottom else 0
+        self.blocked = blocked
+        self.empty_frames = empty_frames
+        self.frames = 0
+        self.swipes = []
+        self.clicked = []
+        self.entrance_open = False
+        self.interval_timer = {}
+        self.device = SimpleNamespace(
+            image=None, swipe=self.drag, click_record_clear=lambda: None,
+        )
+        self.O_E_EXPLORATION_LEVEL_NUMBER = SimpleNamespace(
+            keyword='', detect_and_ocr=self.recognize_chapters,
+        )
+        monkeypatch.setattr('tasks.Exploration.base.time.sleep', lambda _: None)
+        monkeypatch.setattr('module.atom.swipe.random_normal_distribution_int',
+                            lambda low, high: (low + high) // 2)
+
+    def visible_chapters(self):
+        return [name for index, name in enumerate(self.CHAPTERS)
+                if 206 <= 215 + index * self.CHAPTER_HEIGHT - self.offset <= 543 - 28]
+
+    def recognize_chapters(self, image):
+        if self.frames in self.empty_frames:
+            return []
+        return [SimpleNamespace(ocr_text=text) for text in self.visible_chapters()]
+
+    def goto_page(self, page):
+        assert page is page_mainline
+
+    def screenshot(self):
+        self.frames += 1
+        assert self.frames < 40, 'Chapter selection failed to terminate'
+
+    def appear(self, asset):
+        return asset is self.I_E_EXPLORATION_CLICK and self.entrance_open
+
+    def appear_then_click(self, asset, **kwargs):
+        return False
+
+    def drag(self, p1, p2, control_name):
+        # Use the production swipe coordinates, not their potentially ambiguous names.
+        for x, y in (p1, p2):
+            assert 1064 <= x < 1185 and 206 <= y < 543
+        self.swipes.append((p1, p2))
+        if not self.blocked:
+            self.offset = max(0, min(self.MAX_OFFSET, self.offset + p1[1] - p2[1]))
+
+    def ocr_appear_click(self, rule):
+        if rule.keyword not in self.visible_chapters():
+            return False
+        self.clicked.append(rule.keyword)
+        self.entrance_open = True
+        return True
+
+    def wait_until_appear(self, asset, **kwargs):
+        assert self.appear(asset)
+
+    def is_in_room(self):
+        return False
+
+
+@pytest.mark.parametrize('at_bottom', [False, True], ids=['from-top', 'from-bottom'])
+@pytest.mark.parametrize('target', list(ExplorationLevel), ids=lambda level: level.name)
+def test_every_chapter_is_reachable_within_the_swipe_limit(monkeypatch, target, at_bottom):
+    task = ChapterListReplay(monkeypatch, target, at_bottom=at_bottom)
+
+    assert task.open_expect_level() is True
+    assert task.clicked == [target]
+    assert len(task.swipes) < 15
+
+
+def test_reported_first_three_chapters_scroll_toward_chapter_28(monkeypatch):
+    task = ChapterListReplay(monkeypatch, '第二十八章')
+    assert task.visible_chapters() == ['第一章', '第二章', '第三章']
+
+    assert task.open_expect_level() is True
+    assert task.swipes
+    assert all(start[1] > end[1] for start, end in task.swipes)
+    assert task.clicked == ['第二十八章']
+
+
+def test_visible_chapter_is_selected_without_swiping(monkeypatch):
+    task = ChapterListReplay(monkeypatch, '第二章')
+
+    assert task.open_expect_level() is True
+    assert task.swipes == []
+
+
+def test_temporary_ocr_miss_preserves_scroll_direction(monkeypatch):
+    task = ChapterListReplay(monkeypatch, '第一章', at_bottom=True, empty_frames={2, 3})
+
+    assert task.open_expect_level() is True
+    assert all(start[1] < end[1] for start, end in task.swipes)
+    assert task.clicked == ['第一章']
+
+
+def test_unresponsive_chapter_list_still_hits_the_swipe_limit(monkeypatch):
+    task = ChapterListReplay(monkeypatch, '第二十八章', blocked=True)
+
+    with pytest.raises(GameStuckError, match='Swiped too many times'):
+        task.open_expect_level()
+
+    assert len(task.swipes) == 15
+    assert task.clicked == []