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

Merge pull request #976 from runhey/dev

Automated PR 2025.07.31
huangrunheng 1 год назад
Родитель
Сommit
2d31548447

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

@@ -209,7 +209,29 @@ class NemuIpcImpl:
         self.instance_id: int = instance_id
         self.instance_id: int = instance_id
         self.display_id: int = display_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(
         logger.info(
             f'NemuIpcImpl init, '
             f'NemuIpcImpl init, '
             f'nemu_folder={nemu_folder}, '
             f'nemu_folder={nemu_folder}, '
@@ -218,18 +240,6 @@ class NemuIpcImpl:
             f'display_id={display_id}'
             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.connect_id: int = 0
         self.width = 0
         self.width = 0
         self.height = 0
         self.height = 0

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

@@ -122,7 +122,7 @@ class Emulator(EmulatorBase):
                 return cls.MuMuPlayerX
                 return cls.MuMuPlayerX
             else:
             else:
                 return cls.MuMuPlayer
                 return cls.MuMuPlayer
-        if exe == 'mumuplayer.exe':
+        if exe in ['mumuplayer.exe', 'mumunxmain.exe']:
             return cls.MuMuPlayer12
             return cls.MuMuPlayer12
         if exe == 'memu.exe':
         if exe == 'memu.exe':
             return cls.MEmuPlayer
             return cls.MEmuPlayer
@@ -171,6 +171,9 @@ class Emulator(EmulatorBase):
         """
         """
         if 'MuMuPlayer.exe' in exe:
         if 'MuMuPlayer.exe' in exe:
             return exe.replace('MuMuPlayer.exe', 'MuMuManager.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:
         elif 'LDPlayer.exe' in exe:
             return exe.replace('LDPlayer.exe', 'ldconsole.exe')
             return exe.replace('LDPlayer.exe', 'ldconsole.exe')
         elif 'dnplayer.exe' in exe:
         elif 'dnplayer.exe' in exe:
@@ -464,7 +467,9 @@ class EmulatorManager(EmulatorManagerBase):
             'leidian9',
             'leidian9',
             'Nemu',
             'Nemu',
             'Nemu9',
             'Nemu9',
-            'MuMuPlayer-12.0'
+            'MuMuPlayer',
+            'MuMuPlayer-12.0',
+            'MuMu Player 12.0',
             'MEmu',
             'MEmu',
         ]
         ]
         for path in known_uninstall_registry_path:
         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)
             logger.info(instance)
         search_args = dict(serial=serial)
         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
         # Search by serial
         select = instances.select(**search_args)
         select = instances.select(**search_args)
         if select.count == 0:
         if select.count == 0:
@@ -224,3 +234,24 @@ class PlatformBase(EmulatorManagerBase):
         # Still too many instances
         # Still too many instances
         logger.warning(f'Found multiple emulator instances with {search_args}')
         logger.warning(f'Found multiple emulator instances with {search_args}')
         return None
         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

+ 101 - 25
module/device/platform2/platform_windows.py

@@ -12,10 +12,68 @@ from module.device.platform2.platform_base import PlatformBase
 from module.device.platform2.emulator_windows import Emulator, EmulatorInstance, EmulatorManager
 from module.device.platform2.emulator_windows import Emulator, EmulatorInstance, EmulatorManager
 from module.logger import logger
 from module.logger import logger
 
 
+import ctypes
+from ctypes import wintypes
+
 
 
 class EmulatorUnknown(Exception):
 class EmulatorUnknown(Exception):
     pass
     pass
 
 
+def minimize_by_name(window_name, convert_hidden=True):
+    """
+    按名称处理窗口状态
+    Args:
+        window_name (str): 窗口名称(支持部分匹配)
+        convert_hidden (bool): 是否将隐藏窗口改为最小化
+    """
+    def callback(hwnd, lParam):
+        title = get_window_title(hwnd)
+        if window_name.lower() in title.lower():
+            # 检查窗口当前状态
+            is_visible = ctypes.windll.user32.IsWindowVisible(hwnd)
+            
+            if is_visible:
+                # 可见窗口 → 最小化
+                minimize_window(hwnd)
+                logger.info(f'最小化可见窗口: {title}')
+            elif convert_hidden:
+                # 隐藏窗口 → 改为最小化不激活
+                ctypes.windll.user32.ShowWindow(hwnd, 6)  # SW_SHOWMINNOACTIVE
+                logger.info(f'隐藏窗口改为最小化: {title}')
+        return True
+    
+    WNDENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, ctypes.POINTER(ctypes.c_int))
+    ctypes.windll.user32.EnumWindows(WNDENUMPROC(callback), None)
+
+def find_hwnd_by_name(window_name):
+    """
+    枚举所有窗口,返回第一个匹配名称的 hwnd
+    """
+    target = None
+    def callback(hwnd, lParam):
+        title = get_window_title(hwnd)
+        if window_name.lower() in title.lower():
+            nonlocal target
+            target = hwnd
+            return False  # 停止枚举
+        return True
+
+    WNDENUMPROC = ctypes.WINFUNCTYPE(ctypes.c_bool, wintypes.HWND, ctypes.POINTER(ctypes.c_int))
+    ctypes.windll.user32.EnumWindows(WNDENUMPROC(callback), None)
+    return target
+def show_window_by_name(window_name):
+    """
+    显示指定名称的窗口
+    Args:
+        window_name (str): 窗口名称(支持部分匹配)
+    """
+    hwnd = find_hwnd_by_name(window_name)
+    if hwnd:
+        ctypes.windll.user32.ShowWindow(hwnd, 5)  # SW_SHOW
+        set_focus_window(hwnd)
+        logger.info(f'显示窗口: {window_name}')
+    else:
+        logger.info(f'没有找到窗口: {window_name}')
 
 
 def get_focused_window():
 def get_focused_window():
     return ctypes.windll.user32.GetForegroundWindow()
     return ctypes.windll.user32.GetForegroundWindow()
@@ -57,7 +115,7 @@ class AdbDeviceWithStatus(AdbDevice):
 
 
 class PlatformWindows(PlatformBase, EmulatorManager):
 class PlatformWindows(PlatformBase, EmulatorManager):
     @classmethod
     @classmethod
-    def execute(cls, command):
+    def execute(cls, command, show_window=True):
         """
         """
         Args:
         Args:
             command (str):
             command (str):
@@ -65,9 +123,24 @@ class PlatformWindows(PlatformBase, EmulatorManager):
         Returns:
         Returns:
             subprocess.Popen:
             subprocess.Popen:
         """
         """
+
+        startupinfo = subprocess.STARTUPINFO()
+        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+
+        if not show_window:
+            startupinfo.wShowWindow = 0  # SW_MINIMIZE - 不显示窗口
+        else:
+            startupinfo.wShowWindow = 1  # SW_SHOWNORMAL - 正常显示
+
+
         command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
         command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
         logger.info(f'Execute: {command}')
         logger.info(f'Execute: {command}')
-        return subprocess.Popen(command, close_fds=True)  # only work on Windows
+        return subprocess.Popen(
+        command,
+        close_fds=True,
+        startupinfo=startupinfo
+        )
+        #return subprocess.Popen(command, close_fds=True)  # only work on Windows
 
 
     @classmethod
     @classmethod
     def kill_process_by_regex(cls, regex: str) -> int:
     def kill_process_by_regex(cls, regex: str) -> int:
@@ -95,33 +168,34 @@ class PlatformWindows(PlatformBase, EmulatorManager):
         """
         """
         Start a emulator without error handling
         Start a emulator without error handling
         """
         """
+        show_window=not self.config.script.device.emulator_window_minimize and not self.config.script.device.run_background_only
         exe: str = instance.emulator.path
         exe: str = instance.emulator.path
         if instance == Emulator.MuMuPlayer:
         if instance == Emulator.MuMuPlayer:
             # NemuPlayer.exe
             # NemuPlayer.exe
-            self.execute(exe)
+            self.execute(exe, show_window=show_window)
         elif instance == Emulator.MuMuPlayerX:
         elif instance == Emulator.MuMuPlayerX:
             # NemuPlayer.exe -m nemu-12.0-x64-default
             # NemuPlayer.exe -m nemu-12.0-x64-default
-            self.execute(f'"{exe}" -m {instance.name}')
+            self.execute(f'"{exe}" -m {instance.name}', show_window=show_window)
         elif instance == Emulator.MuMuPlayer12:
         elif instance == Emulator.MuMuPlayer12:
             # MuMuPlayer.exe -v 0
             # MuMuPlayer.exe -v 0
             if instance.MuMuPlayer12_id is None:
             if instance.MuMuPlayer12_id is None:
                 logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
                 logger.warning(f'Cannot get MuMu instance index from name {instance.name}')
-            self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}')
+            self.execute(f'"{exe}" -v {instance.MuMuPlayer12_id}', show_window=show_window)
         elif instance == Emulator.LDPlayerFamily:
         elif instance == Emulator.LDPlayerFamily:
             # ldconsole.exe launch --index 0
             # ldconsole.exe launch --index 0
-            self.execute(f'"{Emulator.single_to_console(exe)}" launch --index {instance.LDPlayer_id}')
+            self.execute(f'"{Emulator.single_to_console(exe)}" launch --index {instance.LDPlayer_id}', show_window=show_window)
         elif instance == Emulator.NoxPlayerFamily:
         elif instance == Emulator.NoxPlayerFamily:
             # Nox.exe -clone:Nox_1
             # Nox.exe -clone:Nox_1
-            self.execute(f'"{exe}" -clone:{instance.name}')
+            self.execute(f'"{exe}" -clone:{instance.name}', show_window=show_window)
         elif instance == Emulator.BlueStacks5:
         elif instance == Emulator.BlueStacks5:
             # HD-Player.exe --instance Pie64
             # HD-Player.exe --instance Pie64
-            self.execute(f'"{exe}" --instance {instance.name}')
+            self.execute(f'"{exe}" --instance {instance.name}', show_window=show_window)
         elif instance == Emulator.BlueStacks4:
         elif instance == Emulator.BlueStacks4:
             # Bluestacks.exe -vmname Android_1
             # Bluestacks.exe -vmname Android_1
-            self.execute(f'"{exe}" -vmname {instance.name}')
+            self.execute(f'"{exe}" -vmname {instance.name}', show_window=show_window)
         elif instance == Emulator.MEmuPlayer:
         elif instance == Emulator.MEmuPlayer:
             # MEmu.exe MEmu_0
             # MEmu.exe MEmu_0
-            self.execute(f'"{exe}" {instance.name}')
+            self.execute(f'"{exe}" {instance.name}', show_window=show_window)
         else:
         else:
             raise EmulatorUnknown(f'Cannot start an unknown emulator instance: {instance}')
             raise EmulatorUnknown(f'Cannot start an unknown emulator instance: {instance}')
 
 
@@ -262,7 +336,7 @@ class PlatformWindows(PlatformBase, EmulatorManager):
             # logger.info([get_focused_window(), get_window_title(get_focused_window())])
             # logger.info([get_focused_window(), get_window_title(get_focused_window())])
             if current_window != 0 and new_window == 0:
             if current_window != 0 and new_window == 0:
                 new_window = get_focused_window()
                 new_window = get_focused_window()
-                if current_window != new_window:
+                if current_window != new_window and not self.config.script.device.emulator_window_minimize and not self.config.script.device.run_background_only:
                     logger.info(f'New window showing up: {new_window}, focus back')
                     logger.info(f'New window showing up: {new_window}, focus back')
                     set_focus_window(current_window)
                     set_focus_window(current_window)
                 else:
                 else:
@@ -316,24 +390,26 @@ class PlatformWindows(PlatformBase, EmulatorManager):
             break
             break
 
 
         emulator_window_minimize = self.config.script.device.emulator_window_minimize
         emulator_window_minimize = self.config.script.device.emulator_window_minimize
-        logger.info(f'Minimize new emulator window: {emulator_window_minimize}')
-        if emulator_window_minimize:
-            if new_window != 0 and new_window != current_window:
-                # 如果有新窗口且新窗口不是当前窗口,最小化新窗口
-                logger.info(f'Minimize new window: {new_window}')
-                minimize_window(new_window)
-            if current_window:
-                # 如果有当前窗口,取消当前窗口的闪烁
-                logger.info(f'De-flash current window: {current_window}')
-                flash_window(current_window, flash=False)
-            if new_window:
-                # 如果有新窗口,使新窗口闪烁
-                logger.info(f'Flash new window: {new_window}')
-                flash_window(new_window, flash=True)
+        if (emulator_window_minimize): logger.info(f'Minimize new emulator window: {emulator_window_minimize}')
+        if (self.config.script.device.run_background_only):
+            logger.info(f'run background only: {self.config.script.device.run_background_only}')
+            logger.warning('run_background_only will not show any UI, emulator will run background only')
+        if emulator_window_minimize and not self.config.script.device.run_background_only:
+            # 直接使用窗口名称最小化
+            sleep_time = 3
+            logger.info(f'Waiting {sleep_time} seconds before minimizing window')
+            Timer(sleep_time).wait()
+            target_window_name = self.config.script.device.handle  # 在这里输入你的具体窗口名称
+            minimize_by_name(target_window_name)
+            logger.info(f'最小化窗口: {target_window_name}')
+            # if current_window:
+            #     logger.info(f'De-flash current window: {current_window}')
+            #     flash_window(current_window, flash=False)
 
 
         logger.info('Emulator start completed')
         logger.info('Emulator start completed')
         return True
         return True
 
 
+
     def emulator_start(self):
     def emulator_start(self):
         logger.hr('Emulator start', level=1)
         logger.hr('Emulator start', level=1)
         for _ in range(3):
         for _ in range(3):

+ 29 - 1
module/logger.py

@@ -19,6 +19,28 @@ from rich.style import Style
 from rich.theme import Theme
 from rich.theme import Theme
 from rich.traceback import Traceback
 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):
 def empty_function(*args, **kwargs):
     pass
     pass
@@ -98,7 +120,7 @@ class RichFileHandler(RichHandler):
 pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 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:
     if '_' in name:
         name = name.split('_', 1)[0]
         name = name.split('_', 1)[0]
     log_file = f'./log/{datetime.date.today()}_{name}.txt'
     log_file = f'./log/{datetime.date.today()}_{name}.txt'
@@ -133,6 +155,12 @@ def set_file_logger(name=pyw_name):
     logger.addHandler(hdlr)
     logger.addHandler(hdlr)
     logger.log_file = log_file
     logger.log_file = log_file
 
 
+    # ---------- 可选:清理旧文件 ----------
+    if do_cleanup:
+        cleanup_logs()
+    if do_cleanup:
+        logger.info("Log cleanup finished")   
+
 
 
 # ======================================================================================================================
 # ======================================================================================================================
 #            Set flutter
 #            Set flutter

+ 23 - 1
script.py

@@ -14,6 +14,8 @@ import inflection
 import asyncio
 import asyncio
 import json
 import json
 
 
+from datetime import date
+import threading
 from typing import Callable
 from typing import Callable
 from datetime import datetime, timedelta
 from datetime import datetime, timedelta
 from pathlib import Path
 from pathlib import Path
@@ -32,6 +34,11 @@ from module.base.decorator import del_cached_property
 from module.logger import logger
 from module.logger import logger
 from module.exception import *
 from module.exception import *
 from module.server.i18n import I18n
 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:
 class Script:
     def __init__(self, config_name: str ='oas') -> None:
     def __init__(self, config_name: str ='oas') -> None:
@@ -402,10 +409,25 @@ class Script:
         Main loop of scheduler.
         Main loop of scheduler.
         :return:
         :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}')
         logger.info(f'Start scheduler loop: {self.config_name}')
 
 
+        # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
+        if not self.config.script.device.run_background_only:
+            target_window_name = self.config.script.device.handle  # 在这里输入你的具体窗口名称
+            if self.config.script.device.emulator_window_minimize:
+                minimize_by_name(target_window_name)
+                logger.info(f'重新显示: {target_window_name}')
+            else:
+                show_window_by_name(target_window_name)
+                
         while 1:
         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
             # Check update event from GUI
             # if self.stop_event is not None:
             # if self.stop_event is not None:
             #     if self.stop_event.is_set():
             #     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_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")
 	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
 	# 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",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "领取奖励"
     "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='契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一 > 远远不够',
     missions_rule: MultiLine = Field(default='契灵 > 觉醒三 > 觉醒二 > 觉醒一 > 御灵三 > 御灵二 > 御灵一 > 御魂二 > 御魂一 > 远远不够',
                                      description='missions_rule_help')
                                      description='missions_rule_help')
     setup_when_bondling: bool = Field(default=True, description='setup_when_bondling_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)
     @validator('missions_rule', pre=True, always=True)
     def mr_validator(cls, v):
     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')
             logger.warning('Today\'s missions have been completed')
             self.set_next_run(task='CollectiveMissions', success=False, finish=True)
             self.set_next_run(task='CollectiveMissions', success=False, finish=True)
             raise TaskEnd('CollectiveMissions')
             raise TaskEnd('CollectiveMissions')
+        #切换为目标任务
+        mission_name = self.config.collective_missions.missions_config.missions_select
+        self.select_mission(mission_name)
         # 判断最优的任务是哪一个
         # 判断最优的任务是哪一个
         mission, index = self.detect_best()
         mission, index = self.detect_best()
         logger.info(f'Best mission is {mission}')
         logger.info(f'Best mission is {mission}')
@@ -277,6 +280,26 @@ class ScriptTask(GameUi, CollectiveMissionsAssets):
         logger.info('Donate finished')
         logger.info('Donate finished')
         return True
         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):
     def _soul(self, index: int):
         """
         """
         搞收御魂的任务
         搞收御魂的任务

+ 0 - 2
tasks/Duel/script_task.py

@@ -221,8 +221,6 @@ class ScriptTask(GameUi, GeneralBattle, DuelAssets):
                 logger.warning('Duel battle stuck, swipe')
                 logger.warning('Duel battle stuck, swipe')
                 self.device.stuck_record_clear()
                 self.device.stuck_record_clear()
                 self.device.stuck_record_add('BATTLE_STATUS_S')
                 self.device.stuck_record_add('BATTLE_STATUS_S')
-
-
         return battle_win
         return battle_win
 
 
 
 

+ 1 - 1
tasks/GameUi/assets.py

@@ -65,7 +65,7 @@ class GameUiAssets:
 	# description 
 	# description 
 	I_CHECK_SOUL_ZONES = RuleImage(roi_front=(49,105,298,405), roi_back=(49,105,298,405), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_soul_zones.png")
 	I_CHECK_SOUL_ZONES = RuleImage(roi_front=(49,105,298,405), roi_back=(49,105,298,405), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_soul_zones.png")
 	# description 
 	# description 
-	I_CHECK_REALM_RAID = RuleImage(roi_front=(113,625,86,77), roi_back=(113,625,86,77), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_realm_raid.png")
+	I_CHECK_REALM_RAID = RuleImage(roi_front=(112,593,86,77), roi_back=(66,526,233,173), threshold=0.7, method="Template matching", file="./tasks/GameUi/page/page_check_realm_raid.png")
 	# description 
 	# description 
 	I_CHECK_GORYOU = RuleImage(roi_front=(881,17,30,39), roi_back=(881,17,30,39), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_goryou.png")
 	I_CHECK_GORYOU = RuleImage(roi_front=(881,17,30,39), roi_back=(881,17,30,39), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_goryou.png")
 	# description 
 	# description 

+ 5 - 4
tasks/GameUi/page/page_img.json

@@ -16,7 +16,8 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "庭院卷轴关闭标识"
     "description": "庭院卷轴关闭标识"
-  },  {
+  },
+  {
     "itemName": "main_goto_exploration",
     "itemName": "main_goto_exploration",
     "imageName": "page_main_goto_exploration.png",
     "imageName": "page_main_goto_exploration.png",
     "roiFront": "493,116,45,75",
     "roiFront": "493,116,45,75",
@@ -154,10 +155,10 @@
   {
   {
     "itemName": "check_realm_raid",
     "itemName": "check_realm_raid",
     "imageName": "page_check_realm_raid.png",
     "imageName": "page_check_realm_raid.png",
-    "roiFront": "113,625,86,77",
-    "roiBack": "113,625,86,77",
+    "roiFront": "112,593,86,77",
+    "roiBack": "66,526,233,173",
     "method": "Template matching",
     "method": "Template matching",
-    "threshold": 0.8,
+    "threshold": 0.7,
     "description": "description"
     "description": "description"
   },
   },
   {
   {

+ 5 - 2
tasks/Script/config_device.py

@@ -70,9 +70,12 @@ class Device(BaseModel):
     emulatorinfo_path: str = Field(default='',
     emulatorinfo_path: str = Field(default='',
                                    description='emulatorinfo_path_help')
                                    description='emulatorinfo_path_help')
     # 举例, E:\ProgramFiles\MuMuPlayer-12.0\shell\MuMuPlayer.exe
     # 举例, E:\ProgramFiles\MuMuPlayer-12.0\shell\MuMuPlayer.exe
-    # 模拟器启动后最小化
+    # 模拟器启动时最小化
     emulator_window_minimize: bool = Field(default=False,
     emulator_window_minimize: bool = Field(default=False,
-                                             description='emulator_window_minimize_help')
+                                             description='模拟器静默启动并最小化')
+    # 启动时纯后台运行模拟器,不显示窗口和任务栏
+    run_background_only: bool = Field(default=False,
+                                             description='模拟器无UI后台运行,关掉后重启脚本会重新显示(无需重启OAS)')