import subprocess
import time
import os
from datetime import datetime
# 配置参数
SCREENSHOT_DIR = "../data/img" # 截图保存目录
SCREENSHOT_NAME = "screenshot.png" # 固定文件名
INTERVAL = 10 # 截图间隔(秒),可修改
def ensure_dir_exists(directory):
"""确保目录存在"""
if not os.path.exists(directory):
os.makedirs(directory)
print(f"创建目录: {directory}")
def take_screenshot():
"""使用ADB截取屏幕并覆盖保存"""
ensure_dir_exists(SCREENSHOT_DIR)
filepath = os.path.join(SCREENSHOT_DIR, SCREENSHOT_NAME)
try:
# 使用ADB截屏并覆盖写入
subprocess.run(
['adb', 'exec-out', 'screencap', '-p'],
stdout=open(filepath, 'wb'),
check=True
)
print(f"截图已保存: {filepath} ({datetime.now().strftime('%H:%M:%S')})")
return True
except Exception as e:
print(f"截图失败: {e}")
return False
def check_adb_connection():
"""检查ADB连接状态"""
try:
result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
return "device" in result.stdout
except FileNotFoundError:
print("ADB未安装或未添加到系统PATH")
return False
def start_emulator(emulator_path):
"""启动雷电模拟器"""
if not os.path.exists(emulator_path):
print(f"雷电模拟器路径不存在: {emulator_path}")
return False
try:
subprocess.Popen([emulator_path])
print("正在启动雷电模拟器...")
time.sleep(30) # 等待模拟器启动
return True
except Exception as e:
print(f"启动模拟器失败: {e}")
return False
def start_mini_hero():
"""启动小小英雄游戏"""
game_package = "com.fx.xxyx" # 更新为实际包名
main_activity = "com.zzjxydcs.union.MainActivity" # 更新为主Activity
try:
# 检查游戏是否已安装
result = subprocess.run(['adb', 'shell', 'pm', 'list', 'packages', game_package],
capture_output=True, text=True)
if game_package not in result.stdout:
print("游戏未安装,请先安装小小英雄")
return False
# 启动游戏
subprocess.run(['adb', 'shell', 'am', 'start', '-n', f"{game_package}/{main_activity}"], check=True)
print("正在启动小小英雄...")
time.sleep(15) # 等待游戏加载
return True
except subprocess.CalledProcessError as e:
print(f"启动游戏失败: {e}")
return False
def auto_open_mini_hero():
"""自动打开小小英雄主流程"""
# 配置参数
LD_PLAYER_PATH = "E:/ld/LDPlayer9/dnplayer.exe" # 修改为你的雷电模拟器路径
# 1. 检查ADB连接
if not check_adb_connection():
print("尝试连接雷电模拟器ADB...")
subprocess.run(['adb', 'connect', '127.0.0.1:5555']) # 雷电默认端口
time.sleep(3)
if not check_adb_connection():
print("ADB连接失败,尝试启动模拟器...")
if not start_emulator(LD_PLAYER_PATH):
return False
# 2. 启动游戏
if not start_mini_hero():
print("尝试重新启动游戏...")
time.sleep(5)
if not start_mini_hero():
return False
print("小小英雄已成功启动!")
return True
if __name__ == '__main__':
print(f"开始定时截图,间隔: {INTERVAL}秒")
print(f"图片将保存为: {os.path.abspath(os.path.join(SCREENSHOT_DIR, SCREENSHOT_NAME))}")
print("按Ctrl+C停止截图...")
print("=== 小小英雄自动启动脚本 ===")
if auto_open_mini_hero():
print("自动启动流程完成!")
try:
while True:
take_screenshot()
time.sleep(INTERVAL)
except KeyboardInterrupt:
print("\n截图任务已停止")
else:
print("自动启动失败,请检查日志")