Explorar o código

Merge pull request #1154 from BluettDream/dev_feat

dev_feat
huangrunheng hai 1 ano
pai
achega
c6b3f4970f

+ 1 - 0
module/base/timer.py

@@ -153,6 +153,7 @@ class Timer:
         diff = self._current + self.limit - time.time()
         if diff > 0:
             time.sleep(diff)
+        return self
 
     def show(self):
         from module.logger import logger

+ 26 - 19
module/server/app.py

@@ -1,19 +1,30 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+from contextlib import asynccontextmanager
+
 import argparse
-from fastapi import FastAPI
+from fastapi import FastAPI, Request
 from fastapi.middleware.cors import CORSMiddleware
 
 from module.logger import logger
 
 from module.server.home_router import home_app
 from module.server.script_router import script_app
+from starlette import status
+from starlette.responses import JSONResponse
+
 
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+    await on_startup()
+    yield
+    await on_shutdown()
 app = FastAPI(
     title='OAS',
     description='OAS web service',
     version='0.0.0',
+    lifespan=lifespan,
 )
 
 app.add_middleware(
@@ -27,30 +38,27 @@ app.add_middleware(
 app.include_router(home_app)
 app.include_router(script_app)
 
-@app.on_event("startup")
-async def startup_event():
-    logger.info('OAS web service startup done')
-    pass
-
-@app.on_event("shutdown")
-async def shutdown_event():
-    logger.info('OAS web service shutdown done')
-
-
-
-
-
-
-
-
-
 
+async def on_startup():
+    logger.info('OAS web service startup done')
 
 
+async def on_shutdown():
+    logger.info('OAS web service shutdown done')
 
 
+@app.exception_handler(Exception)
+async def global_exception_handler(request: Request, exc: Exception):
+    logger.error(f"Internal Server Error: ", exc_info=True)
 
+    message = ', '.join(str(arg) for arg in exc.args) if exc.args else str(exc)
 
+    return JSONResponse(
+        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+        content={
+            'message': message
+        },
+    )
 
 
 def fastapi_app():
@@ -71,5 +79,4 @@ def fastapi_app():
     )
     args, _ = parser.parse_known_args()
 
-
     return app

+ 12 - 7
module/server/script_websocket.py

@@ -19,27 +19,32 @@ class ScriptWSManager:
         try:
             # 给前端发送最后一次关闭信号
             await ws.close()
-        except RuntimeError:
-            pass
+        except RuntimeError as e:
+            print(e)
 
     async def broadcast(self, message: str):
         # 广播消息
         for connection in self.active_connections:
-            await connection.send_text(message)
+            try:
+                await connection.send_text(message)
+            except RuntimeError:
+                await self.disconnect(connection)
 
     async def broadcast_state(self, data: dict):
         # 广播自身的状态
         for connection in self.active_connections:
-            await connection.send_json(data)
+            try:
+                await connection.send_json(data)
+            except RuntimeError:
+                await self.disconnect(connection)
 
     async def broadcast_log(self, log: str):
         # 广播日志
         for connection in self.active_connections:
             try:
                 await connection.send_text(log)
-            except RuntimeError as e:
-                print(e)
-                self.active_connections.remove(connection)
+            except RuntimeError:
+                await self.disconnect(connection)
 
 
 

BIN=BIN
tasks/ActivityShikigami/as/as_check_ap100.png


+ 7 - 7
tasks/ActivityShikigami/as/click.json

@@ -1,26 +1,26 @@
 [
   {
     "itemName": "random_left",
-    "roiFront": "21,23,237,599",
-    "roiBack": "21,23,237,599",
+    "roiFront": "17,69,132,599",
+    "roiBack": "17,70,137,599",
     "description": "description"
   },
   {
     "itemName": "random_right",
-    "roiFront": "1047,55,218,638",
-    "roiBack": "1047,55,218,638",
+    "roiFront": "1133,55,131,638",
+    "roiBack": "1131,55,133,638",
     "description": "description"
   },
   {
     "itemName": "random_top",
-    "roiFront": "85,46,1159,101",
+    "roiFront": "84,49,1159,93",
     "roiBack": "85,46,1159,101",
     "description": "description"
   },
   {
     "itemName": "random_bottom",
-    "roiFront": "182,539,1063,100",
-    "roiBack": "182,539,1063,100",
+    "roiFront": "179,577,972,100",
+    "roiBack": "179,579,972,100",
     "description": "description"
   },
   {

+ 11 - 2
tasks/ActivityShikigami/as/image.json

@@ -48,7 +48,7 @@
     "itemName": "lock",
     "imageName": "as_lock.png",
     "roiFront": "884,648,28,25",
-    "roiBack": "761,613,255,76",
+    "roiBack": "739,613,276,76",
     "method": "Template matching",
     "threshold": 0.5,
     "description": "上锁图标"
@@ -57,7 +57,7 @@
     "itemName": "unlock",
     "imageName": "as_unlock.png",
     "roiFront": "884,648,28,25",
-    "roiBack": "758,607,242,85",
+    "roiBack": "733,607,266,85",
     "method": "Template matching",
     "threshold": 0.5,
     "description": "还未上锁图片"
@@ -268,5 +268,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "门票活动定位"
+  },
+  {
+    "itemName": "check_ap100",
+    "imageName": "as_check_ap100.png",
+    "roiFront": "971,575,96,100",
+    "roiBack": "934,537,166,167",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "100体爬塔标识"
   }
 ]

+ 18 - 0
tasks/ActivityShikigami/as/ocr.json

@@ -61,5 +61,23 @@
     "method": "Default",
     "keyword": "挑战",
     "description": "挑战"
+  },
+  {
+    "itemName": "remain_ap100",
+    "roiFront": "922,21,112,39",
+    "roiBack": "913,8,131,62",
+    "mode": "Digit",
+    "method": "Default",
+    "keyword": "",
+    "description": "100体活动门票检测"
+  },
+  {
+    "itemName": "enter_ap100",
+    "roiFront": "72,187,95,32",
+    "roiBack": "7,172,256,108",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "将魂试炼",
+    "description": "进入100体活动标识"
   }
 ]

+ 12 - 6
tasks/ActivityShikigami/assets.py

@@ -32,13 +32,13 @@ class ActivityShikigamiAssets:
 
 	# Click Rule Assets
 	# description 
-	C_RANDOM_LEFT = RuleClick(roi_front=(21,23,237,599), roi_back=(21,23,237,599), name="random_left")
+	C_RANDOM_LEFT = RuleClick(roi_front=(17,69,132,599), roi_back=(17,70,137,599), name="random_left")
 	# description 
-	C_RANDOM_RIGHT = RuleClick(roi_front=(1047,55,218,638), roi_back=(1047,55,218,638), name="random_right")
+	C_RANDOM_RIGHT = RuleClick(roi_front=(1133,55,131,638), roi_back=(1131,55,133,638), name="random_right")
 	# description 
-	C_RANDOM_TOP = RuleClick(roi_front=(85,46,1159,101), roi_back=(85,46,1159,101), name="random_top")
+	C_RANDOM_TOP = RuleClick(roi_front=(84,49,1159,93), roi_back=(85,46,1159,101), name="random_top")
 	# description 
-	C_RANDOM_BOTTOM = RuleClick(roi_front=(182,539,1063,100), roi_back=(182,539,1063,100), name="random_bottom")
+	C_RANDOM_BOTTOM = RuleClick(roi_front=(179,577,972,100), roi_back=(179,579,972,100), name="random_bottom")
 	# description 
 	C_RANDOM_ALL = RuleClick(roi_front=(42,94,1207,543), roi_back=(42,94,1207,543), name="random_all")
 	# 替换buff1 
@@ -69,9 +69,9 @@ class ActivityShikigamiAssets:
 	# 归鹿之途 
 	I_DRUM = RuleImage(roi_front=(327,627,145,28), roi_back=(256,462,301,232), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_drum.png")
 	# 上锁图标 
-	I_LOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(761,613,255,76), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_lock.png")
+	I_LOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(739,613,276,76), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_lock.png")
 	# 还未上锁图片 
-	I_UNLOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(758,607,242,85), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_unlock.png")
+	I_UNLOCK = RuleImage(roi_front=(884,648,28,25), roi_back=(733,607,266,85), threshold=0.5, method="Template matching", file="./tasks/ActivityShikigami/as/as_unlock.png")
 	# 寿司体力 
 	I_AP = RuleImage(roi_front=(1181,657,23,24), roi_back=(1149,631,103,71), threshold=0.65, method="Template matching", file="./tasks/ActivityShikigami/as/as_ap.png")
 	# 活动体力 
@@ -118,6 +118,8 @@ class ActivityShikigamiAssets:
 	I_ACT_MAP_SWITCH = RuleImage(roi_front=(1196,303,59,48), roi_back=(1174,263,104,118), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_act_map_switch.png")
 	# 门票活动定位 
 	I_PASS_ACT_LOCAT = RuleImage(roi_front=(1214,395,29,31), roi_back=(1179,373,100,86), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_pass_act_locat.png")
+	# 100体爬塔标识 
+	I_CHECK_AP100 = RuleImage(roi_front=(971,575,96,100), roi_back=(934,537,166,167), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_ap100.png")
 
 
 	# Ocr Rule Assets
@@ -135,5 +137,9 @@ class ActivityShikigamiAssets:
 	O_REMAIN_BOSS = RuleOcr(roi=(1113,669,131,31), area=(1099,659,162,52), mode="DigitCounter", method="Default", keyword="", name="remain_boss")
 	# 挑战 
 	O_FIRE = RuleOcr(roi=(1137,599,83,44), area=(1129,570,100,100), mode="Single", method="Default", keyword="挑战", name="fire")
+	# 100体活动门票检测 
+	O_REMAIN_AP100 = RuleOcr(roi=(922,21,112,39), area=(913,8,131,62), mode="Digit", method="Default", keyword="", name="remain_ap100")
+	# 进入100体活动标识 
+	O_ENTER_AP100 = RuleOcr(roi=(72,187,95,32), area=(7,172,256,108), mode="Single", method="Default", keyword="将魂试炼", name="enter_ap100")
 
 

+ 72 - 29
tasks/ActivityShikigami/config.py

@@ -1,9 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
-from enum import Enum
-from datetime import time, timedelta
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
 
 from tasks.Component.GeneralBattle.config_general_battle import GreenMarkType
 from tasks.Component.config_scheduler import Scheduler
@@ -11,62 +9,107 @@ from tasks.Component.config_base import ConfigBase, TimeDelta
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 
 
-class ShikigamiType(str, Enum):
-    FOOD_TYPE_1 = 'shikigami_type_1'
-    FOOD_TYPE_2 = 'shikigami_type_2'
-    FOOD_TYPE_3 = 'shikigami_type_3'
-    FOOD_TYPE_4 = 'shikigami_type_4'
+def check_soul_by_number(enable_switch: bool, group_team: str, label: str):
+    if not enable_switch:
+        return
+    if not group_team or group_team == "-1,-1":
+        raise ValueError(f"[{label}]Switch Soul configuration is enabled, but there is no setting")
+    if ',' not in group_team:
+        raise ValueError(f"[{label}]The switch soul configuration must be in English ','")
+    parts = group_team.split(',')
+    if len(parts) != 2:
+        raise ValueError(f"[{label}]The length of the switch soul configuration must be equal to 2")
+    if not all(p.strip().isdigit() for p in parts):
+        raise ValueError(f"[{label}]Switching soul configurations must be numeric")
+
+
+def check_soul_by_ocr(enable_switch: bool, group_team: str, label: str):
+    if not enable_switch:
+        return
+    if not group_team:
+        raise ValueError(f"[{label}]Switch Soul configuration is enabled, but there is no setting")
+    if ',' not in group_team:
+        raise ValueError(f"[{label}]The switch soul configuration must be in English ','")
+    parts = group_team.split(',')
+    if len(parts) != 2:
+        raise ValueError(f"[{label}]The length of the switch soul configuration must be equal to 2")
 
 
 class SwitchSoulConfig(BaseModel):
-    # 切换门票爬塔御魂
     enable_switch_pass: bool = Field(default=False, description='是否切换门票爬塔御魂')
-    pass_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔。战斗内切换队伍预设也使用该值')
+    pass_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
     enable_switch_pass_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     pass_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-    # 切换体力爬塔御魂
+
     enable_switch_ap: bool = Field(default=False, description='是否切换体力爬塔御魂')
-    ap_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔。战斗内切换队伍预设也使用该值')
+    ap_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
     enable_switch_ap_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     ap_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
-    # 切换boss爬塔御魂
+
     enable_switch_boss: bool = Field(default=False, description='是否切换boss爬塔御魂')
-    boss_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔。战斗内切换队伍预设也使用该值')
+    boss_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
     enable_switch_boss_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
     boss_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
 
+    enable_switch_ap100: bool = Field(default=False, description='是否切换100体爬塔御魂')
+    ap100_group_team: str = Field(default='-1,-1', description='组1-7,队伍1-4 中间用英文,分隔')
+    enable_switch_ap100_by_name: bool = Field(default=False, description='是否通过ocr切换御魂')
+    ap100_group_team_name: str = Field(default='', description='组名,队伍名 中间用英文,分隔')
+
+    # @model_validator(mode='after')
+    def validate_switch_soul(self):
+        label_set = self.get_label_set()
+        for label in label_set:
+            enable_num = getattr(self, f"enable_switch_{label}", False)
+            team = getattr(self, f"{label}_group_team", None)
+            check_soul_by_number(enable_num, team, label=label.upper())
+
+            enable_ocr = getattr(self, f"enable_switch_{label}_by_name", False)
+            team_name = getattr(self, f"{label}_group_team_name", None)
+            check_soul_by_ocr(enable_ocr, team_name, label=label.upper())
+        return self
+
+    def get_label_set(self):
+        return {field.replace("enable_switch_", "") for field in self.model_fields if
+                     field.startswith("enable_switch_") and not field.endswith("by_name")}
+
 
 class GeneralBattleConfig(BaseModel):
-    # 是否切换门票爬塔预设
-    enable_pass_preset: bool = Field(default=False, description='是否切换门票爬塔预设')
-    # 是否开启门票爬塔绿标
+    enable_pass_preset: bool = Field(default=False, description='是否切换门票爬塔预设, 仅数字切换御魂可用')
     enable_pass_green: bool = Field(default=False, description='是否开启门票爬塔绿标')
-    # 门票爬塔绿标位置
     pass_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='门票爬塔绿标位置')
-    # 门票爬塔战斗过程是否随机点击或滑动
     enable_pass_anti_detect: bool = Field(default=False, description='门票爬塔战斗过程是否随机点击或滑动')
 
-    # 是否切换体力爬塔预设
-    enable_ap_preset: bool = Field(default=False, description='是否切换体力爬塔预设')
-    # 是否开启体力爬塔绿标
+    enable_ap_preset: bool = Field(default=False, description='是否切换体力爬塔预设, 仅数字切换御魂可用')
     enable_ap_green: bool = Field(default=False, description='是否开启体力爬塔绿标')
-    # 体力爬塔绿标位置
     ap_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='体力爬塔绿标位置')
-    # 体力爬塔战斗过程是否随机点击或滑动
     enable_ap_anti_detect: bool = Field(default=False, description='体力爬塔战斗过程是否随机点击或滑动')
 
-    # 是否切换boss爬塔预设
-    enable_boss_preset: bool = Field(default=False, description='是否切换boss爬塔预设')
-    # 是否开启boss爬塔绿标
+    enable_boss_preset: bool = Field(default=False, description='是否切换boss爬塔预设, 仅数字切换御魂可用')
     enable_boss_green: bool = Field(default=False, description='是否开启boss爬塔绿标')
-    # boss爬塔绿标位置
     boss_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='boss爬塔绿标位置')
-    # boss爬塔战斗过程是否随机点击或滑动
     enable_boss_anti_detect: bool = Field(default=False, description='boss爬塔战斗过程是否随机点击或滑动')
 
+    enable_ap100_preset: bool = Field(default=False, description='是否切换100体爬塔预设, 仅数字切换御魂可用')
+    enable_ap100_green: bool = Field(default=False, description='是否开启100体爬塔绿标')
+    ap100_green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1, description='100体爬塔绿标位置')
+    enable_ap100_anti_detect: bool = Field(default=False, description='100体爬塔战斗过程是否随机点击或滑动')
+
 
 class ActivityShikigami(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     general_climb: GeneralClimb = Field(default_factory=GeneralClimb)
     switch_soul_config: SwitchSoulConfig = Field(default_factory=SwitchSoulConfig)
     general_battle: GeneralBattleConfig = Field(default_factory=GeneralBattleConfig)
+
+    # @model_validator(mode='after')
+    def validate_switch_preset(self):
+        label_set = self.switch_soul_config.get_label_set()
+        for label in label_set:
+            enable_preset = getattr(self.general_battle, f"enable_{label}_preset", False)
+            group_team = getattr(self.switch_soul_config, f"{label}_group_team", None)
+            try:
+                check_soul_by_number(enable_preset, group_team, label=label.upper())
+            except ValueError:
+                raise ValueError(f'The switch preset is enabled, but the switch soul is configured incorrectly')
+        return self

+ 127 - 119
tasks/ActivityShikigami/script_task.py

@@ -15,7 +15,7 @@ from module.base.protect import random_sleep
 from module.exception import TaskEnd
 from module.logger import logger
 from tasks.ActivityShikigami.assets import ActivityShikigamiAssets
-from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig
+from tasks.ActivityShikigami.config import SwitchSoulConfig, GeneralBattleConfig, ActivityShikigami
 from tasks.Component.BaseActivity.base_activity import BaseActivity
 from tasks.Component.BaseActivity.config_activity import GeneralClimb
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
@@ -24,13 +24,6 @@ import tasks.GameUi.page as game
 from typing import Any
 
 
-def get_run_order_list(climb_conf: GeneralClimb) -> list[str]:
-    if not climb_conf.run_sequence or len(climb_conf.run_sequence.split(',')) == 1:
-        raise ValueError('Run sequence now is empty, must set it')
-    run_order_list = [climb_type.strip() for climb_type in climb_conf.run_sequence.split(',')]
-    return [climb_type for climb_type in run_order_list if getattr(climb_conf, f'enable_{climb_type}', False)]
-
-
 def _prepare_image_for_ocr(image: np.ndarray, asset: RuleOcr) -> np.ndarray:
     image_copy = image.copy()
     x, y, w, h = asset.roi
@@ -84,89 +77,63 @@ class Status(Enum):
     ALREADY_SWITCH_BUFF = auto()  # 已经切换buff
     GOTO_ACT_FAILED = auto()  # 前往活动失败
     ENTER_BATTLE_FAILED = auto()  # 进入战斗失败
+    COUNT_LIMIT = auto()  # 达到次数限制
+    NO_TICKETS = auto()  # 没有票数
 
 
 class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
-    # key: climb type, value: run count
-    count_map: dict[str, int] = {
-        'pass': 0,
-        'ap': 0,
-        'boss': 0
-    }
+    _check_map = None
+    _count_map = None
+
     page_map: dict[str, game.Page] = {
         'pass': game.page_climb_act_pass,
         'ap': game.page_climb_act_ap,
         'boss': game.page_climb_act_boss,
+        'ap100': game.page_climb_act_ap100,
     }
-    # key: climb type, value: {status: value}
-    check_map: dict[str, dict[Status, Any]] = {}
-
-    climb_type: str = 'pass'
     run_idx: int = 0
-
-    def put_status(self):
-        """
-        更新全局状态
-        """
-        # 超过运行时间
-        if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
-            logger.warning(f"Climb type {self.climb_type} time out")
-            self.put_check(Status.TIME_OUT, True)
-        # 次数达到限制
-        if self.get_count() >= self.get_limit(self.config.activity_shikigami.general_climb):
-            logger.info(f"Climb type {self.climb_type} count limit reached")
-            self.put_check(Status.DOWN, True)
-
-    def check(self, status: Status) -> Any:
-        if len(self.check_map) == 0:
-            self.check_map = {climb_type: {state: None for state in list(Status)} for climb_type in
-                              get_run_order_list(self.config.activity_shikigami.general_climb)}
-        return self.check_map[self.climb_type][status]
-
-    def put_check(self, status: Status, value: Any):
-        self.check_map[self.climb_type][status] = value
+    conf: ActivityShikigami = None
 
     def run(self) -> None:
-        config = self.config.activity_shikigami
-        self.limit_time: timedelta = config.general_climb.limit_time
-        if isinstance(self.limit_time, time):
-            self.limit_time = timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
-                                        seconds=self.limit_time.second)
-        # 初始化爬塔类型
-        self.climb_type = get_run_order_list(config.general_climb)[0]
+        self.conf = self.config.activity_shikigami
+        self.limit_time: timedelta = self.conf.general_climb.limit_time_v
         while True:
             self.put_status()
             # 超时或全部完成则退出
             if self.check(Status.TIME_OUT) or self.check(Status.ALL_DOWN):
+                logger.hr(f'Climb act all down')
                 break
-            # 当前爬塔类型完成了, 切换下一个类型
-            if self.check(Status.DOWN):
+            # 当前爬塔类型完成了或达到次数限制了, 切换下一个类型
+            if self.check(Status.DOWN) or self.check(Status.COUNT_LIMIT):
                 self.switch_next()
                 continue
             # 获取当前页面
             current_page = self.ui_get_current_page(False)
-            # 检查是否已经切换御魂
-            if not self.check(Status.ALREADY_SWITCH_SOUL):
-                self.switch_soul(config.switch_soul_config)
-                continue
             match current_page:
                 # 庭院, 进入活动主界面
                 case game.page_main:
+                    self.switch_soul(self.conf.switch_soul_config)
                     self.home_main()
                 # 活动主界面或副界面, 进入最终爬塔界面
                 case game.page_climb_act | game.page_climb_act_2:
+                    self.switch_soul(self.conf.switch_soul_config)
                     # self.ui_goto(game.page_climb_act_buff)
                     self.goto_act()
                 # buff界面, 进入最终爬塔界面
                 case game.page_climb_act_buff:
-                    self.switch_buff(config.general_climb)
+                    self.switch_buff(self.conf.general_climb)
                     self.goto_act()
                 # 最终爬塔界面
-                case game.page_climb_act_pass | game.page_climb_act_ap | game.page_climb_act_boss:
-                    if not self.check_can_run():
-                        continue
-                    self.lock_team(config.general_battle)
+                case game.page_climb_act_pass | game.page_climb_act_ap | game.page_climb_act_ap100 | game.page_climb_act_boss:
+                    self.switch_soul(self.conf.switch_soul_config)
+                    self.lock_team(self.conf.general_battle)
+                    self.check_tickets_enough()
                     self.start_battle()
+                case game.page_battle_auto:
+                    self.battle_wait(getattr(self.conf.general_battle, f'enable_{self.climb_type}_anti_detect',
+                                             False))
+                case game.page_battle_hand:
+                    self.ui_click_until_disappear(game.page_battle_hand.check_button)
                 case _:
                     if self.check(Status.GOTO_ACT_FAILED):
                         logger.warning(f'Climb type[{self.climb_type}] goto failed')
@@ -174,29 +141,42 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
                         continue
                     self.put_check(Status.GOTO_ACT_FAILED, True)
                     # 任何活动界面都没有识别到, 尝试主动前往爬塔活动
-                    self.goto_act()
+                    self.goto_act(timeout=25)
         # 返回庭院
         self.main_home()
-        if config.general_climb.active_souls_clean:
+        if self.conf.general_climb.active_souls_clean:
             self.set_next_run(task='SoulsTidy', success=False, finish=False, target=datetime.now())
         self.set_next_run(task="ActivityShikigami", success=True)
         raise TaskEnd
 
     def start_battle(self):
+        # 先识别是否在挑战界面, 不在则交给上层处理
+        if not self.wait_until_appear(self.O_FIRE, wait_time=3):
+            logger.warning(f'Detect fire fail, try reidentify')
+            return
         # 点击战斗前随机休息
-        if self.config.activity_shikigami.general_climb.random_sleep:
+        if self.conf.general_climb.random_sleep:
             random_sleep(probability=0.2)
         logger.info("Click battle")
-        click_times, max_times = 0, 3
+        click_times, max_times = 0, random.randint(2, 4)
         while 1:
             self.screenshot()
             if self.is_in_battle(False):
+                # 进入战斗了则一定有门票
+                self.put_check(Status.NO_TICKETS, False)
                 break
             if click_times >= max_times:
+                # 挑战点击失败, 且无门票则大概率真没有票了
+                if self.check(Status.NO_TICKETS):
+                    self.put_check(Status.DOWN, True)
+                    logger.info(f'Climb {self.climb_type} no tickets detected, try next')
+                    return
+                # 有门票且挑战已经点击失败过一次了
                 if self.check(Status.ENTER_BATTLE_FAILED):
                     logger.warning(f'Climb {self.climb_type} cannot enter, maybe already end, try next')
                     self.put_check(Status.DOWN, True)
                     return
+                # 有门票但挑战点击失败, 交给上层处理
                 logger.warning(f'Climb type {self.climb_type} enter fail, try reidentify')
                 self.put_check(Status.ENTER_BATTLE_FAILED, True)
                 return
@@ -204,56 +184,50 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
             if self.ocr_appear_click(self.O_FIRE, interval=2):
                 click_times += 1
                 continue
-            if self.appear_then_click(self.I_C_CONFIRM1, interval=0.6):
-                continue
-            if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1):
-                continue
-            if self.appear_then_click(self.I_UI_CONFIRM, interval=1):
-                continue
-            if self.appear_then_click(self.I_N_CONFIRM, interval=1):
+            if ((self.appear_then_click(self.I_C_CONFIRM1, interval=0.6) or
+                 self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=1) or
+                 self.appear_then_click(self.I_UI_CONFIRM, interval=1)) or
+                    self.appear_then_click(self.I_N_CONFIRM, interval=1)):
                 continue
         # 运行战斗
-        if self.run_general_battle(config=self.get_general_battle_conf()):
-            self.count_map[self.climb_type] += 1
-            logger.info("General battle success")
+        self.run_general_battle(config=self.get_general_battle_conf())
 
     def battle_wait(self, random_click_swipt_enable: bool) -> bool:
         # 通用战斗结束判断
         self.device.stuck_record_add("BATTLE_STATUS_S")
         self.device.click_record_clear()
-        logger.info("Start battle process")
-
+        logger.info(f"Start {self.climb_type} battle process")
+        self.count_map[self.climb_type] = self.current_count
         for btn in (self.C_RANDOM_LEFT, self.C_RANDOM_RIGHT, self.C_RANDOM_TOP, self.C_RANDOM_BOTTOM):
             btn.name = "BATTLE_RANDOM"
         ok_cnt, max_retry = 0, 5
         while 1:
-            sleep(0.5)
+            sleep(random.uniform(1, 1.5))
             self.screenshot()
-            # 已经回到对应挑战界面
-            if self.ui_page_appear(self.page_map[self.climb_type]):
-                break
-            # 达到最大重试次数且还没有识别到活动界面
+            # 达到最大重试次数则直接交给上层处理
             if ok_cnt > max_retry:
-                # 跳出循环交由外部处理
                 break
+            # 识别到挑战说明已经退出战斗
+            if ok_cnt > 0 and self.ocr_appear(self.O_FIRE):
+                return True
             # 失败
             if self.appear(self.I_FALSE):
-                logger.warning("False battle")
+                logger.warning("Battle failed")
                 self.ui_click_until_smt_disappear(self.random_reward_click(click_now=False), self.I_FALSE, interval=1.5)
                 return False
             # 奖励界面
             if self.ui_page_appear(game.page_reward):
-                logger.info(f'Battle end, try close {ok_cnt}')
+                logger.info(f'Battle success, try close reward page[{ok_cnt}]')
                 self.random_reward_click(exclude_click=[self.C_RANDOM_BOTTOM])
                 ok_cnt += 1
                 continue
-            # 已经不在战斗中了, 且奖励也识别过了还不在活动界面, 则随机点击
+            # 已经不在战斗中了, 且奖励也识别过了, 则随机点击
             if ok_cnt > 0 and not self.ui_page_appear(game.page_battle_auto):
                 self.random_reward_click(exclude_click=[self.C_RANDOM_BOTTOM])
                 ok_cnt += 1
                 continue
             # 战斗中随机滑动
-            if random_click_swipt_enable:
+            if ok_cnt == 0 and random_click_swipt_enable:
                 self.random_click_swipt()
         return True
 
@@ -265,19 +239,17 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
         """
         if self.check(Status.ALREADY_SWITCH_SOUL):
             return
+        conf.validate_switch_soul()
         self.put_check(Status.ALREADY_SWITCH_SOUL, True)
         enable_switch = getattr(conf, f"enable_switch_{self.climb_type}", False)
         enable_by_name = getattr(conf, f"enable_switch_{self.climb_type}_by_name", False)
         if enable_switch or enable_by_name:
             self.ui_goto(game.page_shikigami_records)
         if enable_by_name:
-            group_name = getattr(conf, f"{self.climb_type}_group_team_name", '-1,-1')
-            if not group_name or len(group_name.split(',')) != 2:
-                raise ValueError('switch soul by name must be 2 length')
-            group, team = group_name.split(",")
+            group, team = getattr(conf, f"{self.climb_type}_group_team_name").split(",")
             self.run_switch_soul_by_name(group, team)
         elif enable_switch:
-            group_team = getattr(conf, f"{self.climb_type}_group_team", '-1,-1')
+            group_team = getattr(conf, f"{self.climb_type}_group_team")
             self.run_switch_soul(group_team)
         self.goto_act()
 
@@ -352,6 +324,19 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
                 self.appear_then_click(self.I_BUFF_UP, buff_up_map[buff_list[i]], interval=0.5)
             logger.info(f'Up {buff_list[i]} ok')
 
+    def put_status(self):
+        """
+        更新全局状态
+        """
+        # 超过运行时间
+        if self.limit_time is not None and datetime.now() - self.start_time >= self.limit_time:
+            logger.warning(f"Climb type {self.climb_type} time out")
+            self.put_check(Status.TIME_OUT, True)
+        # 次数达到限制
+        if self.get_count() >= self.get_limit():
+            logger.info(f"Climb type {self.climb_type} count limit reached")
+            self.put_check(Status.DOWN, True)
+
     def get_count(self) -> int:
         """
         获取当前爬塔类型运行次数
@@ -359,19 +344,15 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
         """
         return self.count_map[self.climb_type]
 
-    def check_can_run(self) -> bool:
+    def check_tickets_enough(self):
         """
-        判断当前爬塔类型能否运行
-        pass: 剩余门票爬塔票数>0
-        ap: 剩余体力爬塔票数>0
-        boss: 剩余挑战次数>0
+        判断当前爬塔门票是否足够
         :return: True 可以运行 or False
         """
-        logger.hr(f'Check the {self.climb_type}', 3)
-        if not self.wait_until_appear(self.O_FIRE, wait_time=5):
-            logger.info(f'Detect fire fail, try next')
-            self.put_check(Status.DOWN, True)
-            return False
+        logger.hr(f'Check {self.climb_type} tickets')
+        if not self.wait_until_appear(self.O_FIRE, wait_time=3):
+            logger.warning(f'Detect fire fail, try reidentify')
+            return
         self.screenshot()
         remain_times = 0
         if self.climb_type == 'pass':
@@ -382,16 +363,17 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
                 _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP))
         if self.climb_type == 'boss':
             _, remain_times, _ = self.O_REMAIN_BOSS.ocr_digit_counter(self.device.image)
-        self.put_check(Status.DOWN, remain_times <= 0)
-        return remain_times > 0
+        if self.climb_type == 'ap100':
+            remain_times = self.O_REMAIN_AP100.ocr_digit(
+                _prepare_image_for_ocr(self.device.image, asset=self.O_REMAIN_AP100))
+        self.put_check(Status.NO_TICKETS, remain_times <= 0)
 
-    def get_limit(self, climb_conf: GeneralClimb) -> int:
+    def get_limit(self) -> int:
         """
         获取配置中当前爬塔类型次数限制
-        :param climb_conf: 爬塔配置
         :return: 限制次数
         """
-        limit = getattr(climb_conf, f'{self.climb_type}_limit', 0)
+        limit = getattr(self.conf.general_climb, f'{self.climb_type}_limit', 0)
         return 0 if not limit else limit
 
     def switch_next(self):
@@ -400,35 +382,31 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
         :return: True 切换成功 or False
         """
         self.run_idx += 1
-        climb_type_list = get_run_order_list(self.config.activity_shikigami.general_climb)
-        if self.run_idx >= len(climb_type_list):
+        if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
             logger.info('All climbing activities have been completed')
             self.put_check(Status.ALL_DOWN, True)
             return
         # 切换爬塔类型了, 恢复所有状态
-        self.climb_type = climb_type_list[self.run_idx]
         self.current_count = 0
         self.put_check(Status.ALREADY_SWITCH_SOUL, False)
         self.put_check(Status.ALREADY_LOCK_TEAM, False)
         self.put_check(Status.GOTO_ACT_FAILED, False)
         self.put_check(Status.ENTER_BATTLE_FAILED, False)
-        logger.hr(f'Climb type switch to {self.climb_type}', 2)
+        self.put_check(Status.COUNT_LIMIT, False)
+        logger.hr(f'Climb switch to {self.climb_type}', 2)
 
     def get_general_battle_conf(self) -> tasks.Component.GeneralBattle.config_general_battle.GeneralBattleConfig:
         from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig as gbc
-        conf = self.config.activity_shikigami
-        enable_preset = getattr(conf.general_battle, f'enable_{self.climb_type}_preset', False)
-        group_team = getattr(conf.switch_soul_config, f'{self.climb_type}_group_team')
-        if enable_preset and (not group_team or len(group_team.split(',')) != 2):
-            raise ValueError('Enable preset but group team not set correct!')
-        group, team = group_team.split(',')
+        self.conf.validate_switch_preset()
+        enable_preset = getattr(self.conf.general_battle, f'enable_{self.climb_type}_preset', False)
+        group, team = getattr(self.conf.switch_soul_config, f'{self.climb_type}_group_team').split(',')
         return gbc(lock_team_enable=not enable_preset,
                    preset_enable=enable_preset,
                    preset_group=group if enable_preset else 1,
                    preset_team=team if enable_preset else 1,
-                   green_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_green', False),
-                   green_mark=getattr(conf.general_battle, f'{self.climb_type}_green_mark'),
-                   random_click_swipt_enable=getattr(conf.general_battle, f'enable_{self.climb_type}_anti_detect',
+                   green_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_green', False),
+                   green_mark=getattr(self.conf.general_battle, f'{self.climb_type}_green_mark'),
+                   random_click_swipt_enable=getattr(self.conf.general_battle, f'enable_{self.climb_type}_anti_detect',
                                                      False), )
 
     def home_main(self) -> bool:
@@ -448,8 +426,8 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
         self.ui_get_current_page(False)
         self.ui_goto(game.page_main)
 
-    def goto_act(self):
-        self.ui_goto(self.page_map[self.climb_type], timeout=20)
+    def goto_act(self, timeout: int = 45):
+        self.ui_goto(self.page_map[self.climb_type], timeout=timeout)
 
     def random_reward_click(self, exclude_click: list = None, click_now: bool = True) -> RuleClick:
         """
@@ -466,6 +444,36 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
             self.click(target, interval=1.8)
         return target
 
+    @property
+    def climb_type(self) -> str:
+        if self.run_idx >= len(self.conf.general_climb.run_sequence_v):
+            return self.conf.general_climb.run_sequence_v[-1]
+        return self.conf.general_climb.run_sequence_v[self.run_idx]
+
+    @property
+    def count_map(self) -> dict[str, int]:
+        """
+        :return: key: climb type, value: run count
+        """
+        if not getattr(self, "_count_map", None):
+            self._count_map = {climb_type: 0 for climb_type in self.conf.general_climb.run_sequence_v}
+        return self._count_map
+
+    @property
+    def check_map(self) -> dict[str, dict[Status, Any]]:
+        if not getattr(self, "_check_map", None):
+            self._check_map = {
+                climb_type: {status: None for status in list(Status)}
+                for climb_type in self.conf.general_climb.run_sequence_v
+            }
+        return self._check_map
+
+    def check(self, status: Status) -> Any:
+        return self.check_map[self.climb_type][status]
+
+    def put_check(self, status: Status, value: Any):
+        self.check_map[self.climb_type][status] = value
+
 
 if __name__ == '__main__':
     from module.config.config import Config

+ 30 - 15
tasks/Component/BaseActivity/config_activity.py

@@ -2,7 +2,7 @@
 # @author runhey
 # github https://github.com/runhey
 from datetime import time, timedelta
-from pydantic import BaseModel, Field, validator, field_validator
+from pydantic import BaseModel, Field, validator, field_validator, model_validator
 from enum import Enum
 
 from module.logger import logger
@@ -16,23 +16,13 @@ class ApMode(str, Enum):
 
 
 class GeneralClimb(ConfigBase):
-    # 限制执行的时间
-    limit_time: Time = Field(default=Time(minute=30), description='限制爬塔运行时间')
-    # 限制门票爬塔的次数
+    limit_time: Time = Field(default=Time(minute=30), description='限制爬塔运行总时间')
     pass_limit: int = Field(default=50, description='门票爬塔的最大次数')
-    # 限制体力爬塔的次数
     ap_limit: int = Field(default=300, description='体力爬塔的最大次数')
-    # 限制boss战爬塔的次数
     boss_limit: int = Field(default=20, description='boss战爬塔的最大次数')
-    # 启用门票爬塔
-    enable_pass: bool = Field(default=True, description='是否启用门票爬塔')
-    # 启用体力爬塔
-    enable_ap: bool = Field(default=True, description='是否启用体力爬塔')
-    # 启用boss战爬塔
-    enable_boss: bool = Field(default=True, description='是否启用boss战爬塔')
-    # 爬塔运行顺序
-    run_sequence: str = Field(default='pass,boss,ap',
-                              description='爬塔运行顺序,英文逗号分隔,从左到右运行,若没启用自动跳过对应类型(pass:门票,boss:boss战,ap:体力)')
+    ap100_limit: int = Field(default=20, description='100体爬塔的最大次数')
+    run_sequence: str = Field(default='pass,ap100,boss,ap',
+                              description='运行爬塔顺序(pass:门票,ap100:100体,boss:boss战,ap:体力)\n英文逗号分隔,从左到右运行,可自定义执行顺序\n例如:pass,ap100,boss,ap就是门票->100体->boss战->体力')
     # # 门票爬塔buff
     # pass_buff: str = Field(default='buff_4,buff_5', description='门票爬塔加成,buff1-5,加成页从左往右顺序,清空则不切换加成')
     # # 体力爬塔buff
@@ -44,6 +34,31 @@ class GeneralClimb(ConfigBase):
     # 点击战斗随机休息
     random_sleep: bool = Field(default=False, description='是否启用在点击战斗前随机休息')
 
+    @property
+    def limit_time_v(self) -> timedelta:
+        if isinstance(self.limit_time, time):
+            return timedelta(hours=self.limit_time.hour, minutes=self.limit_time.minute,
+                             seconds=self.limit_time.second)
+        return self.limit_time
+
+    @property
+    def run_sequence_v(self) -> list[str]:
+        self.valid_run_sequence()
+        return [climb_type.strip() for climb_type in self.run_sequence.split(',')]
+
+    # @model_validator(mode='after')
+    def valid_run_sequence(self):
+        if not self.run_sequence or not self.run_sequence.strip():
+            raise ValueError('run sequence cannot be empty')
+        sequence_list = [climb_type.strip() for climb_type in self.run_sequence.split(',')]
+        if not sequence_list or len(sequence_list) < 1:
+            raise ValueError('run sequence cannot be empty')
+        label_set = {field.replace('_limit', '') for field in self.model_fields if field.endswith('_limit')}
+        for climb_type in sequence_list:
+            if climb_type not in label_set:
+                raise ValueError(f'run sequence can only be one of {", ".join(label_set)}, now is {climb_type}')
+        return self
+
     @validator('limit_time', pre=True, always=True)
     def parse_limit_time(cls, value):
         if isinstance(value, str):

+ 108 - 59
tasks/GameUi/game_ui.py

@@ -2,8 +2,12 @@
 # @author runhey
 # github https://github.com/runhey
 import time
+from datetime import datetime
 from time import sleep
+
+import random
 from collections import deque
+from module.atom.gif import RuleGif
 from module.atom.image import RuleImage
 from module.atom.list import RuleList
 from module.atom.ocr import RuleOcr
@@ -37,16 +41,17 @@ class GameUi(BaseTask, GameUiAssets):
         page_collection, page_act_list,
         # 爬塔活动
         page_act_list_climb_act, page_climb_act, page_climb_act_2, page_climb_act_pass, page_climb_act_ap,
-        page_climb_act_boss, page_climb_act_buff,
+        page_climb_act_boss, page_climb_act_buff, page_climb_act_ap100,
         # 战斗
-        page_battle_auto, page_battle_hand, page_reward
+        page_battle_auto, page_battle_hand, page_reward, page_failed
     ]
     ui_close = [GameUiAssets.I_BACK_MALL, GeneralBattleAssets.I_CONFIRM,
                 BaseTask.I_UI_BACK_RED, BaseTask.I_UI_BACK_YELLOW, BaseTask.I_UI_BACK_BLUE,
                 GameUiAssets.I_BACK_FRIENDS, GameUiAssets.I_BACK_DAILY,
                 GameUiAssets.I_REALM_RAID_GOTO_EXPLORATION,
                 GameUiAssets.I_SIX_GATES_GOTO_EXPLORATION, SixRealmsAssets.I_EXIT_SIXREALMS,
-                ActivityShikigamiAssets.I_SKIP_BUTTON, ActivityShikigamiAssets.I_RED_EXIT, ActivityShikigamiAssets.I_RED_EXIT_2]
+                ActivityShikigamiAssets.I_SKIP_BUTTON, ActivityShikigamiAssets.I_RED_EXIT,
+                ActivityShikigamiAssets.I_RED_EXIT_2]
 
     def home_explore(self) -> bool:
         """
@@ -76,10 +81,15 @@ class GameUi(BaseTask, GameUiAssets):
         logger.info(f'Click {self.I_HOME_SHIKIKAMI.name}')
         return True
 
-    def ui_page_appear(self, page):
+    def ui_page_appear(self, page: Page, skip_first_screenshot: bool = True, interval: float = random.uniform(0.5, 1)):
         """
         判断当前页面是否为page
         """
+        if interval:
+            interval_timer = Timer(interval).start()
+            interval_timer.wait()
+        if not skip_first_screenshot:
+            self.screenshot()
         if isinstance(page.check_button, list):
             for button in page.check_button:
                 if self.appear(button):
@@ -87,17 +97,19 @@ class GameUi(BaseTask, GameUiAssets):
             return False
         return self.appear(page.check_button)
 
-    def ui_wait_until_appear(self, page: Page, timeout: int = 3, interval: float = 0.5) -> bool:
+    def ui_wait_until_appear(self, page: Page, timeout: float = 3, interval: float = 0.5,
+                             skip_first_screenshot: bool = True) -> bool:
         """
         等待页面出现
         """
         logger.info(f'Waiting for {page}')
         timeout_timer = Timer(timeout).start()
+        interval_timer = Timer(interval).start()
         while not timeout_timer.reached():
-            self.screenshot()
-            if self.ui_page_appear(page):
+            if self.ui_page_appear(page, skip_first_screenshot):
                 return True
-            sleep(interval)
+            skip_first_screenshot = False
+            interval_timer.wait().reset()
         return False
 
     def ensure_scroll_open(self):
@@ -154,7 +166,7 @@ class GameUi(BaseTask, GameUiAssets):
             for page in self.ui_pages:
                 if not page.check_button:
                     continue
-                if self.ui_page_appear(page=page):
+                if self.ui_page_appear(page=page, interval=None):
                     logger.attr("UI", page.name)
                     self.ui_current = page
                     if page == page_main and self.ensure_scroll_open():
@@ -185,15 +197,15 @@ class GameUi(BaseTask, GameUiAssets):
         Args:
             button (Button):
         """
-        pass
+        if getattr(button, 'name', None) and button.name in self.interval_timer:
+            self.interval_timer[button.name].reset()
 
-    def build_reverse_paths(self, destination: Page) -> list[tuple[Page, list[Page]]]:
+    def build_reverse_path_dict(self, destination: Page) -> dict[Page, list[Page]]:
         """
         构建从每个页面到目标页面的最短路径(反向 BFS)
-        并按路径长度从短到长排序返回。
 
         Returns:
-            list[tuple[Page, list[Page]]] -> [(start_page, [path...destinationPage]), ...]
+            dict[Page, list[Page]] -> {start_page: [page1, ...destinationPage], ...}
         """
         paths = {destination: [destination]}
         queue = deque([destination])
@@ -204,11 +216,22 @@ class GameUi(BaseTask, GameUiAssets):
                     # page -> cur
                     paths[page] = [page] + paths[cur]
                     queue.append(page)
+        return paths
+
+    def build_reverse_paths(self, destination: Page) -> list[tuple[Page, list[Page]]]:
+        """
+        构建从每个页面到目标页面的最短路径(反向 BFS)
+        路径从短到长排序
+
+        Returns:
+            [(start_page, [page1, ...destinationPage]), ...]
+        """
+        paths = self.build_reverse_path_dict(destination)
         # 转换成列表并按路径长度排序, 短到长
         sorted_paths = sorted(paths.items(), key=lambda kv: len(kv[1]))
         return sorted_paths
 
-    def ui_goto(self, destination: Page, confirm_wait=0, skip_first_screenshot=True, timeout: int = 45):
+    def ui_goto(self, destination: Page, confirm_wait=0, skip_first_screenshot=True, timeout: int = 60):
         """
         Args:
             destination (Page):
@@ -220,82 +243,108 @@ class GameUi(BaseTask, GameUiAssets):
         # 初始化
         timeout_timer = Timer(timeout).start()
         confirm_timer = Timer(confirm_wait, count=int(confirm_wait // 0.5)).start()
-        try_close_unknown_timer = Timer(3).start()
-        # 构建路径映射并排序
-        paths = self.build_reverse_paths(destination)
+        close_unknown_timer = Timer(3).start()
+        # 构建路径映射
+        path_dict = self.build_reverse_path_dict(destination)
 
         while not timeout_timer.reached():
-            if not skip_first_screenshot:
-                self.screenshot()
-            skip_first_screenshot = False
             # 已经在目标页面
-            if self.ui_page_appear(destination):
+            if self.ui_page_appear(destination, skip_first_screenshot):
                 if confirm_timer.reached():
                     logger.info(f'Page arrive: {destination}')
-                    break
-                confirm_timer.reset()
+                    return True
                 continue
+            skip_first_screenshot = False
             # 尝试关闭未知页面
-            if try_close_unknown_timer.reached():
+            if close_unknown_timer.reached_and_reset():
+                logger.warning('Trying to switch to supported page')
                 for close in self.ui_close:
                     if self.appear_then_click(close, interval=1.5):
-                        logger.warning('Trying to switch to supported page')
-                try_close_unknown_timer.reset()
-            # 遍历所有路径,优先尝试最短路径
-            for page, path in paths:
-                if not self.ui_page_appear(page):
-                    continue
-                logger.info(f"Current page: {page}. Following shortest path:")
-                show_paths: str = ''.join([f"{p.name} -> " for p in path])
-                logger.info(f" {show_paths}")
-                if self._execute_path(path, confirm_timer, timeout_timer):
-                    return True
-            sleep(0.3)
+                        logger.info(f'[{close_unknown_timer.current():.1f}s]Click {close} on {self.ui_current} success')
+            confirm_timer.reset()
+            path = path_dict.get(self.ui_current, None)
+            # 找不到路径则重新获取页面重试
+            if not path:
+                self.ui_get_current_page(skip_first_screenshot)
+                continue
+            logger.info(f"Current page: {self.ui_current}. Following shortest path:")
+            show_paths: str = ' -> '.join([p.name for p in path])
+            logger.info(f"{show_paths}")
+            # 遍历路径
+            if self._execute_path(path, timeout_timer) and confirm_timer.reached():
+                return True
         else:
             logger.error(f'Cannot goto page[{destination}], timeout[{timeout}s] reached')
         return False
 
-    def _execute_path(self, path: list, confirm_timer, timeout_timer):
+    def _execute_path(self, path: list, timeout_timer):
         """
         执行路径
         :param path: currentPage,page1,page2,...,destinationPage
-        :param confirm_timer: 确认定时器
         :param timeout_timer: 超时定时器
         :return: currentPage==destinationPage
         """
         for i in range(len(path) - 1):
             current_page, next_page = path[i], path[i + 1]
-            # 已超时则不再遍历
             if timeout_timer.reached():
                 return False
-            # 等待当前页面出现
-            self.ui_wait_until_appear(current_page)
-            logger.info(f'Page switch: {current_page} -> {next_page}')
+            # 当前页不等于路径中对应页, 尝试下一页
+            if self.ui_current != current_page:
+                continue
             # 执行附加操作
             if current_page.additional:
                 for button in current_page.additional:
-                    if ((isinstance(button, RuleClick) and self.click(button)) or
-                            self.appear_then_click(button, interval=0.6) or
-                            (isinstance(button, RuleOcr) and self.ocr_appear_click(button, interval=2))):
+                    if self.appear_then_operate(button, skip_first_screenshot=False, interval=random.uniform(0.4, 0.6)):
                         logger.info(f'Page {current_page} additional {button} clicked')
-                sleep(0.3)
-            # 执行页面跳转
+            logger.info(f'Page switch: {current_page} -> {next_page}')
+            # 获取页面跳转操作
             button = current_page.links.get(next_page)
             if not button:
                 logger.warning(f"No link from {current_page} to {next_page}")
-                return False
-            # 执行对应操作
-            if ((isinstance(button, RuleList) and self.list_appear_click(button)) or
-                    (isinstance(button, RuleClick) and self.click(button)) or
-                    self.appear_then_click(button, interval=2) or
-                    (isinstance(button, RuleOcr) and self.ocr_appear_click(button, interval=2))):
-                self.ui_button_interval_reset(button)
-                confirm_timer.reset()
+                continue
+            # 跳转页面
+            max_wait_timer = Timer(5).start()
+            while not max_wait_timer.reached():
+                if timeout_timer.reached():
+                    return False
+                if self.appear_then_operate(button, skip_first_screenshot=False):
+                    break
+                logger.warning(f"[{max_wait_timer.current():.1f}s]Failed click {button} on {current_page}, retry...")
+                sleep(0.3)
             else:
-                logger.warning(f"Failed to click {button} on {current_page}")
-                return False
-        # 最后确认目标页面
-        return self.ui_page_appear(path[-1])
+                self.ui_get_current_page(skip_first_screenshot=False)
+                # 当前页面不是对应路径的页面, 则尝试下一个页面
+                if self.ui_current != current_page:
+                    continue
+            max_wait_timer.reset()
+            while not max_wait_timer.reached():
+                if timeout_timer.reached():
+                    return False
+                if self.ui_wait_until_appear(next_page, timeout=1.5, interval=random.uniform(0.4, 0.8),
+                                             skip_first_screenshot=False):
+                    logger.info(f'[{max_wait_timer.current():.1f}s]Page arrived {next_page}')
+                    self.ui_current = next_page
+                    break
+            else:
+                # 重新获取当前页
+                self.ui_get_current_page(skip_first_screenshot=False)
+        return self.ui_current == path[-1]
+
+    def appear_then_operate(self, target: RuleList | RuleImage | RuleGif | RuleOcr | RuleClick,
+                            interval: float = random.uniform(0.6, 1.2), skip_first_screenshot: bool = True):
+        self.ui_button_interval_reset(target)
+        interval_timer = Timer(interval).start()
+        interval_timer.wait()
+        if not skip_first_screenshot:
+            self.screenshot()
+        if isinstance(target, RuleList):
+            return self.list_appear_click(target)
+        if isinstance(target, (RuleImage, RuleGif)):
+            return self.appear_then_click(target)
+        if isinstance(target, RuleOcr):
+            return self.ocr_appear_click(target)
+        if isinstance(target, RuleClick):
+            return self.click(target)
 
     # ------------------------------------------------------------------------------------------------------------------
     # 下面的这些是一些特殊的页面,需要额外处理

+ 18 - 5
tasks/GameUi/page.py

@@ -150,8 +150,10 @@ page_daily = Page(G.I_CHECK_DAILY)
 # page_daily.additional = [G.O_CLICK_CLOSE_1, G.O_CLICK_CLOSE_2]
 page_daily.link(button=G.I_BACK_Y, destination=page_main)
 page_main.link(button=G.I_MAIN_GOTO_DAILY, destination=page_daily)
+from tasks.DailyTrifles.assets import DailyTriflesAssets
+
 # 商店 mall
-page_mall = Page(G.I_CHECK_MALL)
+page_mall = Page(check_button=[G.I_CHECK_MALL, DailyTriflesAssets.I_ROOM_GIFT])
 page_mall.additional = [G.I_AD_CLOSE_RED, G.I_BACK_Y, G.I_DLC_CLOSE]
 page_mall.link(button=G.I_BACK_BLUE, destination=page_main)
 page_main.link(button=G.I_MAIN_GOTO_MALL, destination=page_mall)
@@ -200,7 +202,8 @@ page_climb_act.link(button=G.I_BACK_Y, destination=page_main)
 page_act_list_climb_act.link(button=G.I_ACT_LIST_GOTO_ACT, destination=page_climb_act)
 # 爬塔活动副界面
 page_climb_act_2 = Page(asa.I_CHECK_BATTLE_2)
-page_climb_act_2.additional = [asa.I_ACT_MAP_SWITCH, asa.I_PASS_ACT_LOCAT, asa.I_SKIP_BUTTON, asa.I_RED_EXIT, asa.I_RED_EXIT_2]
+page_climb_act_2.additional = [asa.I_ACT_MAP_SWITCH, asa.I_PASS_ACT_LOCAT, asa.I_SKIP_BUTTON, asa.I_RED_EXIT,
+                               asa.I_RED_EXIT_2]
 page_climb_act_2.link(button=G.I_BACK_BATTLE, destination=page_climb_act)
 page_climb_act.link(button=asa.I_BATTLE, destination=page_climb_act_2)
 # 门票爬塔活动界面
@@ -217,6 +220,10 @@ page_climb_act_2.link(button=asa.O_ENTRY_ACTIVITY, destination=page_climb_act_ap
 # 体力, 门票互相跳转
 # page_climb_act_ap.link(button=asa.I_SWITCH, destination=page_climb_act_pass)
 # page_climb_act_pass.link(button=asa.I_SWITCH, destination=page_climb_act_ap)
+# 100体爬塔活动界面
+page_climb_act_ap100 = Page(asa.I_CHECK_AP100)
+page_climb_act_2.link(button=asa.O_ENTER_AP100, destination=page_climb_act_ap100)
+page_climb_act_ap100.link(button=G.I_BACK_Y, destination=page_climb_act_2)
 # 爬塔活动boss战界面
 page_climb_act_boss = Page(asa.I_CHECK_BOSS)
 page_climb_act_boss.additional = [BT.I_UI_BACK_RED, asa.I_SKIP_BUTTON]
@@ -242,6 +249,7 @@ def random_click(low: int = None, high: int = None) -> RuleClick | list[RuleClic
     :return: RuleClick或者RuleClick的数组
     """
     click = random.choice([asa.C_RANDOM_LEFT, asa.C_RANDOM_RIGHT, asa.C_RANDOM_TOP])
+    click.name = "BATTLE_RANDOM"
     if low is None or high is None:
         return click
     return [click for _ in range(random.randint(low, high))]
@@ -249,10 +257,15 @@ def random_click(low: int = None, high: int = None) -> RuleClick | list[RuleClic
 
 # 奖励界面
 page_reward = Page(check_button=[GeneralBattleAssets.I_REWARD_PURPLE_SNAKE_SKIN, GeneralBattleAssets.I_REWARD,
-                                 GeneralBattleAssets.I_REWARD_EXP_SOUL_4,
+                                 GeneralBattleAssets.I_REWARD_EXP_SOUL_4, GeneralBattleAssets.I_WIN,
                                  GeneralBattleAssets.I_REWARD_GOLD, GeneralBattleAssets.I_REWARD_GOLD_SNAKE_SKIN,
                                  GeneralBattleAssets.I_REWARD_SOUL_5, GeneralBattleAssets.I_REWARD_SOUL_6,
-                                 gga.I_UI_REWARD],
+                                 gga.I_UI_REWARD, ],
+                   links={page_climb_act_pass: random_click(), page_climb_act_ap: random_click(),
+                          page_area_boss: random_click()})
+page_reward.additional = [random_click()]
+# 失败界面
+page_failed = Page(check_button=GeneralBattleAssets.I_FALSE,
                    links={page_climb_act_pass: random_click(), page_climb_act_ap: random_click(),
                           page_area_boss: random_click()})
-page_reward.additional = random_click(1, 3)
+page_failed.additional = [random_click()]

+ 23 - 23
tasks/base_task.py

@@ -4,6 +4,7 @@
 
 from time import sleep
 
+import random
 from datetime import datetime, timedelta
 from module.atom.animate import RuleAnimate
 from module.atom.click import RuleClick
@@ -468,31 +469,30 @@ class BaseTask(GlobalGameAssets, CostumeBase):
         :param name:
         :return:
         """
-        if target.is_image:
-            while True:
-                self.screenshot()
+        swipe_down = False
+        swipe_distance_ratio = None
+        result = None
+        if not target:
+            return False
+        while True:
+            self.screenshot()
+            if target.is_image:
                 result = target.image_appear(self.device.image, name=name)
-                if result is not None:
-                    return result
-                x1, y1, x2, y2 = target.swipe_pos()
-                self.device.swipe(p1=(x1, y1), p2=(x2, y2))
-
-        elif target.is_ocr:
-            while True:
-                self.screenshot()
+                swipe_down = True
+            elif target.is_ocr:
                 result = target.ocr_appear(self.device.image, name=name)
-                if isinstance(result, tuple):
-                    return result
-
-                after = True
-                if isinstance(result, int) and result > 0:
-                    after = True
-                elif isinstance(result, int) and result < 0:
-                    after = False
-
-                x1, y1, x2, y2 = target.swipe_pos(number=1, after=after)
-                self.device.swipe(p1=(x1, y1), p2=(x2, y2))
-                sleep(1)  # 等待滑动完成, 还没想好如何优化
+                swipe_down = isinstance(result, int) and result > 0
+                swipe_distance_ratio = 1
+            if not result:
+                return False
+            if isinstance(result, tuple):
+                return result
+            if swipe_distance_ratio:
+                x1, y1, x2, y2 = target.swipe_pos(number=swipe_distance_ratio, after=swipe_down)
+            else:
+                x1, y1, x2, y2 = target.swipe_pos(after=swipe_down)
+            self.device.swipe(p1=(x1, y1), p2=(x2, y2))
+            sleep(random.uniform(0.8, 1.3))  # 等待滑动完成, 待优化
 
     def list_appear_click(self, target: RuleList) -> bool:
         appear = self.list_find(target, name=target.array[0])