Răsfoiți Sursa

Merge branch 'dev' into fix(emulator_window_minimize)

huangrunheng 1 an în urmă
părinte
comite
7a417d2ba2

+ 23 - 13
module/device/method/nemu_ipc.py

@@ -209,7 +209,29 @@ class NemuIpcImpl:
         self.instance_id: int = instance_id
         self.display_id: int = display_id
 
-        ipc_dll = os.path.abspath(os.path.join(nemu_folder, './shell/sdk/external_renderer_ipc.dll'))
+        list_dll = [
+            # MuMuPlayer12
+            os.path.abspath(os.path.join(nemu_folder, './shell/sdk/external_renderer_ipc.dll')),
+            # MuMuPlayer12 5.0
+            os.path.abspath(os.path.join(nemu_folder, './nx_device/12.0/shell/sdk/external_renderer_ipc.dll')),
+        ]
+        self.lib = None
+        for ipc_dll in list_dll:
+            if not os.path.exists(ipc_dll):
+                continue
+            try:
+                self.lib = ctypes.CDLL(ipc_dll)
+                break
+            except OSError as e:
+                logger.error(e)
+                logger.error(f'ipc_dll={ipc_dll} exists, but cannot be loaded')
+                continue
+        if self.lib is None:
+            # not found
+            raise NemuIpcIncompatible(
+                f'NemuIpc requires MuMu12 version >= 3.8.13, please check your version. '
+                f'None of the following path exists: {list_dll}')
+        # success
         logger.info(
             f'NemuIpcImpl init, '
             f'nemu_folder={nemu_folder}, '
@@ -218,18 +240,6 @@ class NemuIpcImpl:
             f'display_id={display_id}'
         )
 
-        try:
-            self.lib = ctypes.CDLL(ipc_dll)
-        except OSError as e:
-            logger.error(e)
-            # OSError: [WinError 126] 找不到指定的模块。
-            if not os.path.exists(ipc_dll):
-                raise NemuIpcIncompatible(
-                    f'ipc_dll={ipc_dll} does not exist, '
-                    f'NemuIpc requires MuMu12 version >= 3.8.13, please check your version')
-            else:
-                raise NemuIpcIncompatible(
-                    f'ipc_dll={ipc_dll} exists, but cannot be loaded')
         self.connect_id: int = 0
         self.width = 0
         self.height = 0

+ 7 - 2
module/device/platform2/emulator_windows.py

@@ -122,7 +122,7 @@ class Emulator(EmulatorBase):
                 return cls.MuMuPlayerX
             else:
                 return cls.MuMuPlayer
-        if exe == 'mumuplayer.exe':
+        if exe in ['mumuplayer.exe', 'mumunxmain.exe']:
             return cls.MuMuPlayer12
         if exe == 'memu.exe':
             return cls.MEmuPlayer
@@ -171,6 +171,9 @@ class Emulator(EmulatorBase):
         """
         if 'MuMuPlayer.exe' in exe:
             return exe.replace('MuMuPlayer.exe', 'MuMuManager.exe')
+         # MuMuPlayer12 5.0
+        elif 'MuMuNxMain.exe' in exe:
+            return exe.replace('MuMuNxMain.exe', 'MuMuManager.exe')
         elif 'LDPlayer.exe' in exe:
             return exe.replace('LDPlayer.exe', 'ldconsole.exe')
         elif 'dnplayer.exe' in exe:
@@ -464,7 +467,9 @@ class EmulatorManager(EmulatorManagerBase):
             'leidian9',
             'Nemu',
             'Nemu9',
-            'MuMuPlayer-12.0'
+            'MuMuPlayer',
+            'MuMuPlayer-12.0',
+            'MuMu Player 12.0',
             'MEmu',
         ]
         for path in known_uninstall_registry_path:

+ 31 - 0
module/device/platform2/platform_base.py

@@ -152,6 +152,16 @@ class PlatformBase(EmulatorManagerBase):
             logger.info(instance)
         search_args = dict(serial=serial)
 
+        instance_id = serial_to_id(self.serial)
+        if instance_id is not None:
+            select = instances.select(MuMuPlayer12_id=instance_id)
+            # No logs for if select.count == 1:
+            # because this is just a trial
+            if select.count == 1:
+                instance = select[0]
+                logger.hr('Emulator instance', level=2)
+                logger.info(f'Found emulator instance: {instance}')
+                return instance
         # Search by serial
         select = instances.select(**search_args)
         if select.count == 0:
@@ -224,3 +234,24 @@ class PlatformBase(EmulatorManagerBase):
         # Still too many instances
         logger.warning(f'Found multiple emulator instances with {search_args}')
         return None
+
+def serial_to_id(serial: str):
+    """
+    Predict instance ID from serial
+    E.g.
+        "127.0.0.1:16384" -> 0
+        "127.0.0.1:16416" -> 1
+        Port from 16414 to 16418 -> 1
+    Returns:
+        int: instance_id, or None if failed to predict
+    """
+    try:
+        port = int(serial.split(':')[1])
+    except (IndexError, ValueError):
+        return None
+    index, offset = divmod(port - 16384 + 16, 32)
+    offset -= 16
+    if 0 <= index < 32 and offset in [-2, -1, 0, 1, 2]:
+        return index
+    else:
+        return None

+ 29 - 1
module/logger.py

@@ -19,6 +19,28 @@ from rich.style import Style
 from rich.theme import Theme
 from rich.traceback import Traceback
 
+import time
+from pathlib import Path
+
+SECONDS_IN_DAY = 24 * 60 * 60
+
+def cleanup_logs(log_dir: str = "./log", keep_days: int = 7):
+    """删除 log_dir 下所有早于 keep_days 的普通文件"""
+    cutoff_ts = time.time() - keep_days * SECONDS_IN_DAY
+
+    log_path = Path(log_dir)
+    if not log_path.exists():
+        return  # 目录都没有,直接退出
+
+    for p in log_path.iterdir():
+        # 只处理文件;子文件夹一律跳过
+        if p.is_file():
+            try:
+                if p.stat().st_mtime < cutoff_ts:
+                    p.unlink()
+                    logger.info(f"Removed old log finish: {p.name}")
+            except Exception as e:
+                logger.warning(f"Failed to delete {p}: {e}")
 
 def empty_function(*args, **kwargs):
     pass
@@ -98,7 +120,7 @@ class RichFileHandler(RichHandler):
 pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
 
-def set_file_logger(name=pyw_name):
+def set_file_logger(name=pyw_name, *, do_cleanup=False):
     if '_' in name:
         name = name.split('_', 1)[0]
     log_file = f'./log/{datetime.date.today()}_{name}.txt'
@@ -133,6 +155,12 @@ def set_file_logger(name=pyw_name):
     logger.addHandler(hdlr)
     logger.log_file = log_file
 
+    # ---------- 可选:清理旧文件 ----------
+    if do_cleanup:
+        cleanup_logs()
+    if do_cleanup:
+        logger.info("Log cleanup finished")   
+
 
 # ======================================================================================================================
 #            Set flutter

+ 12 - 2
script.py

@@ -14,6 +14,8 @@ import inflection
 import asyncio
 import json
 
+from datetime import date
+import threading
 from typing import Callable
 from datetime import datetime, timedelta
 from pathlib import Path
@@ -32,10 +34,12 @@ from module.base.decorator import del_cached_property
 from module.logger import logger
 from module.exception import *
 from module.server.i18n import I18n
-
 from module.device.platform2.platform_windows import minimize_by_name,show_window_by_name
 
 
+_log_switch_lock = threading.Lock()#线程锁
+
+
 class Script:
     def __init__(self, config_name: str ='oas') -> None:
         logger.hr('Start', level=0)
@@ -405,7 +409,9 @@ class Script:
         Main loop of scheduler.
         :return:
         """
-        logger.set_file_logger(self.config_name)
+        with _log_switch_lock:
+            logger.set_file_logger(self.config_name, do_cleanup=True)
+        start_day = date.today()
         logger.info(f'Start scheduler loop: {self.config_name}')
 
         # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
@@ -418,6 +424,10 @@ class Script:
                 show_window_by_name(target_window_name)
                 
         while 1:
+            if date.today() > start_day:
+                with _log_switch_lock:
+                    logger.set_file_logger(self.config_name, do_cleanup=True)
+                start_day = date.today()
             # Check update event from GUI
             # if self.stop_event is not None:
             #     if self.stop_event.is_set():

+ 2 - 0
tasks/CollectiveMissions/assets.py

@@ -40,6 +40,8 @@ class CollectiveMissionsAssets:
 	I_CM_ADD_4 = RuleImage(roi_front=(904,510,47,47), roi_back=(904,510,47,47), threshold=0.8, method="Template matching", file="./tasks/CollectiveMissions/cm/cm_cm_add_4.png")
 	# 领取奖励 
 	I_CM_REWARDS = RuleImage(roi_front=(567,463,145,60), roi_back=(200,458,914,88), threshold=0.8, method="Template matching", file="./tasks/CollectiveMissions/cm/cm_cm_rewards.png")
+	# description 
+	I_CM_SWITCH = RuleImage(roi_front=(414,478,43,58), roi_back=(310,453,282,114), threshold=0.8, method="Template matching", file="./tasks/CollectiveMissions/cm/cm_cm_switch.png")
 
 
 	# Ocr Rule Assets

BIN
tasks/CollectiveMissions/cm/cm_cm_switch.png


+ 9 - 0
tasks/CollectiveMissions/cm/image.json

@@ -88,5 +88,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "领取奖励"
+  },
+  {
+    "itemName": "cm_switch",
+    "imageName": "cm_cm_switch.png",
+    "roiFront": "414,478,43,58",
+    "roiBack": "310,453,282,114",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "description"
   }
 ]

+ 2 - 0
tasks/CollectiveMissions/config.py

@@ -17,6 +17,8 @@ class MissionsConfig(BaseModel):
     missions_rule: MultiLine = Field(default='契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一 > 远远不够',
                                      description='missions_rule_help')
     setup_when_bondling: bool = Field(default=True, description='setup_when_bondling_help')
+    missions_select: str = Field(default='觉醒三',
+                                description='指定的任务')
 
     @validator('missions_rule', pre=True, always=True)
     def mr_validator(cls, v):

+ 23 - 0
tasks/CollectiveMissions/script_task.py

@@ -59,6 +59,9 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
             logger.warning('Today\'s missions have been completed')
             self.set_next_run(task='CollectiveMissions', success=False, finish=True)
             raise TaskEnd('CollectiveMissions')
+        #切换为目标任务
+        mission_name = self.config.collective_missions.missions_config.missions_select
+        self.select_mission(mission_name)
         # 判断最优的任务是哪一个
         mission, index = self.detect_best()
         logger.info(f'Best mission is {mission}')
@@ -277,6 +280,26 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
         logger.info('Donate finished')
         return True
 
+    def select_mission(self, missions_select: str) -> bool:
+        """
+        尝试在当前界面中识别并选择指定名称的好友
+        :param friend_name: 要选择的好友名称
+        :return: 成功选择返回True
+        """
+
+        while 1:
+            self.screenshot()
+            # 识别当前任务
+            missions = self.detect_one(self.O_CM_1, self.O_CM_2)
+            logger.info(f"当前任务: {missions}")
+            logger.info(f"目标任务: {missions_select}")
+            if missions == missions_select:
+                logger.info(f"成功切换任务")
+                return True
+            else:
+                logger.info(f"尝试切换任务")
+                self.appear_then_click(self.I_CM_SWITCH, interval=1)
+
     def _soul(self, index: int):
         """
         搞收御魂的任务

+ 67 - 20
tasks/KekkaiUtilize/script_task.py

@@ -8,7 +8,10 @@ from datetime import timedelta, datetime
 from module.base.timer import Timer
 from module.atom.image_grid import ImageGrid
 from module.logger import logger
-from module.exception import TaskEnd,GameStuckError
+
+from module.exception import TaskEnd, GameStuckError
+from ppocronnx.predict_system import BoxedResult
+
 
 from tasks.GameUi.game_ui import GameUi
 from tasks.Utils.config_enum import ShikigamiClass
@@ -66,11 +69,7 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             )
         raise TaskEnd
 
-
-
-
-
-    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:
         """
         在寮的主界面 检查是否有收取体力或者是收取寮资金
         如果有就顺带收取
@@ -128,7 +127,7 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             if self.appear_then_click(self.I_GUILD_REALM, interval=1):
                 continue
 
-    def check_box_ap_or_exp(self, ap_enable: bool=True, exp_enable: bool=True, exp_waste: bool=True) -> bool:
+    def check_box_ap_or_exp(self, ap_enable: bool = True, exp_enable: bool = True, exp_waste: bool = True) -> bool:
         """
         顺路检查盒子
         :param ap_enable:
@@ -147,7 +146,7 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
                     continue
 
         # 先是体力盒子
-        def _check_ap_box(appear: bool=False):
+        def _check_ap_box(appear: bool = False):
             if not appear:
                 return False
             # 点击盒子
@@ -177,7 +176,7 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             _exit_to_realm()
 
         # 经验盒子
-        def _check_exp_box(appear: bool=False):
+        def _check_exp_box(appear: bool = False):
             if not appear:
                 logger.info('No exp box')
                 return False
@@ -391,15 +390,21 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             :return: 成功选择返回True
             """
             logger.info(f"尝试选择好友: {friend_name}")
-            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
-
+            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')
         self.switch_friend_list(friend)
@@ -504,6 +509,49 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
         self.set_shikigami(shikigami_order, stop_image)
         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:
+        """
+        # 首先先将所有的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
+
+        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:
+                    continue
+                if i <= max_index:
+                    indices.append(i)
+                    break
+        if indices:
+            # 剔除掉重复的index
+            indices = list(set(indices))
+            return indices
+        else:
+            return None
 
     def back_guild(self):
         """
@@ -523,6 +571,7 @@ class ScriptTask(GameUi, ReplaceShikigami, KekkaiUtilizeAssets):
             if self.appear_then_click(self.I_UI_BACK_BLUE, interval=1):
                 continue
 
+
 if __name__ == "__main__":
     from module.config.config import Config
     from module.device.device import Device
@@ -535,5 +584,3 @@ if __name__ == "__main__":
     # t.screenshot()
     # print(t.appear(t.I_BOX_EXP, threshold=0.6))
     # print(t.appear(t.I_BOX_EXP_MAX, threshold=0.6))
-
-

+ 3 - 3
tasks/RichMan/assets.py

@@ -183,15 +183,15 @@ class RichManAssets:
 	# 荣誉 
 	I_SIDE_CHECK_HONOR = RuleImage(roi_front=(694,12,41,42), roi_back=(694,12,41,42), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_check_honor.png")
 	# 友情点 
-	I_SIDE_SURE_FRIENDS = RuleImage(roi_front=(1190,287,43,52), roi_back=(1163,258,93,109), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_sure_friends.png")
+	I_SIDE_SURE_FRIENDS = RuleImage(roi_front=(1190,287,43,52), roi_back=(1163,258,93,126), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_sure_friends.png")
 	# 友情点 
 	I_SIDE_CHECK_FRIENDS = RuleImage(roi_front=(890,8,39,43), roi_back=(890,8,39,43), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_check_friends.png")
 	# 勋章 
-	I_SIDE_SURE_MEDAL = RuleImage(roi_front=(1190,375,39,62), roi_back=(1156,352,99,113), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_sure_medal.png")
+	I_SIDE_SURE_MEDAL = RuleImage(roi_front=(1190,404,39,62), roi_back=(1156,352,112,128), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_sure_medal.png")
 	# 勋章 
 	I_SIDE_CHECK_MEDAL = RuleImage(roi_front=(665,6,40,44), roi_back=(453,1,476,58), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_check_medal.png")
 	# 魅力值 
-	I_SIDE_SURE_CHARISMA = RuleImage(roi_front=(1181,467,59,58), roi_back=(1158,445,101,106), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_sure_charisma.png")
+	I_SIDE_SURE_CHARISMA = RuleImage(roi_front=(1181,467,59,58), roi_back=(1158,445,101,142), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_sure_charisma.png")
 	# 魅力值 
 	I_SIDE_CHECK_CHARISMA = RuleImage(roi_front=(886,4,48,46), roi_back=(886,4,48,46), threshold=0.7, method="Template matching", file="./tasks/RichMan/mall/navbar/navbar_side_check_charisma.png")
 

+ 4 - 4
tasks/RichMan/mall/navbar/image_side.json

@@ -39,7 +39,7 @@
     "itemName": "side_sure_friends",
     "imageName": "navbar_side_sure_friends.png",
     "roiFront": "1190,287,43,52",
-    "roiBack": "1163,258,93,109",
+    "roiBack": "1163,258,93,126",
     "method": "Template matching",
     "threshold": 0.7,
     "description": "友情点"
@@ -56,8 +56,8 @@
   {
     "itemName": "side_sure_medal",
     "imageName": "navbar_side_sure_medal.png",
-    "roiFront": "1190,375,39,62",
-    "roiBack": "1156,352,99,113",
+    "roiFront": "1190,404,39,62",
+    "roiBack": "1156,352,112,128",
     "method": "Template matching",
     "threshold": 0.7,
     "description": "勋章"
@@ -75,7 +75,7 @@
     "itemName": "side_sure_charisma",
     "imageName": "navbar_side_sure_charisma.png",
     "roiFront": "1181,467,59,58",
-    "roiBack": "1158,445,101,106",
+    "roiBack": "1158,445,101,142",
     "method": "Template matching",
     "threshold": 0.7,
     "description": "魅力值"

BIN
tasks/RichMan/mall/navbar/navbar_side_sure_medal.png