复古传奇挂机脚本开发全解析

来源: 作者: 点击:
#### 一、游戏自动化脚本开发基础
游戏自动化脚本是通过编程方式模拟玩家操作,实现游戏内任务自动执行的程序。在复古传奇这类MMORPG游戏中,常见的挂机需求包括自动打怪、拾取物品、自动买药、自动回城等重复性操作。

开发游戏脚本通常有两种方式:
1. **内存挂**:直接修改游戏内存数据,这种方式效果显著但容易被检测
2. **模拟操作挂**:通过模拟鼠标键盘操作实现自动化,安全性较高

本文将使用Python开发一个基于图像识别和键鼠模拟的复古传奇挂机脚本,这种方式兼容性强且不容易被游戏检测。

#### 二、脚本核心功能模块设计

一个完整的复古传奇挂机脚本通常包含以下核心模块:

1. **游戏窗口管理模块**
2. **图像识别模块**
3. **键鼠操作模拟模块**
4. **战斗逻辑模块**
5. **物品管理模块**
6. **状态监控模块**
7. **主控制循环**

下面是一个基础挂机脚本的实现框架:

```python
import pyautogui
import cv2
import numpy as np
import time
import win32gui
import win32con
import random
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class LegendAutoScript:
def __init__(self):
# 游戏窗口信息
self.game_window_title = "复古传奇" # 游戏窗口标题
self.game_hwnd = None
self.game_rect = None

# 配置参数
self.safe_hp_percent = 30 # 安全血量百分比,低于此值自动回城
self.safe_mp_percent = 20 # 安全魔法值百分比
self.battle_interval = (1.0, 2.0) # 攻击间隔范围(秒)
self.pick_interval = 3.0 # 拾取间隔(秒)

# 物品识别参数
self.item_templates = {
"金币": cv2.imread("items/gold.png", 0),
"药水": cv2.imread("items/potion.png", 0),
"装备": cv2.imread("items/equipment.png", 0)
}

# 状态变量
self.is_running = False
self.last_pick_time = 0
self.last_attack_time = 0
self.current_hp = 100
self.current_mp = 100

def find_game_window(self):
"""查找游戏窗口并获取窗口信息"""
self.game_hwnd = win32gui.FindWindow(None, self.game_window_title)
if not self.game_hwnd:
logger.error(f"未找到游戏窗口: {self.game_window_title}")
return False

# 获取窗口位置和大小
rect = win32gui.GetWindowRect(self.game_hwnd)
self.game_rect = (rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1])
logger.info(f"找到游戏窗口: {self.game_window_title}, 位置: {self.game_rect}")

# 激活游戏窗口
win32gui.SetForegroundWindow(self.game_hwnd)
time.sleep(0.5) # 等待窗口激活

return True

def capture_game_screen(self):
"""截取游戏窗口画面"""
if not self.game_hwnd:
return None

# 获取窗口位置
left, top, width, height = self.game_rect

# 截取屏幕
screenshot = pyautogui.screenshot(region=(left, top, width, height))
return cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

def find_template_on_screen(self, template, threshold=0.8):
"""在屏幕上查找模板图像"""
screen = self.capture_game_screen()
if screen is None:
return None

# 转换为灰度图
screen_gray = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)

# 模板匹配
result = cv2.matchTemplate(screen_gray, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

# 如果匹配度大于阈值,返回位置
if max_val >= threshold:
h, w = template.shape
center_x = max_loc[0] + w // 2
center_y = max_loc[1] + h // 2
return (center_x, center_y, max_val)

return None

def recognize_hp_mp(self):
"""识别当前角色的血量和魔法值"""
# 这里需要根据游戏界面自定义实现
# 可以通过截取血条和魔法条区域,分析颜色来确定百分比
# 简化实现,实际使用时需要根据游戏界面调整
screen = self.capture_game_screen()
if screen is None:
return

# 假设已经知道血条和魔法条的位置区域
hp_bar_region = screen[50:55, 100:200] # 示例区域,需要根据实际游戏调整
mp_bar_region = screen[60:65, 100:200] # 示例区域,需要根据实际游戏调整

# 计算血量百分比 (通过分析红色通道)
hp_pixels = cv2.inRange(hp_bar_region, (0, 0, 100), (100, 100, 255))
self.current_hp = (np.count_nonzero(hp_pixels) / hp_pixels.size) * 100

# 计算魔法值百分比 (通过分析蓝色通道)
mp_pixels = cv2.inRange(mp_bar_region, (100, 0, 0), (255, 100, 100))
self.current_mp = (np.count_nonzero(mp_pixels) / mp_pixels.size) * 100

logger.debug(f"当前血量: {self.current_hp:.1f}%, 魔法值: {self.current_mp:.1f}%")

def attack_monster(self):
"""攻击怪物"""
# 查找怪物 (这里简化为随机点击游戏区域)
if not self.game_rect:
return

left, top, width, height = self.game_rect

# 计算攻击区域 (避开UI部分)
attack_area = (int(width * 0.2), int(height * 0.2),
int(width * 0.6), int(height * 0.6))

# 在攻击区域内随机选择一个点
x = left + attack_area[0] + random.randint(0, attack_area[2])
y = top + attack_area[1] + random.randint(0, attack_area[3])

# 移动鼠标并点击
pyautogui.moveTo(x, y, duration=0.2 + random.random() * 0.3)
pyautogui.click()

# 记录攻击时间
self.last_attack_time = time.time()
logger.info(f"攻击怪物,位置: ({x}, {y})")

# 模拟攻击间隔
interval = random.uniform(*self.battle_interval)
time.sleep(interval)

def pick_items(self):
"""拾取物品"""
# 只在设定的间隔时间执行拾取
current_time = time.time()
if current_time - self.last_pick_time < self.pick_interval:
return

logger.info("开始搜索可拾取物品...")

# 遍历所有物品模板进行查找
for item_name, template in self.item_templates.items():
location = self.find_template_on_screen(template, threshold=0.7)
if location:
x, y, confidence = location
# 转换为屏幕坐标
screen_x = self.game_rect[0] + x
screen_y = self.game_rect[1] + y

# 移动到物品位置并拾取
pyautogui.moveTo(screen_x, screen_y, duration=0.2 + random.random() * 0.3)
pyautogui.press('space') # 假设空格键是拾取键
logger.info(f"发现{item_name},正在拾取,位置: ({screen_x}, {screen_y}),匹配度: {confidence:.2f}")

# 拾取后稍作等待
time.sleep(0.5 + random.random() * 0.5)

# 更新拾取时间
self.last_pick_time = current_time

def use_healing_potion(self):
"""使用治疗药水"""
logger.info("血量过低,使用治疗药水")
# 假设F1键是使用药水的快捷键
pyautogui.press('f1')
time.sleep(0.5) # 等待药水效果

def return_to_town(self):
"""返回城镇"""
logger.info("状态不佳,返回城镇")
# 假设F2键是回城快捷键
pyautogui.press('f2')
# 等待回城动画
time.sleep(10 + random.random() * 3)

def main_loop(self):
"""主循环,控制整个脚本的运行逻辑"""
if not self.find_game_window():
return

self.is_running = True
logger.info("脚本开始运行,按Ctrl+C终止")

try:
while self.is_running:
# 识别当前状态
self.recognize_hp_mp()

# 检查是否需要使用药水或回城
if self.current_hp < self.safe_hp_percent:
if self.current_hp < 10: # 极低血量,直接回城
self.return_to_town()
else:
self.use_healing_potion()
elif self.current_mp < self.safe_mp_percent:
# 魔法值不足,回城
self.return_to_town()
else:
# 正常战斗状态
self.attack_monster()
self.pick_items()

# 随机延迟,避免操作过于规律
delay = random.uniform(0.3, 0.7)
time.sleep(delay)

except KeyboardInterrupt:
logger.info("用户中断,脚本停止运行")
finally:
self.is_running = False

# 脚本入口
if __name__ == "__main__":
script = LegendAutoScript()
script.main_loop()
```

#### 三、脚本实现详细解析

1. **游戏窗口管理**
- 通过Windows API查找和管理游戏窗口
- 获取窗口位置和大小,确保操作精确

2. **图像识别系统**
- 使用OpenCV实现基于模板匹配的图像识别
- 识别游戏中的怪物、物品、血条等元素
- 通过调整匹配阈值控制识别精度

3. **键鼠操作模拟**
- 使用PyAutoGUI库模拟鼠标移动和点击
- 模拟键盘按键操作,如技能释放、拾取等
- 添加随机延迟,使操作更接近人类行为

4. **智能战斗逻辑**
- 自动识别和攻击怪物
- 血量和魔法值监控,低于安全值自动使用药水或回城
- 实现物品自动拾取系统

5. **安全机制**
- 添加随机延迟避免操作规律被检测
- 状态异常自动处理,如极低血量直接回城
- 完善的日志系统,便于调试和监控

#### 四、脚本使用和优化建议

1. **使用方法**
- 安装必要的库:`pip install pyautogui opencv-python numpy pywin32`
- 准备物品模板图片,放入items目录
- 根据游戏实际情况调整参数,如窗口标题、安全值等
- 运行脚本,确保游戏窗口可见

2. **优化建议**
- 针对特定游戏版本调整图像识别参数
- 添加更多物品模板,提高拾取准确性
- 实现技能释放逻辑,根据怪物类型使用不同技能
- 添加自动任务功能,实现更复杂的游戏自动化

3. **注意事项**
- 使用脚本可能违反游戏用户协议,有被封号风险,请谨慎使用
- 建议不要长时间连续运行脚本,避免被检测
- 定期检查脚本运行情况,确保正常工作

这个脚本框架提供了基本的挂机功能,你可以根据实际游戏情况进行调整和扩展,添加更多个性化功能,如自动任务、自动交易等。