Explorar el Código

feat: climb act

Azure hace 1 año
padre
commit
0e3e4c7795

+ 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"
   },
   {

+ 2 - 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": "还未上锁图片"

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

@@ -61,5 +61,32 @@
     "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体活动标识"
+  },
+  {
+    "itemName": "check_ap100",
+    "roiFront": "89,12,128,44",
+    "roiBack": "67,0,166,69",
+    "mode": "Single",
+    "method": "Default",
+    "keyword": "将魂试炼",
+    "description": "100体活动界面标识"
   }
 ]

+ 14 - 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=(1182,652,73,32), roi_back=(1141,627,135,81), threshold=0.8, method="Template matching", file="./tasks/ActivityShikigami/as/as_check_ap100.png")
 
 
 	# Ocr Rule Assets
@@ -135,5 +137,11 @@ 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")
+	# 100体活动界面标识 
+	O_CHECK_AP100 = RuleOcr(roi=(89,12,128,44), area=(67,0,166,69), mode="Single", method="Default", keyword="将魂试炼", name="check_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

+ 119 - 115
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,70 +77,41 @@ 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)
+                self.switch_soul(self.conf.switch_soul_config)
                 continue
             match current_page:
                 # 庭院, 进入活动主界面
@@ -159,13 +123,12 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
                     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.lock_team(self.conf.general_battle)
+                    self.check_tickets_enough()
                     self.start_battle()
                 case _:
                     if self.check(Status.GOTO_ACT_FAILED):
@@ -174,29 +137,42 @@ class ScriptTask(GameUi, BaseActivity, SwitchSoul, ActivityShikigamiAssets):
                         continue
                     self.put_check(Status.GOTO_ACT_FAILED, True)
                     # 任何活动界面都没有识别到, 尝试主动前往爬塔活动
-                    self.goto_act()
+                    self.goto_act(timeout=15)
         # 返回庭院
         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
         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 +180,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(0.6, 1.2))
             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 +235,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 +320,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 +340,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 +359,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 +378,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 +422,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=25)
+    def goto_act(self, timeout: int = 25):
+        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 +440,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):

+ 5 - 5
tasks/GameUi/game_ui.py

@@ -37,9 +37,9 @@ 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,
@@ -232,7 +232,7 @@ class GameUi(BaseTask, GameUiAssets):
             if self.ui_page_appear(destination):
                 if confirm_timer.reached():
                     logger.info(f'Page arrive: {destination}')
-                    break
+                    return True
                 confirm_timer.reset()
                 continue
             # 尝试关闭未知页面
@@ -278,8 +278,8 @@ class GameUi(BaseTask, GameUiAssets):
                             self.appear_then_click(button, interval=0.6) or
                             (isinstance(button, RuleOcr) and self.ocr_appear_click(button, interval=2))):
                         logger.info(f'Page {current_page} additional {button} clicked')
-                        # 每次点击之间添加随机延迟, 等待响应
-                        sleep(random.uniform(0.2, 0.6))
+                    # 每次都随机延迟, 等待响应
+                    sleep(random.uniform(0.4, 0.8))
             # 执行页面跳转
             button = current_page.links.get(next_page)
             if not button:

+ 10 - 2
tasks/GameUi/page.py

@@ -217,6 +217,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.O_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]
@@ -249,10 +253,14 @@ 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(1, 3)
+# 失败界面
+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()})