Эх сурвалжийг харах

feat(kekkai): 结界蹭卡识别卡收益进行蹭卡

ljxun 1 жил өмнө
parent
commit
2f4716ff43

+ 19 - 0
module/atom/image_grid.py

@@ -24,4 +24,23 @@ class ImageGrid:
                 return image
                 return image
         return None
         return None
 
 
+    def find_everyone(self, img: np.array) -> list or None:
+        """
+        自下而上查找所有匹配项,返回带对应image对象的排序结果
+        :param img: 待匹配图像
+        :return: 排序后的列表,每个元素为(image对象, (x, y, w, h)),无匹配返回None
+        """
+        matched = []
+        # 收集匹配结果时保留来源image
+        for image in self.images:
+            matches = image.match_all_any(img, threshold=0.8, nms_threshold=0.3)
+            for (score, x, y, w, h) in matches:
+                matched.append( (image, score, (x, y, w, h)) )
+
+        # 按y坐标升序排列(屏幕坐标系从上到下)
+        sorted_results = sorted(
+            matched,
+            key=lambda item: item[2][1]  # item[1]是坐标元组,取y值
+        )
 
 
+        return sorted_results if sorted_results else None

+ 36 - 13
tasks/KekkaiUtilize/assets.py

@@ -20,11 +20,15 @@ class KekkaiUtilizeAssets:
 	# 神灶 
 	# 神灶 
 	I_GUILD_SHIRNE = RuleImage(roi_front=(872,624,60,62), roi_back=(872,624,60,62), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_shirne.png")
 	I_GUILD_SHIRNE = RuleImage(roi_front=(872,624,60,62), roi_back=(872,624,60,62), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_shirne.png")
 	# 寮体力 
 	# 寮体力 
-	I_GUILD_AP = RuleImage(roi_front=(483,314,22,22), roi_back=(290,224,393,218), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_ap.png")
+	I_GUILD_AP = RuleImage(roi_front=(483,314,22,22), roi_back=(1,134,582,363), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_ap.png")
 	# 寮资金 
 	# 寮资金 
-	I_GUILD_ASSETS = RuleImage(roi_front=(315,311,23,28), roi_back=(290,224,393,218), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_assets.png")
+	I_GUILD_ASSETS = RuleImage(roi_front=(315,311,23,28), roi_back=(1,134,782,363), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_assets.png")
 	# 领取寮资金 
 	# 领取寮资金 
 	I_GUILD_ASSETS_RECEIVE = RuleImage(roi_front=(565,426,144,63), roi_back=(565,426,144,63), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_assets_receive.png")
 	I_GUILD_ASSETS_RECEIVE = RuleImage(roi_front=(565,426,144,63), roi_back=(565,426,144,63), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_assets_receive.png")
+	# 收起的寮活动横幅 
+	I_GUILD_COLLAPSE = RuleImage(roi_front=(28,159,19,22), roi_back=(12,125,88,101), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_collapse.png")
+	# 展开的寮活动横幅 
+	I_GUILD_EXPAND = RuleImage(roi_front=(264,162,16,18), roi_back=(212,102,110,124), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/ku/ku_guild_expand.png")
 
 
 
 
 	# Swipe Rule Assets
 	# Swipe Rule Assets
@@ -34,9 +38,9 @@ class KekkaiUtilizeAssets:
 
 
 	# Image Rule Assets
 	# Image Rule Assets
 	# 育成 
 	# 育成 
-	I_SHI_GROWN = RuleImage(roi_front=(595,291,35,38), roi_back=(530,254,181,198), threshold=0.7, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_shi_grown.png")
+	I_SHI_GROWN = RuleImage(roi_front=(595,291,35,38), roi_back=(530,254,181,198), threshold=0.6, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_shi_grown.png")
 	# 结界卡 
 	# 结界卡 
-	I_SHI_CARD = RuleImage(roi_front=(886,290,38,56), roi_back=(870,276,75,86), threshold=0.7, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_shi_card.png")
+	I_SHI_CARD = RuleImage(roi_front=(886,290,38,56), roi_back=(870,276,75,86), threshold=0.6, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_shi_card.png")
 	# description 
 	# description 
 	I_SHI_DEFENSE = RuleImage(roi_front=(294,298,49,56), roi_back=(215,207,208,221), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_shi_defense.png")
 	I_SHI_DEFENSE = RuleImage(roi_front=(294,298,49,56), roi_back=(215,207,208,221), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_shi_defense.png")
 	# 收取经验(没有满的图) 
 	# 收取经验(没有满的图) 
@@ -57,6 +61,19 @@ class KekkaiUtilizeAssets:
 	I_BOX_EXP_MAX = RuleImage(roi_front=(889,430,61,64), roi_back=(829,372,228,186), threshold=0.7, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_box_exp_max.png")
 	I_BOX_EXP_MAX = RuleImage(roi_front=(889,430,61,64), roi_back=(829,372,228,186), threshold=0.7, method="Template matching", file="./tasks/KekkaiUtilize/realm/realm_box_exp_max.png")
 
 
 
 
+	# Click Rule Assets
+	# 选择结界区域1 
+	C_SELECT_REALM_1 = RuleClick(roi_front=(300,200,200,50), roi_back=(300,200,200,50), name="select_realm_1")
+	# 选择结界区域2 
+	C_SELECT_REALM_2 = RuleClick(roi_front=(300,307,200,50), roi_back=(300,307,200,50), name="select_realm_2")
+	# 选择结界区域3 
+	C_SELECT_REALM_3 = RuleClick(roi_front=(300,415,200,50), roi_back=(300,415,200,50), name="select_realm_3")
+	# 选择结界区域4 
+	C_SELECT_REALM_4 = RuleClick(roi_front=(300,520,200,50), roi_back=(300,520,200,50), name="select_realm_4")
+	# 点击识别到的卡(用识别到的坐标填充作用) 
+	C_SELECT_CARD = RuleClick(roi_front=(0,0,0,0), roi_back=(0,0,0,0), name="select_card")
+
+
 	# Image Rule Assets
 	# Image Rule Assets
 	# 右上角的放置好友寄养 
 	# 右上角的放置好友寄养 
 	I_UTILIZE_ADD = RuleImage(roi_front=(1149,54,74,67), roi_back=(1149,54,74,67), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_utilize_add.png")
 	I_UTILIZE_ADD = RuleImage(roi_front=(1149,54,74,67), roi_back=(1149,54,74,67), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_utilize_add.png")
@@ -69,17 +86,17 @@ class KekkaiUtilizeAssets:
 	# description 
 	# description 
 	I_U_TAIKO_4 = RuleImage(roi_front=(543,316,60,43), roi_back=(541,171,73,438), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_taiko_4.png")
 	I_U_TAIKO_4 = RuleImage(roi_front=(543,316,60,43), roi_back=(541,171,73,438), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_taiko_4.png")
 	# description 
 	# description 
-	I_U_TAIKO_5 = RuleImage(roi_front=(544,201,59,52), roi_back=(538,179,79,426), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_taiko_5.png")
+	I_U_TAIKO_5 = RuleImage(roi_front=(543,201,62,54), roi_back=(538,179,79,426), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_taiko_5.png")
 	# description 
 	# description 
-	I_U_TAIKO_6 = RuleImage(roi_front=(545,313,60,45), roi_back=(533,156,87,450), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_taiko_6.png")
+	I_U_TAIKO_6 = RuleImage(roi_front=(543,521,62,54), roi_back=(533,156,87,450), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_taiko_6.png")
 	# description 
 	# description 
 	I_U_FISH_3 = RuleImage(roi_front=(552,216,41,33), roi_back=(543,178,69,412), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_3.png")
 	I_U_FISH_3 = RuleImage(roi_front=(552,216,41,33), roi_back=(543,178,69,412), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_3.png")
 	# description 
 	# description 
 	I_U_FISH_4 = RuleImage(roi_front=(549,310,51,50), roi_back=(542,177,73,401), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_4.png")
 	I_U_FISH_4 = RuleImage(roi_front=(549,310,51,50), roi_back=(542,177,73,401), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_4.png")
 	# description 
 	# description 
-	I_U_FISH_5 = RuleImage(roi_front=(552,529,45,41), roi_back=(541,183,71,403), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_5.png")
+	I_U_FISH_5 = RuleImage(roi_front=(543,412,62,54), roi_back=(541,183,71,403), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_5.png")
 	# description 
 	# description 
-	I_U_FISH_6 = RuleImage(roi_front=(544,201,59,52), roi_back=(530,184,82,416), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_6.png")
+	I_U_FISH_6 = RuleImage(roi_front=(542,197,62,54), roi_back=(530,184,82,416), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_fish_6.png")
 	# 进入结界 
 	# 进入结界 
 	I_U_ENTER_REALM = RuleImage(roi_front=(792,531,178,67), roi_back=(792,531,178,67), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_enter_realm.png")
 	I_U_ENTER_REALM = RuleImage(roi_front=(792,531,178,67), roi_back=(792,531,178,67), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_enter_realm.png")
 	# 右侧大的图片 
 	# 右侧大的图片 
@@ -96,6 +113,14 @@ class KekkaiUtilizeAssets:
 	I_U_ADD_2 = RuleImage(roi_front=(979,52,76,69), roi_back=(979,52,76,69), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_add_2.png")
 	I_U_ADD_2 = RuleImage(roi_front=(979,52,76,69), roi_back=(979,52,76,69), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_add_2.png")
 	# description 
 	# description 
 	I_U_CONFIRM_SMALL = RuleImage(roi_front=(672,513,131,60), roi_back=(672,513,131,60), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_confirm_small.png")
 	I_U_CONFIRM_SMALL = RuleImage(roi_front=(672,513,131,60), roi_back=(672,513,131,60), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/utilize_u_confirm_small.png")
+	# description 
+	I_SELECT_REALM_ON_1 = RuleImage(roi_front=(608,191,21,59), roi_back=(608,191,21,59), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/select_realm_on_1.png")
+	# description 
+	I_SELECT_REALM_ON_2 = RuleImage(roi_front=(606,298,21,59), roi_back=(606,298,21,59), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/select_realm_on_2.png")
+	# description 
+	I_SELECT_REALM_ON_3 = RuleImage(roi_front=(607,404,21,59), roi_back=(607,404,21,59), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/select_realm_on_3.png")
+	# description 
+	I_SELECT_REALM_ON_4 = RuleImage(roi_front=(607,516,21,59), roi_back=(607,516,21,59), threshold=0.8, method="Template matching", file="./tasks/KekkaiUtilize/utilize/select_realm_on_4.png")
 
 
 
 
 	# Image Rule Assets
 	# Image Rule Assets
@@ -122,15 +147,13 @@ class KekkaiUtilizeAssets:
 	O_UTILIZE_RES_TIME = RuleOcr(roi=(1140,117,100,30), area=(1140,117,100,30), mode="Duration", method="Default", keyword="", name="utilize_res_time")
 	O_UTILIZE_RES_TIME = RuleOcr(roi=(1140,117,100,30), area=(1140,117,100,30), mode="Duration", method="Default", keyword="", name="utilize_res_time")
 	# 今日已领取经验 
 	# 今日已领取经验 
 	O_BOX_EXP = RuleOcr(roi=(654,538,179,39), area=(654,538,179,39), mode="DigitCounter", method="Default", keyword="", name="box_exp")
 	O_BOX_EXP = RuleOcr(roi=(654,538,179,39), area=(654,538,179,39), mode="DigitCounter", method="Default", keyword="", name="box_exp")
-	# 今日已领取经验(招财上宾) 
-	O_BOX_EXP_ZCSB = RuleOcr(roi=(584,542,181,35), area=(584,542,181,35), mode="DigitCounter", method="Default", keyword="", name="box_exp_zcsb")
-	# Ocr-description 
-	O_UTILIZE_F_LIST = RuleOcr(roi=(307,171,213,416), area=(307,171,213,416), mode="Full", method="Default", keyword="", name="utilize_f_list")
+	# 斗鱼或太古寄养数目 
+	O_CARD_NUM = RuleOcr(roi=(800,421,150,33), area=(800,421,150,33), mode="Single", method="Default", keyword="", name="card_num")
 
 
 
 
 	# Swipe Rule Assets
 	# Swipe Rule Assets
 	# 向下滑动 
 	# 向下滑动 
-	S_U_UP = RuleSwipe(roi_front=(237,349,50,21), roi_back=(225,177,72,21), mode="default", name="u_up")
+	S_U_UP = RuleSwipe(roi_front=(247,520,100,1), roi_back=(247,104,100,1), mode="default", name="u_up")
 	# 滑动到底部 
 	# 滑动到底部 
 	S_U_END = RuleSwipe(roi_front=(175,179,26,26), roi_back=(164,518,49,102), mode="default", name="u_end")
 	S_U_END = RuleSwipe(roi_front=(175,179,26,26), roi_back=(164,518,49,102), mode="default", name="u_end")
 
 

+ 3 - 4
tasks/KekkaiUtilize/config.py

@@ -17,22 +17,21 @@ class UtilizeRule(str, Enum):
     DEFAULT = 'default'  # 默认就好
     DEFAULT = 'default'  # 默认就好
     TAIKO = 'kaiko'  # 太鼓优先
     TAIKO = 'kaiko'  # 太鼓优先
     FISH = 'fish'  # 斗鱼优先
     FISH = 'fish'  # 斗鱼优先
-    AUTO = 'auto'  # 自动 兼容代码罢了
-    FRIEND = 'friend'  # 好友选定
+    # AUTO = 'auto'  # 自动 兼容代码罢了
 
 
 
 
 
 
 class UtilizeScheduler(Scheduler):
 class UtilizeScheduler(Scheduler):
-    priority: int = Field(default=2, description='priority_help')
+    priority = Field(default=2, description='priority_help')
     success_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='success_interval_help')
     success_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='success_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='failure_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='failure_interval_help')
 
 
 class UtilizeConfig(BaseModel):
 class UtilizeConfig(BaseModel):
     utilize_rule: UtilizeRule = Field(default=UtilizeRule.DEFAULT, description='utilize_rule_help')
     utilize_rule: UtilizeRule = Field(default=UtilizeRule.DEFAULT, description='utilize_rule_help')
-    utilize_friend: str = Field(default= '',description='你要指定的好友的名字,需要选择同区好友还是跨区好友(就是下面那个选项)')
     select_friend_list: SelectFriendList = Field(default=SelectFriendList.SAME_SERVER, description='select_friend_list_help')
     select_friend_list: SelectFriendList = Field(default=SelectFriendList.SAME_SERVER, description='select_friend_list_help')
     shikigami_class: ShikigamiClass = Field(default=ShikigamiClass.N, description='shikigami_class_help')
     shikigami_class: ShikigamiClass = Field(default=ShikigamiClass.N, description='shikigami_class_help')
     shikigami_order: int = Field(default=4, description='shikigami_order_help')
     shikigami_order: int = Field(default=4, description='shikigami_order_help')
+    utilize_enable: bool = Field(default=True, description='是否蹭卡,小号可以选择不蹭卡')
     guild_ap_enable: bool = Field(default=True, description='guild_ap_enable_help')
     guild_ap_enable: bool = Field(default=True, description='guild_ap_enable_help')
     guild_assets_enable: bool = Field(default=True, description='guild_assets_enable_help')
     guild_assets_enable: bool = Field(default=True, description='guild_assets_enable_help')
     box_ap_enable: bool = Field(default=True, description='box_ap_enable_help')
     box_ap_enable: bool = Field(default=True, description='box_ap_enable_help')

+ 20 - 2
tasks/KekkaiUtilize/ku/image.json

@@ -39,7 +39,7 @@
     "itemName": "guild_ap",
     "itemName": "guild_ap",
     "imageName": "ku_guild_ap.png",
     "imageName": "ku_guild_ap.png",
     "roiFront": "483,314,22,22",
     "roiFront": "483,314,22,22",
-    "roiBack": "290,224,393,218",
+    "roiBack": "1,134,582,363",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "寮体力"
     "description": "寮体力"
@@ -48,7 +48,7 @@
     "itemName": "guild_assets",
     "itemName": "guild_assets",
     "imageName": "ku_guild_assets.png",
     "imageName": "ku_guild_assets.png",
     "roiFront": "315,311,23,28",
     "roiFront": "315,311,23,28",
-    "roiBack": "290,224,393,218",
+    "roiBack": "1,134,782,363",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "寮资金"
     "description": "寮资金"
@@ -61,5 +61,23 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "领取寮资金"
     "description": "领取寮资金"
+  },
+  {
+    "itemName": "guild_collapse",
+    "imageName": "ku_guild_collapse.png",
+    "roiFront": "28,159,19,22",
+    "roiBack": "12,125,88,101",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "收起的寮活动横幅"
+  },
+  {
+    "itemName": "guild_expand",
+    "imageName": "ku_guild_expand.png",
+    "roiFront": "264,162,16,18",
+    "roiBack": "212,102,110,124",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "展开的寮活动横幅"
   }
   }
 ]
 ]

BIN
tasks/KekkaiUtilize/ku/ku_guild_collapse.png


BIN
tasks/KekkaiUtilize/ku/ku_guild_expand.png


+ 2 - 2
tasks/KekkaiUtilize/realm/image.json

@@ -5,7 +5,7 @@
     "roiFront": "595,291,35,38",
     "roiFront": "595,291,35,38",
     "roiBack": "530,254,181,198",
     "roiBack": "530,254,181,198",
     "method": "Template matching",
     "method": "Template matching",
-    "threshold": 0.7,
+    "threshold": 0.6,
     "description": "育成"
     "description": "育成"
   },
   },
   {
   {
@@ -14,7 +14,7 @@
     "roiFront": "886,290,38,56",
     "roiFront": "886,290,38,56",
     "roiBack": "870,276,75,86",
     "roiBack": "870,276,75,86",
     "method": "Template matching",
     "method": "Template matching",
-    "threshold": 0.7,
+    "threshold": 0.6,
     "description": "结界卡"
     "description": "结界卡"
   },
   },
   {
   {

+ 399 - 241
tasks/KekkaiUtilize/script_task.py

@@ -1,6 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
+import re
 import time
 import time
 from cached_property import cached_property
 from cached_property import cached_property
 from datetime import timedelta, datetime
 from datetime import timedelta, datetime
@@ -8,10 +9,7 @@ from datetime import timedelta, datetime
 from module.base.timer import Timer
 from module.base.timer import Timer
 from module.atom.image_grid import ImageGrid
 from module.atom.image_grid import ImageGrid
 from module.logger import logger
 from module.logger import logger
-
-from module.exception import TaskEnd, GameStuckError
-from ppocronnx.predict_system import BoxedResult
-
+from module.exception import TaskEnd
 
 
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.game_ui import GameUi
 from tasks.Utils.config_enum import ShikigamiClass
 from tasks.Utils.config_enum import ShikigamiClass
@@ -20,54 +18,124 @@ from tasks.KekkaiUtilize.config import UtilizeRule, SelectFriendList
 from tasks.KekkaiUtilize.utils import CardClass, target_to_card_class
 from tasks.KekkaiUtilize.utils import CardClass, target_to_card_class
 from tasks.Component.ReplaceShikigami.replace_shikigami import ReplaceShikigami
 from tasks.Component.ReplaceShikigami.replace_shikigami import ReplaceShikigami
 from tasks.GameUi.page import page_main, page_guild
 from tasks.GameUi.page import page_main, page_guild
+from module.base.utils import point2str
+import random
+
+""" 结界蹭卡 """
 
 
 
 
 class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
 class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
+    last_best_index = 99
+    utilize_add_count = 0
+    ap_max_num = 0
+    jade_max_num = 0
+    first_utilize = True
 
 
     def run(self):
     def run(self):
         con = self.config.kekkai_utilize.utilize_config
         con = self.config.kekkai_utilize.utilize_config
         self.ui_get_current_page()
         self.ui_get_current_page()
         self.ui_goto(page_guild)
         self.ui_goto(page_guild)
-        # 收体力或者资金
-        # 进入寮主页会有一个动画,等一等,让小纸人跑一会儿
-        time.sleep(3)
-        self.check_guild_ap_or_assets(ap_enable=con.guild_ap_enable, assets_enable=con.guild_assets_enable)
+
         # 进入寮结界
         # 进入寮结界
         self.goto_realm()
         self.goto_realm()
-        # 顺带收体力盒子或者是经验盒子
-        time.sleep(1)
-        self.check_box_ap_or_exp(con.box_ap_enable, con.box_exp_enable, con.box_exp_waste)
+        # 育成界面去蹭卡
+        if con.utilize_enable:
+            self.check_utilize_add()
 
 
-        # 收菜看看
+        # 查看育成满级
+        self.check_max_lv(con.shikigami_class)
+        # 检查蹭卡收获
         self.check_utilize_harvest()
         self.check_utilize_harvest()
+        # 收体力盒子或者是经验盒子
+        self.check_box_ap_or_exp(con.box_ap_enable, con.box_exp_enable, con.box_exp_waste)
+
+        # 收取寮资金和体力
+        self.recive_guild_ap_or_assets()
+        if not con.utilize_enable:
+            self.set_next_run(task='KekkaiUtilize', finish=True, success=True)
+        raise TaskEnd
+
+    def recive_guild_ap_or_assets(self):
+        for i in range(1, 5):
+            self.ui_get_current_page()
+            self.ui_goto(page_guild)
+            # 在寮的主界面 检查是否有收取体力或者是收取寮资金
+            if self.check_guild_ap_or_assets():
+                logger.warning(f'第[{i}]次检查寮收获,成功')
+                self.ui_goto(page_main)
+                break
+            else:
+                logger.warning(f'第[{i}]次检查寮收获寮收获,失败')
+            self.ui_goto(page_main)
+
+    def check_utilize_add(self):
+        con = self.config.kekkai_utilize.utilize_config
+        while 1:
+            self.utilize_add_count += 1
+            if self.utilize_add_count >= 5:
+                logger.warning('没有合适可以蹭的卡, 5分钟后再次执行蹭卡')
+                self.push_notify(content=f"没有合适可以蹭的卡, 5分钟后再次执行蹭卡")
+                self.set_next_run(task='KekkaiUtilize', target=datetime.now() + timedelta(minutes=5))
+                return
+
+            # 无论收不收到菜,都会进入看看至少看一眼时间还剩多少
+            time.sleep(0.5)
+            # 进入育成界面
+            self.realm_goto_grown()
+            self.screenshot()
+
+            if not self.appear(self.I_UTILIZE_ADD):
+                remaining_time = self.O_UTILIZE_RES_TIME.ocr(self.device.image)
+                if not isinstance(remaining_time, timedelta):
+                    logger.warning('Ocr remaining time error')
+                logger.info(f'Utilize remaining time: {remaining_time}')
+                # 已经蹭上卡了,设置下次蹭卡时间  # 减少30秒
+                # remaining_time = remaining_time - timedelta(seconds=30)
+                next_time = datetime.now() + remaining_time
+                self.set_next_run(task='KekkaiUtilize', target=next_time)
+                return
+            if not self.grown_goto_utilize():
+                logger.info('Utilize failed, exit')
+            # 开始执行寄养
+            if self.run_utilize(con.select_friend_list, con.shikigami_class, con.shikigami_order):
+                # 退出寮结界
+                self.back_guild()
+                # 进入寮结界
+                self.goto_realm()
+            else:
+                self.back_realm()
+
+    def check_max_lv(self, shikigami_class: ShikigamiClass = ShikigamiClass.N):
+        """
+        在结界界面,进入式神育成,检查是否有满级的,如果有就换下一个
+        退出的时候还是结界界面
+        :return:
+        """
         self.realm_goto_grown()
         self.realm_goto_grown()
-        # 无论收不收到菜,都会进入看看至少看一眼时间还剩多少
-        self.screenshot()
-        if not self.appear(self.I_UTILIZE_ADD):
-            remaining_time = self.O_UTILIZE_RES_TIME.ocr(self.device.image)
-            if not isinstance(remaining_time, timedelta):
-                logger.warning('Ocr remaining time error')
-            logger.info(f'Utilize remaining time: {remaining_time}')
-            # 执行失败,推出下一次执行为失败的时间间隔
-            logger.info('Utilize failed, exit')
-            self.back_guild()
-            next_time = datetime.now() + remaining_time
-            self.set_next_run(task='KekkaiUtilize', success=False, finish=True, target=next_time)
-            raise TaskEnd
-        if not self.grown_goto_utilize():
-            logger.info('Utilize failed, exit')
-        success = self.run_utilize(con.select_friend_list, con.shikigami_class, con.shikigami_order)
-        self.back_guild()
-        if success:
-            self.set_next_run(task='KekkaiUtilize', success=True, finish=True)
+        if self.appear(self.I_RS_LEVEL_MAX):
+            # 存在满级的式神
+            logger.info('Exist max level shikigami and replace it')
+            self.unset_shikigami_max_lv()
+            self.switch_shikigami_class(shikigami_class)
+            self.set_shikigami(shikigami_order=7, stop_image=self.I_RS_NO_ADD)
         else:
         else:
-            self.set_next_run(
-                task='KekkaiUtilize',
-                success=False,
-                finish=False,
-                target=datetime.now() + timedelta(minutes=5)
-            )
-        raise TaskEnd
+            logger.info('No max level shikigami')
+        if self.detect_no_shikigami():
+            logger.warning('There are no any shikigami grow room')
+            self.switch_shikigami_class(shikigami_class)
+            self.set_shikigami(shikigami_order=7, stop_image=self.I_RS_NO_ADD)
+
+        # 回到结界界面
+        while 1:
+            self.screenshot()
+
+            if self.appear(self.I_REALM_SHIN) and self.appear(self.I_SHI_GROWN):
+                self.screenshot()
+                if not self.appear(self.I_REALM_SHIN):
+                    continue
+                break
+            if self.appear_then_click(self.I_UI_BACK_BLUE, interval=2.5):
+                continue
 
 
     def check_guild_ap_or_assets(self, ap_enable: bool = True, assets_enable: bool = True) -> bool:
     def check_guild_ap_or_assets(self, ap_enable: bool = True, assets_enable: bool = True) -> bool:
         """
         """
@@ -75,53 +143,49 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
         如果有就顺带收取
         如果有就顺带收取
         :return:
         :return:
         """
         """
-        if ap_enable or assets_enable:
-            # 尝试移动寻找体力或资金
-            try_find_ap = 0
-            while try_find_ap < 3:
-                self.screenshot()
-                try_find_ap += 1
-                if self.appear(self.I_GUILD_AP) or self.appear(self.I_GUILD_ASSETS):
-                    logger.info('Find ap or assets')
-                    break
-                else:
-                    logger.info('Try find ap or assets')
-                    self.swipe(self.S_GUILD_FIND_AP)
-            # 如果未找到则返回False
-            if not self.appear(self.I_GUILD_AP) and not self.appear(self.I_GUILD_ASSETS):
-                logger.info('No ap or assets to collect')
-                return False
-        else:
-            return False
-
-        # 如果有就收取
         timer_check = Timer(2)
         timer_check = Timer(2)
         timer_check.start()
         timer_check.start()
+        click_ap = False
         while 1:
         while 1:
             self.screenshot()
             self.screenshot()
 
 
             # 获得奖励
             # 获得奖励
             if self.ui_reward_appear_click():
             if self.ui_reward_appear_click():
                 timer_check.reset()
                 timer_check.reset()
+                continue
 
 
-            # 资金收取确认
-            if self.appear_then_click(self.I_GUILD_ASSETS_RECEIVE, interval=0.5):
+            if timer_check.reached():
+                return False
+
+            if click_ap and not self.appear(self.I_GUILD_AP) and not self.appear(self.I_UI_REWARD):
+                return True
+
+            # 关闭展开的寮活动横幅
+            if self.appear_then_click(self.I_GUILD_EXPAND):
                 timer_check.reset()
                 timer_check.reset()
                 continue
                 continue
 
 
-            # 收体力
-            if self.appear_then_click(self.I_GUILD_AP, interval=1.5):
+            # 资金收取确认
+            if self.appear_then_click(self.I_GUILD_ASSETS_RECEIVE, interval=1):
+                time.sleep(1)
                 timer_check.reset()
                 timer_check.reset()
                 continue
                 continue
+
             # 收资金
             # 收资金
             if self.appear_then_click(self.I_GUILD_ASSETS, interval=1.5, threshold=0.6):
             if self.appear_then_click(self.I_GUILD_ASSETS, interval=1.5, threshold=0.6):
                 timer_check.reset()
                 timer_check.reset()
                 continue
                 continue
 
 
-            if timer_check.reached():
-                break
-        logger.info('Collect ap or assets success')
-        return True
+            # 收体力
+            if self.appear_then_click(self.I_GUILD_AP, interval=1):
+                # 等待1秒,看到获得奖励
+                time.sleep(1)
+                logger.info('appear_click guild_ap success')
+                if self.ui_reward_appear_click(True):
+                    logger.info('appear_click reward success')
+                    click_ap = True
+                    timer_check.reset()
+                continue
 
 
     def goto_realm(self):
     def goto_realm(self):
         """
         """
@@ -220,12 +284,9 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
                 if self.appear(self.I_EXP_EXTRACT):
                 if self.appear(self.I_EXP_EXTRACT):
                     # 如果达到今日领取的最大,就不领取了
                     # 如果达到今日领取的最大,就不领取了
                     cur, res, totol = self.O_BOX_EXP.ocr(self.device.image)
                     cur, res, totol = self.O_BOX_EXP.ocr(self.device.image)
-                    if cur != 0 and totol != 0 and cur == totol and cur + res == totol:
-                        logger.info('Exp box reach max do not collect')
-                        break
-                    # 开启招财上宾后,上限增加20%,数值位置有偏移
-                    cur, res, totol = self.O_BOX_EXP_ZCSB.ocr(self.device.image)
-                    if cur != 0 and totol != 0 and cur == totol * 1.2 and cur + res == totol:
+                    if cur == res == totol == 0:
+                        continue
+                    if cur == totol and cur + res == totol:
                         logger.info('Exp box reach max do not collect')
                         logger.info('Exp box reach max do not collect')
                         break
                         break
                 if self.appear_then_click(self.I_BOX_EXP, threshold=0.6, interval=1):
                 if self.appear_then_click(self.I_BOX_EXP, threshold=0.6, interval=1):
@@ -326,14 +387,11 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
     def order_targets(self) -> ImageGrid:
     def order_targets(self) -> ImageGrid:
         rule = self.config.kekkai_utilize.utilize_config.utilize_rule
         rule = self.config.kekkai_utilize.utilize_config.utilize_rule
         if rule == UtilizeRule.DEFAULT:
         if rule == UtilizeRule.DEFAULT:
-            return ImageGrid([self.I_U_TAIKO_6, self.I_U_FISH_6, self.I_U_TAIKO_5, self.I_U_FISH_5,
-                              self.I_U_TAIKO_4, self.I_U_FISH_4, self.I_U_TAIKO_3, self.I_U_FISH_3])
+            return ImageGrid([self.I_U_FISH_6, self.I_U_TAIKO_6, self.I_U_FISH_5, self.I_U_TAIKO_5])
         elif rule == UtilizeRule.FISH:
         elif rule == UtilizeRule.FISH:
-            return ImageGrid([self.I_U_FISH_6, self.I_U_FISH_5, self.I_U_FISH_4, self.I_U_FISH_3,
-                              self.I_U_TAIKO_6, self.I_U_TAIKO_5, self.I_U_TAIKO_4, self.I_U_TAIKO_3])
+            return ImageGrid([self.I_U_FISH_6, self.I_U_FISH_5])
         elif rule == UtilizeRule.TAIKO:
         elif rule == UtilizeRule.TAIKO:
-            return ImageGrid([self.I_U_TAIKO_6, self.I_U_TAIKO_5, self.I_U_TAIKO_4, self.I_U_TAIKO_3,
-                              self.I_U_FISH_6, self.I_U_FISH_5, self.I_U_FISH_4, self.I_U_FISH_3])
+            return ImageGrid([self.I_U_TAIKO_6, self.I_U_TAIKO_5])
         else:
         else:
             logger.error('Unknown utilize rule')
             logger.error('Unknown utilize rule')
             raise ValueError('Unknown utilize rule')
             raise ValueError('Unknown utilize rule')
@@ -343,14 +401,16 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
         rule = self.config.kekkai_utilize.utilize_config.utilize_rule
         rule = self.config.kekkai_utilize.utilize_config.utilize_rule
         result = []
         result = []
         if rule == UtilizeRule.DEFAULT:
         if rule == UtilizeRule.DEFAULT:
-            result = [CardClass.TAIKO6, CardClass.FISH6, CardClass.TAIKO5, CardClass.FISH5,
+            result = [CardClass.FISH6, CardClass.TAIKO6, CardClass.FISH5, CardClass.TAIKO5,
                       CardClass.TAIKO4, CardClass.FISH4, CardClass.TAIKO3, CardClass.FISH3]
                       CardClass.TAIKO4, CardClass.FISH4, CardClass.TAIKO3, CardClass.FISH3]
         elif rule == UtilizeRule.FISH:
         elif rule == UtilizeRule.FISH:
-            result = [CardClass.FISH6, CardClass.FISH5, CardClass.FISH4, CardClass.FISH3,
-                      CardClass.TAIKO6, CardClass.TAIKO5, CardClass.TAIKO4, CardClass.TAIKO3]
+            result = [CardClass.FISH6, CardClass.FISH5,
+                      CardClass.TAIKO6, CardClass.TAIKO5, CardClass.FISH4, CardClass.TAIKO4, CardClass.FISH3,
+                      CardClass.TAIKO3]
         elif rule == UtilizeRule.TAIKO:
         elif rule == UtilizeRule.TAIKO:
-            result = [CardClass.TAIKO6, CardClass.TAIKO5, CardClass.TAIKO4, CardClass.TAIKO3,
-                      CardClass.FISH6, CardClass.FISH5, CardClass.FISH4, CardClass.FISH3]
+            result = [CardClass.TAIKO6, CardClass.TAIKO5,
+                      CardClass.FISH6, CardClass.FISH5, CardClass.TAIKO4, CardClass.FISH4, CardClass.TAIKO3,
+                      CardClass.FISH3]
         else:
         else:
             logger.error('Unknown utilize rule')
             logger.error('Unknown utilize rule')
             raise ValueError('Unknown utilize rule')
             raise ValueError('Unknown utilize rule')
@@ -358,7 +418,7 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
 
 
     def run_utilize(self, friend: SelectFriendList = SelectFriendList.SAME_SERVER,
     def run_utilize(self, friend: SelectFriendList = SelectFriendList.SAME_SERVER,
                     shikigami_class: ShikigamiClass = ShikigamiClass.N,
                     shikigami_class: ShikigamiClass = ShikigamiClass.N,
-                    shikigami_order: int = 7) -> bool:
+                    shikigami_order: int = 7):
         """
         """
         执行寄养
         执行寄养
         :param shikigami_class:
         :param shikigami_class:
@@ -366,125 +426,40 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
         :param rule:
         :param rule:
         :return:
         :return:
         """
         """
-        def _current_select_best(last_best: CardClass or None) -> CardClass | None:
-            """
-            当前选中的最好的卡,(会自动和记录的最好的比较)
-            包括点击这种卡
-            :return: 返回当前选中的最好的卡, 如果什么的都没有,返回None
-            """
-            self.screenshot()
-            target = self.order_targets.find_anyone(self.device.image)
-            if target is None:
-                logger.info('No target card found')
-                return None
-            card_class = target_to_card_class(target)
-            logger.info('Current find best card: %s', target)
-            # 如果当前的卡比记录的最好的卡还要好,那么就更新最好的卡
-            if last_best is not None:
-                last_index = self.order_cards.index(last_best)
-                current_index = self.order_cards.index(card_class)
-                if current_index >= last_index:
-                    # 不比上一张卡好就退出不执行操作,相同星级卡亦跳过
-                    logger.info('Current card is not better than last best card')
-                    return last_best
-            logger.info('Current select card: %s', card_class)
-
-            self.appear_then_click(target, interval=0.3)
-            # 验证这张卡 的等级是否一致
-            # while 1:
-            #     self.screenshot()
-            return card_class
-        def select_friend(friend_name: str) -> bool:
-            """
-            尝试在当前界面中识别并选择指定名称的好友
-            :param friend_name: 要选择的好友名称
-            :return: 成功选择返回True
-            """
-            logger.info(f"尝试选择好友: {friend_name}")
-            original_filter = self.O_UTILIZE_F_LIST.filter
-            try:
-                # 替换为自定义filter
-                self.O_UTILIZE_F_LIST.filter = self.filter
-                while 1:
-                    self.screenshot()
-                    self.O_UTILIZE_F_LIST.keyword = friend_name
-                    if self.ocr_appear_click(self.O_UTILIZE_F_LIST):
-                        logger.info(f"成功选择好友: {friend_name}")
-                        return True
-                    else:
-                        return False
-            finally:
-                # 恢复原始filter方法,防止副作用
-                self.O_UTILIZE_F_LIST.filter = original_filter
-
         logger.hr('Start utilize')
         logger.hr('Start utilize')
-        self.switch_friend_list(friend)
-        self.swipe(self.S_U_END, interval=3)
-        if friend == SelectFriendList.SAME_SERVER:
-            self.switch_friend_list(SelectFriendList.DIFFERENT_SERVER)
-            self.switch_friend_list(SelectFriendList.SAME_SERVER)
-        else:
-            self.switch_friend_list(SelectFriendList.SAME_SERVER)
-            self.switch_friend_list(SelectFriendList.DIFFERENT_SERVER)
-
-        rule = self.config.kekkai_utilize.utilize_config.utilize_rule
-        friend_name = self.config.kekkai_utilize.utilize_config.utilize_friend
-        if rule == UtilizeRule.FRIEND:
-            swipe_count = 0
-            while 1:
-                self.screenshot()
-                if select_friend(friend_name):
-                    break
-
-                # 超过十次就退出
-                if swipe_count > 10:
-                    logger.warning('Swipe count is more than 10')
-                    break
-
-                # 一直向下滑动
-                self.swipe(self.S_U_UP, interval=0.9)
-                swipe_count += 1
-                time.sleep(3)
-
+        if self.first_utilize:
+            self.swipe(self.S_U_END, interval=3)
+            self.first_utilize = False
+            if friend == SelectFriendList.SAME_SERVER:
+                self.switch_friend_list(SelectFriendList.DIFFERENT_SERVER)
+                self.switch_friend_list(SelectFriendList.SAME_SERVER)
+            else:
+                self.switch_friend_list(SelectFriendList.SAME_SERVER)
+                self.switch_friend_list(SelectFriendList.DIFFERENT_SERVER)
         else:
         else:
-            card_best = None
-            swipe_count = 0
-            while 1:
-                self.screenshot()
-                current_card = _current_select_best(card_best)
-
-                if current_card is None:
-                    break
-                else:
-                    card_best = current_card
-
-                # 超过十次就退出
-                if swipe_count > 10:
-                    logger.warning('Swipe count is more than 10')
-                    break
+            self.switch_friend_list(friend)
 
 
-                # 一直向下滑动
-                self.swipe(self.S_U_UP, interval=0.9)
-                swipe_count += 1
-                time.sleep(3)
-            # 最好的结界卡
-            logger.info('End best card is %s', card_best)
+        # --------------- 结界卡选择 ---------------
+        if not self._select_optimal_resource_card():
+            return False
 
 
-        # 进入结界
+        # 找到卡,重置次数
+        self.utilize_add_count = 0
+        logger.info('开始执行进入结界蹭卡流程')
         self.screenshot()
         self.screenshot()
+        # 进入结界
         if not self.appear(self.I_U_ENTER_REALM):
         if not self.appear(self.I_U_ENTER_REALM):
             logger.warning('Cannot find enter realm button')
             logger.warning('Cannot find enter realm button')
             # 可能是滑动的时候出错
             # 可能是滑动的时候出错
             logger.warning('The best reason is that the swipe is wrong')
             logger.warning('The best reason is that the swipe is wrong')
-            return False
-        TIMEOUT_SEC = 120          # 超时时长(秒)
-        start_time = time.time()   # 记录起始时间
+            return
+        wait_timer = Timer(20)
+        wait_timer.start()
         while 1:
         while 1:
-            # ——1. 先做超时检查——
-            if time.time() - start_time > TIMEOUT_SEC:
-                logger.error('寄养等待超过 2 分钟,自动退出')
-                raise GameStuckError('寄养超时(>120 s)')
             self.screenshot()
             self.screenshot()
+            if self.appear(self.I_U_ADD_1) or self.appear(self.I_U_ADD_2):
+                logger.info('Appear enter friend realm button')
+                break
             if self.appear(self.I_CHECK_FRIEND_REALM_1):
             if self.appear(self.I_CHECK_FRIEND_REALM_1):
                 self.wait_until_stable(self.I_CHECK_FRIEND_REALM_1)
                 self.wait_until_stable(self.I_CHECK_FRIEND_REALM_1)
                 logger.info('Appear enter friend realm button')
                 logger.info('Appear enter friend realm button')
@@ -493,7 +468,10 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
                 self.wait_until_stable(self.I_CHECK_FRIEND_REALM_3)
                 self.wait_until_stable(self.I_CHECK_FRIEND_REALM_3)
                 logger.info('Appear enter friend realm button')
                 logger.info('Appear enter friend realm button')
                 break
                 break
-
+            if wait_timer.reached():
+                self.save_image(wait_time=0, push_flag=False, content='进入好友结界超时', image_type='png')
+                logger.warning('Appear friend realm timeout')
+                return
             if self.appear_then_click(self.I_CHECK_FRIEND_REALM_2, interval=1.5):
             if self.appear_then_click(self.I_CHECK_FRIEND_REALM_2, interval=1.5):
                 logger.info('Click too fast to enter the friend\'s realm pool')
                 logger.info('Click too fast to enter the friend\'s realm pool')
                 continue
                 continue
@@ -502,67 +480,231 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
                 continue
                 continue
         logger.info('Enter friend realm')
         logger.info('Enter friend realm')
 
 
-        # 切换式神的类型
-        self.switch_shikigami_class(shikigami_class)
         # 判断好友的有两个位置还是一个坑位
         # 判断好友的有两个位置还是一个坑位
         stop_image = None
         stop_image = None
         self.screenshot()
         self.screenshot()
         if self.appear(self.I_U_ADD_1):  # 右侧第一个有(无论左侧有没有)
         if self.appear(self.I_U_ADD_1):  # 右侧第一个有(无论左侧有没有)
+            logger.info('Right side has one')
             stop_image = self.I_U_ADD_1
             stop_image = self.I_U_ADD_1
         elif self.appear(self.I_U_ADD_2) and not self.appear(self.I_U_ADD_1):  # 右侧第二个有 但是最左边的没有,这表示只留有一个坑位
         elif self.appear(self.I_U_ADD_2) and not self.appear(self.I_U_ADD_1):  # 右侧第二个有 但是最左边的没有,这表示只留有一个坑位
+            logger.info('Right side has two')
             stop_image = self.I_U_ADD_2
             stop_image = self.I_U_ADD_2
         if not stop_image:
         if not stop_image:
             # 没有坑位可能是其他人的手速太快了抢占了
             # 没有坑位可能是其他人的手速太快了抢占了
-            logger.warning('Cannot find stop image')
-            logger.warning('Maybe other people is faster than you')
-            return False
-
+            self.save_image(content='没有坑位了', wait_time=0, push_flag=False, image_type='png')
+            logger.warning('没有坑位可能是其他人的手速太快了抢占了')
+            return True
+        # 切换式神的类型
+        self.switch_shikigami_class(shikigami_class)
+        # 上式神
         self.set_shikigami(shikigami_order, stop_image)
         self.set_shikigami(shikigami_order, stop_image)
         return True
         return True
 
 
-    def filter(self, boxed_results: list[BoxedResult], keyword: str=None) -> list or None:
-        """
-        使用ocr获取结果后和keyword进行匹配. 返回匹配的index list
-        :param keyword: 如果不指定默认适用对象的keyword
-        :param boxed_results:
-        :return:
+    def _select_optimal_resource_card(self):
+        """整合后的智能选卡主逻辑(无嵌套函数版)"""
+        # 类常量声明(需在类中定义)
+        RESOURCE_PRESETS = {
+            '斗鱼': [151, 143, 134, 126, 101, 84],
+            '太鼓': [76,  76,  67,  67,  59,  50]
+        }
+        MAX_INDEX = 99
+
+        def get_resource_index(resource_name, current_value, preset_values):
+            """获取资源匹配的档位索引"""
+            for idx, val in enumerate(preset_values):
+                if current_value >= val:
+                    logger.info(f'📊 {resource_name}区间匹配: {current_value} ≥ {val} (档位{idx})')
+                    return idx
+            logger.warning(f'⚠️ {resource_name}值[{current_value}]低于所有预设')
+            return MAX_INDEX
+
+        while True:
+            self.screenshot()
+
+            # 第一阶段:初始记录获取
+            if self.ap_max_num == 0 and self.jade_max_num == 0:
+                logger.hr('第一阶段:初始记录获取', 2)
+                if self._current_select_best():
+                    logger.info(f'✅ 完美结界卡确认成功,重置状态')
+                    self.ap_max_num, self.jade_max_num = 0, 0
+                    return True
+                logger.info(f'📝 记录最佳值 | 斗鱼:{self.ap_max_num} 太鼓:{self.jade_max_num}')
+                return False
+
+            logger.hr('第二阶段:资源优先级判断', 2)
+            # 获取双资源档位
+            ap_index = get_resource_index('斗鱼', self.ap_max_num, RESOURCE_PRESETS['斗鱼'])
+            jade_index = get_resource_index('太鼓', self.jade_max_num, RESOURCE_PRESETS['太鼓'])
+
+            # 双资源超限处理
+            if ap_index == MAX_INDEX and jade_index == MAX_INDEX:
+                logger.warning('🔄 斗鱼和太鼓均低于预设,重置初始记录')
+                self.ap_max_num, self.jade_max_num = 0, 0
+                return False
+
+            # 决策优先级
+            res_type, target = ('斗鱼', self.ap_max_num) if ap_index <= jade_index else ('太鼓', self.jade_max_num)
+            logger.info(f'⚖️ 选择{res_type}卡 | 目标: {target}')
+
+            # 第三阶段:执行选卡操作
+            logger.hr('第三阶段:执行选卡操作', 2)
+            if self._current_select_best(res_type, target, selected_card=True):
+                logger.info(f'✅ {res_type}卡确认成功,重置状态')
+                self.ap_max_num, self.jade_max_num = 0, 0
+                return True
+            else:
+                logger.warning(f'❌ {res_type}卡确认失败,重置状态')
+                self.ap_max_num, self.jade_max_num = 0, 0
+                return False
+
+    def _current_select_best(self, best_card_type=None, best_card_num=0, selected_card=False):
+        """结界卡选择核心逻辑(集成版)
+        功能:滑动屏幕寻找最优资源卡,支持两种模式:
+        - 探索模式:记录当前遇到的最佳结界卡数值
+        - 确认模式:根据给定条件选择指定类型结界卡
+
+        :param best_card_type: 目标卡类型('太鼓'/'斗鱼')
+        :param best_card_num:  要求的最低数值
+        :param selected_card:  是否处于确认选择模式
+        :return: 找到符合条件返回True,否则None
         """
         """
-        # 首先先将所有的ocr的str顺序拼接起来, 然后再进行匹配
-        logger.info(f"重写的filter方法")
-        result = None
-        strings = [boxed_result.ocr_text for boxed_result in boxed_results]
-        concatenated_string = "".join(strings)
-        if keyword is None:
-            keyword = self.keyword
-        if keyword in concatenated_string:
-            result = [index for index, word in enumerate(strings) if keyword in word]
-        else:
-            result = None
+        # ============== 配置常量 ==============#
+        RESOURCE_CONFIG = {
+            '斗鱼': {'max': 151, 'record_attr': 'ap_max_num'},
+            '太鼓': {'max': 76, 'record_attr': 'jade_max_num'}
+        }
+        MAX_SWIPES = 20  # 最大滑动次数
+        CONSEC_MISS = 3  # 允许连续无卡次数
+        TIMEOUT = 120  # 操作超时(秒)
+
+        # ============== 初始化阶段 ==============#
+        logger.info(f'启动{"探索模式" if not selected_card else f"确认模式 | 目标: {best_card_type} @ {best_card_num}"}')
+        timer = Timer(TIMEOUT).start()
+        miss_count = 0  # 连续无卡计数器
+
+        # ============== 主滑动循环 ==============#
+        for swipe_count in range(MAX_SWIPES + 1):
+            # 超时检测
+            if timer.reached():
+                logger.warning('⏰ 操作超时,终止流程')
+                return None
 
 
-        if result is not None:
-            # logger.info("Filter result: %s" % result)
-            return result
-        else:
-            return None
-
-        # 如果适用顺序拼接还是没有匹配到,那可能是竖排的,使用单个字节的keyword进行匹配
-        indices = []
-        # 对于keyword中的每一个字符,都要在strings中进行匹配
-        # 如果这个字符在strings中的某一个string中,那么就记录这个string的index
-        max_index = len(strings) - 1
-        for index, char in enumerate(keyword):
-            for i, string in enumerate(strings):
-                if char not in string:
+            # ------ 步骤1: 截图识别结界卡 ------#
+            self.screenshot()
+            cards = self.order_targets.find_everyone(self.device.image)
+
+            # 处理无卡情况
+            if not cards:
+                miss_count += 1
+                logger.info(f'第{swipe_count}次滑动 | 未检测到结界卡' if swipe_count > 0 else '初始界面 | 未检测到结界卡')
+                # 连续无卡超过阈值则终止
+                if miss_count > CONSEC_MISS:
+                    logger.warning(f'⚠️ 连续{miss_count}次 | 未检测到结界卡, 终止流程')
+                    return None
+                # 执行滑动操作
+                self.perform_swipe_action()
+                continue
+
+            miss_count = 0  # 重置无卡计数器
+
+            # ------ 步骤2: 处理识别到的结界卡 ------
+            cards_list = [target for target, _, _ in cards]
+            logger.info((f'第{swipe_count}次滑动' if swipe_count > 0 else '初始界面') + f' | 检测到结界卡:{cards_list}')
+
+            # 遍历所有结界卡(已按位置排序)
+            for _, _, area in cards:
+                # 设置点击区域并获取结界卡详情
+                self.C_SELECT_CARD.roi_front = area
+                self.click(self.C_SELECT_CARD)
+                time.sleep(2)  # 等待结界卡详情加载
+
+                # 解析结界卡类型和数值
+                card_type, card_value = self.check_card_num()
+
+                # 跳过无效结界卡(类型未知或数值异常)
+                if card_type == 'unknown' or card_value <= 0 or card_type not in RESOURCE_CONFIG:
+                    logger.info(f'⏭️ 跳过无效卡: {card_type}@{card_value}')
                     continue
                     continue
-                if i <= max_index:
-                    indices.append(i)
-                    break
-        if indices:
-            # 剔除掉重复的index
-            indices = list(set(indices))
-            return indices
+
+                # ====== 模式分支处理 ======#
+                current_max = RESOURCE_CONFIG[card_type]['max']
+                record_attr = RESOURCE_CONFIG[card_type]['record_attr']
+                current_record = getattr(self, record_attr, 0)
+                logger.info(f'🔍 识别卡片: {card_type} | 当前值: {card_value}, 最优值: {current_record}')
+
+                # 更新最佳记录
+                if card_value > current_record:
+                    logger.info(f'📈 更新记录: {card_type} | {current_record} → {card_value}')
+                    setattr(self, record_attr, card_value)
+
+                if selected_card:  # 确认选择模式
+                    # 检查是否符合选择条件
+                    if (card_type == best_card_type) and (card_value >= best_card_num):
+                        logger.info(f'🎉 确认蹭卡: {card_type} | 当前值: {card_value} ≥ 目标值: {best_card_num}')
+                        self.save_image(push_flag=False, wait_time=0, content=f'🎉 确认蹭卡({card_type}: {card_value})')
+                        return True
+                else:  # 探索记录模式
+                    # 发现完美卡直接返回
+                    if card_value >= current_max:
+                        message = f'🎉 完美蹭卡 | {card_type}: {card_value}'
+                        logger.info(message)
+                        self.save_image(push_flag=False, wait_time=0, content=message)
+                        return True
+
+            # ------ 步骤3: 滑动到下一屏 ------#
+            self.perform_swipe_action()
+
+        # ============== 终止处理 ==============#
+        logger.warning(f'⚠️ 已达到最大滑动次数{MAX_SWIPES}, 终止流程')
+        return None
+
+    def perform_swipe_action(self):
+        """统一滑动操作"""
+        duration = 2
+        safe_pos_x = random.randint(340, 600)
+        safe_pos_y = random.randint(500, 565)
+        p1 = (safe_pos_x, safe_pos_y)
+        p2 = (safe_pos_x, safe_pos_y - 416)
+        logger.info('Swipe %s -> %s, %sS ' % (point2str(*p1), point2str(*p2), duration))
+        self.device.swipe_adb(p1, p2, duration=duration)
+
+        # self.swipe(self.S_U_UP, duration=1, wait_up_time=1)
+        self.device.click_record_clear()
+        time.sleep(2)
+
+    def check_card_num(self) -> tuple[str, int]:
+        """优化版数值提取方法,返回结界卡类型及对应数值"""
+        self.screenshot()
+        # OCR识别
+        raw_text = self.O_CARD_NUM.ocr(self.device.image)
+        # logger.info(f'OCR原始结果: {raw_text}')
+
+        # 判断结界卡类型
+        if any(c in raw_text for c in ['体', 'カ', '力']):
+            card_type = '斗鱼'
+        elif any(c in raw_text for c in ['勾', '玉']):
+            card_type = '太鼓'
         else:
         else:
-            return None
+            logger.warning(f'结界卡类型识别失败,原始内容: {raw_text}')
+            # self.push_notify(content=f'结界卡类型识别失败: {raw_text}')
+            return 'unknown', 0  # 未知类型返回0
+
+        # 提取纯数字部分(兼容带+号的情况,如+100)
+        cleaned = re.sub(r'[^\d+]', '', raw_text)  # 保留数字和加号
+        match = re.search(r'\d+', cleaned)  # 匹配连续数字
+
+        try:
+            value = int(match.group()) if match else 0
+        except ValueError:
+            logger.warning(f'数值转换异常,清理后文本: {cleaned}')
+            value = 0
+
+        if value <= 0:
+            self.push_notify(content=f'数值异常: {raw_text} -> 解析值: {value}')
+            return card_type, 0
+
+        # logger.info(f'识别成功: 卡类型: {card_type}, 数值: {value}')
+        return card_type, value
 
 
     def back_guild(self):
     def back_guild(self):
         """
         """
@@ -582,16 +724,32 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             if self.appear_then_click(self.I_UI_BACK_BLUE, interval=1):
             if self.appear_then_click(self.I_UI_BACK_BLUE, interval=1):
                 continue
                 continue
 
 
+    def back_realm(self):
+        # 回到寮结界
+        while 1:
+            self.screenshot()
+            if self.appear(self.I_REALM_SHIN):
+                break
+            if self.appear(self.I_SHI_DEFENSE):
+                break
+            if self.appear_then_click(self.I_UI_BACK_RED, interval=1):
+                continue
+            if self.appear_then_click(self.I_UI_BACK_BLUE, interval=1):
+                continue
+
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     from module.config.config import Config
     from module.config.config import Config
     from module.device.device import Device
     from module.device.device import Device
 
 
-    c = Config('oas1')
+    c = Config('switch')
     d = Device(c)
     d = Device(c)
     t = ScriptTask(c, d)
     t = ScriptTask(c, d)
-
-    t.run()
+    for i in range(10):
+        t.perform_swipe_action()
+    t.recive_guild_ap_or_assets()
+    # t.check_utilize_add()
+    # t.check_card_num('勾玉', 67)
     # t.screenshot()
     # t.screenshot()
     # print(t.appear(t.I_BOX_EXP, threshold=0.6))
     # print(t.appear(t.I_BOX_EXP, threshold=0.6))
     # print(t.appear(t.I_BOX_EXP_MAX, threshold=0.6))
     # print(t.appear(t.I_BOX_EXP_MAX, threshold=0.6))

+ 32 - 0
tasks/KekkaiUtilize/utilize/click.json

@@ -0,0 +1,32 @@
+[
+  {
+    "itemName": "select_realm_1",
+    "roiFront": "300,200,200,50",
+    "roiBack": "300,200,200,50",
+    "description": "选择结界区域1"
+  },
+  {
+    "itemName": "select_realm_2",
+    "roiFront": "300,307,200,50",
+    "roiBack": "300,307,200,50",
+    "description": "选择结界区域2"
+  },
+  {
+    "itemName": "select_realm_3",
+    "roiFront": "300,415,200,50",
+    "roiBack": "300,415,200,50",
+    "description": "选择结界区域3"
+  },
+  {
+    "itemName": "select_realm_4",
+    "roiFront": "300,520,200,50",
+    "roiBack": "300,520,200,50",
+    "description": "选择结界区域4"
+  },
+  {
+    "itemName": "select_card",
+    "roiFront": "0,0,0,0",
+    "roiBack": "0,0,0,0",
+    "description": "点击识别到的卡(用识别到的坐标填充作用)"
+  }
+]

+ 40 - 4
tasks/KekkaiUtilize/utilize/image.json

@@ -47,7 +47,7 @@
   {
   {
     "itemName": "u_taiko_5",
     "itemName": "u_taiko_5",
     "imageName": "utilize_u_taiko_5.png",
     "imageName": "utilize_u_taiko_5.png",
-    "roiFront": "544,201,59,52",
+    "roiFront": "543,201,62,54",
     "roiBack": "538,179,79,426",
     "roiBack": "538,179,79,426",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
@@ -56,7 +56,7 @@
   {
   {
     "itemName": "u_taiko_6",
     "itemName": "u_taiko_6",
     "imageName": "utilize_u_taiko_6.png",
     "imageName": "utilize_u_taiko_6.png",
-    "roiFront": "545,313,60,45",
+    "roiFront": "543,521,62,54",
     "roiBack": "533,156,87,450",
     "roiBack": "533,156,87,450",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
@@ -83,7 +83,7 @@
   {
   {
     "itemName": "u_fish_5",
     "itemName": "u_fish_5",
     "imageName": "utilize_u_fish_5.png",
     "imageName": "utilize_u_fish_5.png",
-    "roiFront": "552,529,45,41",
+    "roiFront": "543,412,62,54",
     "roiBack": "541,183,71,403",
     "roiBack": "541,183,71,403",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
@@ -92,7 +92,7 @@
   {
   {
     "itemName": "u_fish_6",
     "itemName": "u_fish_6",
     "imageName": "utilize_u_fish_6.png",
     "imageName": "utilize_u_fish_6.png",
-    "roiFront": "544,201,59,52",
+    "roiFront": "542,197,62,54",
     "roiBack": "530,184,82,416",
     "roiBack": "530,184,82,416",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
@@ -169,5 +169,41 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "description"
     "description": "description"
+  },
+  {
+    "itemName": "select_realm_on_1",
+    "imageName": "select_realm_on_1.png",
+    "roiFront": "608,191,21,59",
+    "roiBack": "608,191,21,59",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "select_realm_on_2",
+    "imageName": "select_realm_on_2.png",
+    "roiFront": "606,298,21,59",
+    "roiBack": "606,298,21,59",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "select_realm_on_3",
+    "imageName": "select_realm_on_3.png",
+    "roiFront": "607,404,21,59",
+    "roiBack": "607,404,21,59",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
+  },
+  {
+    "itemName": "select_realm_on_4",
+    "imageName": "select_realm_on_4.png",
+    "roiFront": "607,516,21,59",
+    "roiBack": "607,516,21,59",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
   }
   }
 ]
 ]

+ 5 - 14
tasks/KekkaiUtilize/utilize/ocr.json

@@ -18,21 +18,12 @@
     "description": "今日已领取经验"
     "description": "今日已领取经验"
   },
   },
   {
   {
-    "itemName": "box_exp_zcsb",
-    "roiFront": "584,542,181,35",
-    "roiBack": "584,542,181,35",
-    "mode": "DigitCounter",
-    "method": "Default",
-    "keyword": "",
-    "description": "今日已领取经验(招财上宾)"
-  },
-  {
-    "itemName": "utilize_f_list",
-    "roiFront": "307,171,213,416",
-    "roiBack": "307,171,213,416",
-    "mode": "Full",
+    "itemName": "card_num",
+    "roiFront": "800,421,150,33",
+    "roiBack": "800,421,150,33",
+    "mode": "Single",
     "method": "Default",
     "method": "Default",
     "keyword": "",
     "keyword": "",
-    "description": "Ocr-description"
+    "description": "斗鱼或太古寄养数目"
   }
   }
 ]
 ]

BIN
tasks/KekkaiUtilize/utilize/select_realm_on_1.png


BIN
tasks/KekkaiUtilize/utilize/select_realm_on_2.png


BIN
tasks/KekkaiUtilize/utilize/select_realm_on_3.png


BIN
tasks/KekkaiUtilize/utilize/select_realm_on_4.png


+ 3 - 3
tasks/KekkaiUtilize/utilize/swipe.json

@@ -1,8 +1,8 @@
 [
 [
   {
   {
     "itemName": "u_up",
     "itemName": "u_up",
-    "roiFront": "237,349,50,21",
-    "roiBack": "225,177,72,21",
+    "roiFront": "247,520,100,1",
+    "roiBack": "247,104,100,1",
     "mode": "default",
     "mode": "default",
     "description": "向下滑动"
     "description": "向下滑动"
   },
   },
@@ -13,4 +13,4 @@
     "mode": "default",
     "mode": "default",
     "description": "滑动到底部"
     "description": "滑动到底部"
   }
   }
-]
+]

BIN
tasks/KekkaiUtilize/utilize/utilize_check_friend_realm_3.png


BIN
tasks/KekkaiUtilize/utilize/utilize_u_fish_5.png


BIN
tasks/KekkaiUtilize/utilize/utilize_u_fish_6.png


BIN
tasks/KekkaiUtilize/utilize/utilize_u_taiko_5.png


BIN
tasks/KekkaiUtilize/utilize/utilize_u_taiko_6.png


+ 7 - 1
tasks/base_task.py

@@ -627,4 +627,10 @@ class BaseTask(GlobalGameAssets, CostumeBase):
                 continue
                 continue
             if isinstance(click, RuleOcr):
             if isinstance(click, RuleOcr):
                 self.click(click)
                 self.click(click)
-                continue
+                continue
+
+    def push_notify(self, content='', title=None, level=3):
+        logger.info(f'Push notify: {content}')
+
+    def save_image(self, task_name=None, content=None, wait_time=2, image_type=False, push_flag=False, level=3):
+        logger.info(f'Save image: {task_name}')