# Mineflayer全栈开发指南:构建Minecraft智能自动化系统
Mineflayer作为Node.js环境下的Minecraft机器人框架,为开发者提供了构建智能自动化系统的完整工具链。通过编程控制游戏内实体行为,可以实现从基础导航到复杂决策的全栈自动化解决方案。
## 环境配置与基础连接
Mineflayer项目的初始设置需要确保正确的依赖环境:
```javascript
// package.json 核心依赖配置
{
"name": "mineflayer-bot",
"version": "1.0.0",
"dependencies": {
"mineflayer": "^4.8.0",
"mineflayer-pathfinder": "^2.4.5",
"mineflayer-collectblock": "^1.4.0",
"mineflayer-pvp": "^1.0.0",
"vec3": "^0.1.7"
},
"scripts": {
"start": "node bot.js",
"dev": "nodemon bot.js"
}
}
```
基础机器人连接与事件处理:
```javascript
const mineflayer = require('mineflayer');
const pathfinder = require('mineflayer-pathfinder');
// 创建机器人实例
function createBot(options) {
const bot = mineflayer.createBot({
host: options.host || 'localhost',
port: options.port || 25565,
username: options.username || 'AutomationBot',
version: options.version || '1.18.2',
auth: options.auth || 'offline'
});
// 加载路径查找插件
bot.loadPlugin(pathfinder.pathfinder);
// 基础事件监听
bot.on('login', () => {
console.log(`${bot.username} 已登录到服务器`);
bot.chat('/register 密码 密码'); // 如有需要
});
bot.on('spawn', () => {
console.log(`${bot.username} 已在世界重生`);
bot.chat('机器人已就绪');
});
bot.on('death', () => {
console.log(`${bot.username} 已死亡`);
});
bot.on('kicked', (reason) => {
console.log(`被踢出服务器: ${reason}`);
});
bot.on('error', (err) => {
console.error(`机器人错误: ${err.message}`);
});
return bot;
}
// 使用示例
const bot = createBot({
host: 'mc.example.com',
username: 'MiningBot_v1'
});
```
## 智能导航与路径规划
路径规划是自动化系统的核心功能:
```javascript
const { GoalNear, Movements } = require('mineflayer-pathfinder');
class NavigationSystem {
constructor(bot) {
this.bot = bot;
this.movements = new Movements(bot);
this.configureMovements();
}
configureMovements() {
// 配置移动参数
this.movements.canDig = true;
this.movements.allowParkour = true;
this.movements.allowSprinting = true;
this.movements.blocksToAvoid = new Set([
this.bot.registry.blocksByName.lava.id,
this.bot.registry.blocksByName.cactus.id
]);
this.bot.pathfinder.setMovements(this.movements);
}
async moveToPosition(x, y, z, range = 1) {
const goal = new GoalNear(x, y, z, range);
return new Promise((resolve, reject) => {
this.bot.pathfinder.goto(goal, (err) => {
if (err) {
console.error(`导航到 (${x}, ${y}, ${z}) 失败: ${err.message}`);
reject(err);
} else {
console.log(`已到达位置 (${x}, ${y}, ${z})`);
resolve();
}
});
});
}
async findPathToEntity(entityName, maxDistance = 32) {
const entity = this.bot.nearestEntity(
entity => entity.name === entityName &&
this.bot.entity.position.distanceTo(entity.position) < maxDistance
);
if (!entity) {
throw new Error(`附近未找到 ${entityName}`);
}
const { x, y, z } = entity.position.floored();
return this.moveToPosition(x, y, z);
}
async patrolRoute(waypoints, delay = 2000) {
for (const waypoint of waypoints) {
await this.moveToPosition(waypoint.x, waypoint.y, waypoint.z);
await this.wait(delay);
}
}
wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// 导航系统使用示例
const navigation = new NavigationSystem(bot);
bot.on('spawn', async () => {
// 移动到指定坐标
await navigation.moveToPosition(100, 64, 200);
// 巡逻路线
const patrolPoints = [
{ x: 100, y: 64, z: 200 },
{ x: 120, y: 64, z: 180 },
{ x: 80, y: 64, z: 160 }
];
await navigation.patrolRoute(patrolPoints);
});
```
## 资源采集自动化
自动化资源采集需要结合物品识别和工具管理:
```javascript
const collectBlock = require('mineflayer-collectblock');
class ResourceCollector {
constructor(bot) {
this.bot = bot;
this.bot.loadPlugin(collectBlock.plugin);
this.collectBlock = this.bot.collectBlock;
}
async collectBlocks(blockNames, count = 64) {
const blocks = blockNames.map(name =>
this.bot.registry.blocksByName[name]
).filter(Boolean);
if (blocks.length === 0) {
throw new Error('未找到指定的方块类型');
}
let collected = 0;
const results = [];
while (collected < count) {
// 查找最近的指定方块
const block = this.bot.findBlock({
matching: blocks.map(b => b.id),
maxDistance: 32,
count: count - collected
});
if (!block) {
console.log('附近没有更多目标方块');
break;
}
try {
// 收集方块
const collectedItems = await this.collectBlock.collect(block);
collected += collectedItems.length;
results.push({
block: block.name,
position: block.position,
count: collectedItems.length
});
console.log(`已收集 ${collected}/${count} 个方块`);
// 短暂延迟避免服务器压力
await this.wait(500);
} catch (err) {
console.error(`收集方块失败: ${err.message}`);
break;
}
}
return results;
}
async smartMining(veinBlocks, toolPreferences) {
// 智能采矿:识别矿脉并选择合适工具
const blocks = veinBlocks.map(name =>
this.bot.registry.blocksByName[name]
);
// 查找矿脉
const vein = this.findVein(blocks, 16);
if (!vein) {
throw new Error('未发现矿脉');
}
console.log(`发现矿脉,包含 ${vein.length} 个方块`);
// 装备合适工具
await this.equipBestTool(blocks[0], toolPreferences);
// 采集矿脉
for (const block of vein) {
await this.mineBlock(block);
await this.wait(200); // 控制采集速度
}
}
findVein(blockTypes, radius) {
const center = this.bot.entity.position.floored();
const vein = [];
const visited = new Set();
const dfs = (pos) => {
const key = `${pos.x},${pos.y},${pos.z}`;
if (visited.has(key)) return;
visited.add(key);
const block = this.bot.blockAt(pos);
if (block && blockTypes.some(type => type.id === block.type)) {
vein.push(block);
// 检查相邻方块
const directions = [
{ x: 1, y: 0, z: 0 }, { x: -1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 }, { x: 0, y: -1, z: 0 },
{ x: 0, y: 0, z: 1 }, { x: 0, y: 0, z: -1 }
];
for (const dir of directions) {
const neighborPos = pos.offset(dir.x, dir.y, dir.z);
if (center.distanceTo(neighborPos) <= radius) {
dfs(neighborPos);
}
}
}
};
dfs(center);
return vein;
}
async equipBestTool(blockType, preferences) {
// 根据方块类型选择最佳工具
const tools = this.bot.inventory.items()
.filter(item => preferences.some(pref => item.name.includes(pref)));
if (tools.length > 0) {
const bestTool = tools.reduce((best, current) => {
// 简单的工具选择逻辑,可根据耐久度、附魔等优化
return current.name.includes('diamond') ? current : best;
}, tools[0]);
await this.bot.equip(bestTool, 'hand');
console.log(`已装备 ${bestTool.name}`);
}
}
async mineBlock(block) {
return new Promise((resolve, reject) => {
this.bot.dig(block, (err) => {
if (err) reject(err);
else resolve();
});
});
}
wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// 资源采集示例
const collector = new ResourceCollector(bot);
bot.on('spawn', async () => {
// 收集木材
await collector.collectBlocks(['oak_log', 'spruce_log'], 32);
// 智能采矿
await collector.smartMining(
['coal_ore', 'iron_ore', 'gold_ore'],
['pickaxe', 'shovel']
);
});
```
## 物品管理与库存优化
高效的库存管理是长期运行的关键:
```javascript
class InventoryManager {
constructor(bot) {
this.bot = bot;
this.storageLocations = new Map(); // 存储位置缓存
}
async organizeInventory(categories) {
// 按类别整理物品
const items = this.bot.inventory.items();
const chestLocation = this.storageLocations.get('main_storage');
if (!chestLocation) {
console.log('未设置主存储位置');
return;
}
for (const [category, itemNames] of Object.entries(categories)) {
const categoryItems = items.filter(item =>
itemNames.some(name => item.name.includes(name))
);
if (categoryItems.length > 0) {
await this.storeItems(categoryItems, chestLocation);
console.log(`已存储 ${category}: ${categoryItems.length} 组物品`);
}
}
}
async storeItems(items, chestPos) {
// 移动到箱子位置
const { x, y, z } = chestPos;
await this.bot.pathfinder.goto(new GoalNear(x, y, z, 2));
// 查找箱子
const chestBlock = this.bot.findBlock({
matching: this.bot.registry.blocksByName.chest.id,
maxDistance: 3
});
if (!chestBlock) {
throw new Error('未找到箱子');
}
// 打开箱子
const chest = await this.bot.openContainer(chestBlock);
// 存入物品
for (const item of items) {
if (item.slot >= 36) continue; // 跳过装备槽
await this.depositItem(chest, item);
await this.wait(100); // 避免过快操作
}
chest.close();
}
async depositItem(container, item) {
return new Promise((resolve, reject) => {
container.deposit(item.type, null, item.count, (err) => {
if (err) reject(err);
else resolve();
});
});
}
async autoRefuel(minFuel = 64) {
// 自动补充燃料
const fuelItems = this.bot.inventory.items().filter(item =>
['coal', 'charcoal', 'lava_bucket'].includes(item.name)
);
if (fuelItems.length === 0) {
console.log('没有可用燃料');
return false;
}
const currentFuel = this.bot.currentFuel || 0;
if (currentFuel > minFuel) return true;
const bestFuel = fuelItems.reduce((best, current) => {
// 选择燃烧时间最长的燃料
const fuelValues = {
'coal': 800, 'charcoal': 800, 'lava_bucket': 20000
};
return fuelValues[current.name] > fuelValues[best.name] ? current : best;
}, fuelItems[0]);
await this.bot.equip(bestFuel, 'hand');
await this.bot.activateItem();
console.log(`已添加燃料: ${bestFuel.name}`);
return true;
}
async craftItems(recipe, amount = 1) {
// 自动化合成
const items = this.bot.inventory.items();
// 检查材料是否充足
const hasMaterials = recipe.ingredients.every(ingredient =>
items.some(item =>
item.name === ingredient.name &&
item.count >= ingredient.count * amount
)
);
if (!hasMaterials) {
throw new Error('材料不足');
}
// 移动到工作台
const workbench = this.storageLocations.get('workbench');
if (workbench) {
await this.bot.pathfinder.goto(new GoalNear(
workbench.x, workbench.y, workbench.z, 2
));
}
// 执行合成
const craftingTable = this.bot.findBlock({
matching: this.bot.registry.blocksByName.crafting_table.id,
maxDistance: 3
});
if (craftingTable) {
const table = await this.bot.openCraftingTable(craftingTable);
for (let i = 0; i < amount; i++) {
await table.craft(recipe.id, recipe.count, null);
await this.wait(500);
}
table.close();
} else {
// 使用背包合成
await this.bot.craft(recipe.id, recipe.count, null);
}
console.log(`已合成 ${amount} 个 ${recipe.output}`);
}
wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// 库存管理示例
const inventory = new InventoryManager(bot);
// 配置存储分类
const itemCategories = {
'ores': ['_ore', 'raw_'],
'woods': ['_log', '_planks'],
'foods': ['_steak', 'bread', 'apple'],
'tools': ['_pickaxe', '_axe', '_shovel']
};
bot.on('spawn', async () => {
// 设置存储位置
inventory.storageLocations.set('main_storage', { x: 100, y: 64, z: 200 });
inventory.storageLocations.set('workbench', { x: 102, y: 64, z: 200 });
// 自动整理库存
setInterval(async () => {
await inventory.organizeInventory(itemCategories);
await inventory.autoRefuel();
}, 300000); // 每5分钟执行一次
});
```
## 战斗系统与威胁响应
智能战斗系统确保机器人的生存能力:
```javascript
const pvp = require('mineflayer-pvp');
class CombatSystem {
constructor(bot) {
this.bot = bot;
this.bot.loadPlugin(pvp.plugin);
this.target = null;
this.defensiveMode = false;
}
async engageNearestHostile(maxDistance = 16) {
const hostile = this.bot.nearestEntity(entity => {
return this.isHostile(entity) &&
this.bot.entity.position.distanceTo(entity.position) < maxDistance;
});
if (!hostile) return false;
this.target = hostile;
await this.bot.pvp.attack(hostile);
console.log(`正在攻击 ${hostile.name}`);
return true;
}
isHostile(entity) {
const hostileTypes = [
'zombie', 'skeleton', 'spider', 'creeper',
'enderman', 'witch', 'pillager'
];
return hostileTypes.some(type => entity.name.includes(type));
}
async defensiveBehavior() {
this.defensiveMode = true;
// 撤退到安全位置
const safeHouse = this.getSafeLocation();
if (safeHouse) {
await this.retreatTo(safeHouse);
}
// 治疗和恢复
await this.healIfNeeded();
// 设置防御姿态
this.bot.setControlState('sneak', true);
setTimeout(() => {
this.defensiveMode = false;
this.bot.setControlState('sneak', false);
}, 10000);
}
getSafeLocation() {
// 从记忆或配置中获取安全位置
return { x: 100, y: 64, z: 200 };
}
async retreatTo(position) {
const { x, y, z } = position;
const goal = new GoalNear(x, y, z, 2);
return new Promise((resolve) => {
this.bot.pathfinder.goto(goal, () => {
console.log('已撤退到安全位置');
resolve();
});
});
}
async healIfNeeded() {
const health = this.bot.health;
if (health < 10) {
const food = this.bot.inventory.items().find(item =>
['golden_apple', 'cooked_beef', 'bread'].includes(item.name)
);
if (food) {
await this.bot.equip(food, 'hand');
await this.bot.consume();
console.log(`已使用 ${food.name} 恢复生命`);
}
}
}
setupCombatListeners() {
this.bot.on('entityHurt', (entity) => {
if (entity === this.bot.entity) {
console.log(`受到攻击,生命值: ${this.bot.health}`);
if (this.bot.health < 8 && !this.defensiveMode) {
this.defensiveBehavior();
}
}
});
this.bot.on('entityGone', (entity) => {
if (entity === this.target) {
console.log(`目标 ${entity.name} 已消失`);
this.target = null;
}
});
}
}
// 战斗系统集成
const combat = new CombatSystem(bot);
combat.setupCombatListeners();
// 自动巡逻与防御
setInterval(async () => {
<"1a.csxthr.com"><"4e.zhaiLimao.com"><"8b.yunruiwater.cn">
if (!combat.target && !combat.defensiveMode) {
const engaged = await combat.engageNearestHostile();
if (!engaged) {
// 执行巡逻任务
await navigation.patrolRoute([
{ x: 100, y: 64, z: 200 },
{ x: 120, y: 64, z: 220 },
{ x: 80, y: 64, z: 180 }
]);
}
}
}, 5000);
```
## 任务调度与状态管理
完整的自动化系统需要任务调度机制:
```javascript
class TaskScheduler {
constructor(bot) {
this.bot = bot;
this.tasks = new Map();
this.currentTask = null;
this.taskQueue = [];
this.isRunning = false;
}
registerTask(name, taskFunction, priority = 1) {
this.tasks.set(name, {
execute: taskFunction,
priority,
lastRun: null,
successCount: 0,
failureCount: 0
});
}
async scheduleTask(name, ...args) {
const task = this.tasks.get(name);
if (!task) {
throw new Error(`任务 ${name} 未注册`);
}
this.taskQueue.push({
name,
args,
priority: task.priority,
timestamp: Date.now()
});
// 按优先级排序
this.taskQueue.sort((a, b) => b.priority - a.priority);
if (!this.isRunning) {
this.processQueue();
}
}
async processQueue() {
this.isRunning = true;
while (this.taskQueue.length > 0) {
const taskItem = this.taskQueue.shift();
const task = this.tasks.get(taskItem.name);
this.currentTask = taskItem.name;
try {
console.log(`开始执行任务: ${taskItem.name}`);
await task.execute(this.bot, ...taskItem.args);
task.lastRun = Date.now();
task.successCount++;
console.log(`任务 ${taskItem.name} 完成`);
} catch (error) {
task.failureCount++;
console.error(`任务 ${taskItem.name} 失败: ${error.message}`);
// 失败重试逻辑
if (task.failureCount < 3) {
console.log(`将在30秒后重试 ${taskItem.name}`);
setTimeout(() => {
this.scheduleTask(taskItem.name, ...taskItem.args);
}, 30000);
}
}
await this.wait(1000); // 任务间隔
}
this.currentTask = null;
this.isRunning = false;
}
getTaskStatus() {
const status = {
current: this.currentTask,
queued: this.taskQueue.length,
tasks: {}
};
for (const [name, task] of this.tasks) {
status.tasks[name] = {
priority: task.priority,
lastRun: task.lastRun,
successCount: task.successCount,
failureCount: task.failureCount
};
}
return status;
}
wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// 任务调度器集成
const scheduler = new TaskScheduler(bot);
// 注册任务
scheduler.registerTask('collect_wood', async (bot) => {
const collector = new ResourceCollector(bot);
await collector.collectBlocks(['oak_log', 'birch_log'], 16);
}, 2);
scheduler.registerTask('mine_ores', async (bot) => {
const collector = new ResourceCollector(bot);
await collector.smartMining(
['coal_ore', 'iron_ore'],
['pickaxe']
);
}, 3);
scheduler.registerTask('store_items', async (bot) => {
const inventory = new InventoryManager(bot);
await inventory.organizeInventory(itemCategories);
}, 1);
// 定时执行任务
setInterval(() => {
scheduler.scheduleTask('collect_wood');
scheduler.scheduleTask('mine_ores');
scheduler.scheduleTask('store_items');
}, 600000); // 每10分钟执行一次
// 监控系统状态
setInterval(() => {
const status = scheduler.getTaskStatus();
console.log('系统状态:', JSON.stringify(status, null, 2));
// 报告机器人状态
console.log(`位置: ${bot.entity.position}`);
console.log(`生命值: ${bot.health}`);
console.log(`饥饿值: ${bot.food}`);
}, 300000); // 每5分钟报告一次
```
## 错误处理与恢复机制
健壮的系统需要完善的错误处理:
```javascript
class RecoverySystem {
constructor(bot) {
this.bot = bot;
this.errorCount = 0;
this.maxErrors = 5;
this.lastErrorTime = 0;
}
async handleError(error, context) {
console.error(`[${context}] 错误: ${error.message}`);
console.error(error.stack);
this.errorCount++;
this.lastErrorTime = Date.now();
// 错误过多时执行恢复
if (this.errorCount >= this.maxErrors) {
console.log('错误过多,执行系统恢复');
await this.performRecovery();
this.errorCount = 0;
}
// 记录错误
this.logError(error, context);
}
async performRecovery() {
console.log('开始系统恢复流程');
try {
// 1. 尝试回到重生点
await this.returnToSpawn();
// 2. 检查物品和状态
await this.checkInventory();
// 3. 重置机器人状态
this.resetBotState();
console.log('系统恢复完成');
} catch (recoveryError) {
console.error('系统恢复失败:', recoveryError.message);
// 如果恢复失败,可能需要重启机器人
}
}
async returnToSpawn() {
console.log('返回重生点');
// 实现返回重生点的逻辑
}
async checkInventory() {
const items = this.bot.inventory.items();
console.log(`当前携带 ${items.length} 组物品`);
// 检查重要物品
const essentials = ['iron_pickaxe', 'stone_sword', 'cooked_beef'];
for (const item of essentials) {
const hasItem = items.some(i => i.name.includes(item));
if (!hasItem) {
console.log(`缺少重要物品: ${item}`);
}
}
}
resetBotState() {
// 重置机器人控制状态
['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak'].forEach(control => {
this.bot.setControlState(control, false);
});
this.bot.clearControlStates();
console.log('机器人状态已重置');
}
logError(error, context) {
// 实现错误日志记录
const logEntry = {
timestamp: new Date().toISOString(),
context,
message: error.message,
stack: error.stack
};
// 可以保存到文件或发送到监控服务
console.log('错误已记录:', logEntry);
}
resetErrorCount() {
// 定期重置错误计数
const now = Date.now();
if (now - this.lastErrorTime > 3600000) { // 1小时
this.errorCount = 0;
console.log('错误计数已重置');
}
}
}
// 集成错误恢复系统
const recovery = new RecoverySystem(bot);
// 全局错误处理
process.on('unhandledRejection', (error) => {
recovery.handleError(error, 'unhandledRejection');
});
process.on('uncaughtException', (error) => {
recovery.handleError(error, 'uncaughtException');
});
// 定期重置错误计数
setInterval(() => {
recovery.resetErrorCount();
}, 1800000); // 每30分钟执行一次
```
## 系统集成与部署
完整的自动化系统需要模块化集成:
```javascript
// main.js - 主系统集成
const mineflayer = require('mineflayer');
const { NavigationSystem, ResourceCollector, InventoryManager,
CombatSystem, TaskScheduler, RecoverySystem } = require('./systems');
class MinecraftAutomationSystem {
constructor(config) {
this.config = config;
this.bot = this.createBot();
this.modules = {};
this.initializeModules();
this.setupEventHandlers();
}
createBot() {
return mineflayer.createBot({
host: this.config.host,
port: this.config.port,
username: this.config.username,
version: this.config.version,
auth: this.config.auth
});
}
initializeModules() {
// 初始化所有模块
this.modules.navigation = new NavigationSystem(this.bot);
this.modules.collector = new ResourceCollector(this.bot);
this.modules.inventory = new InventoryManager(this.bot);
this.modules.combat = new CombatSystem(this.bot);
this.modules.scheduler = new TaskScheduler(this.bot);
this.modules.recovery = new RecoverySystem(this.bot);
// 注册任务
this.registerTasks();
}
registerTasks() {
this.modules.scheduler.registerTask('daily_mining', async () => {
await this.modules.collector.smartMining(
['coal_ore', 'iron_ore', 'diamond_ore'],
['diamond_pickaxe', 'iron_pickaxe']
);
}, 3);
this.modules.scheduler.registerTask('farm_management', async () => {
// 农场管理任务
await this.manageFarm();
}, 2);
this.modules.scheduler.registerTask('base_defense', async () => {
await this.modules.combat.engageNearestHostile(32);
}, 4);
}
async manageFarm() {
// 实现农场管理逻辑
console.log('执行农场管理');
// 种植、收割等操作
}
setupEventHandlers() {
this.bot.on('spawn', async () => {
console.log('自动化系统启动');
// 启动任务调度
this.startScheduledTasks();
// 执行初始化任务
await this.initializeBase();
});
this.bot.on('death', () => {
console.log('机器人死亡,等待重生');
this.modules.scheduler.processQueue(); // 暂停任务处理
});
this.bot.on('health', () => {
if (this.bot.health < 10) {
this.modules.combat.defensiveBehavior();
}
});
}
startScheduledTasks() {
// 定时执行各种任务
setInterval(() => {
this.modules.scheduler.scheduleTask('daily_mining');
}, 7200000); // 每2小时
setInterval(() => {
this.modules.scheduler.scheduleTask('farm_management');
}, 3600000); // 每小时
setInterval(() => {
this.modules.scheduler.scheduleTask('base_defense');
}, 30000); // 每30秒
}
async initializeBase() {
console.log('初始化基地');
// 确保有基本工具
await this.ensureBasicTools();
// 设置存储位置
this.modules.inventory.storageLocations.set('main_chest',
{ x: 100, y: 64, z: 200 });
// 首 次资源收集
await this.modules.scheduler.scheduleTask('daily_mining');
}
async ensureBasicTools() {
// 确保有基本工具
const tools = ['wooden_pickaxe', 'stone_sword', 'wooden_axe'];
const inventory = this.bot.inventory.items();
for (const tool of tools) {
if (!inventory.some(item => item.name.includes(tool))) {
console.log(`缺少 ${tool},尝试合成`);
// 合成逻辑
}
}
}
getSystemStatus() {
return {
bot: {
username: this.bot.username,
health: this.bot.health,
food: this.bot.food,
position: this.bot.entity.position
},
modules: Object.keys(this.modules).reduce((acc, key) => {
if (this.modules[key].getStatus) {
acc[key] = this.modules[key].getStatus();
}
return acc;
}, {}),
tasks: this.modules.scheduler.getTaskStatus()
};
}
}
// 系统启动
const config = {
host: 'localhost',
port: 25565,
username: 'AutoFarmer_v2',
version: '1.18.2',
auth: 'offline'
};
const automationSystem = new MinecraftAutomationSystem(config);
// 系统监控端点
const express = require('express');
const app = express();
const PORT = 3000;
app.get('/status', (req, res) => {
res.json(automationSystem.getSystemStatus());
<"2j.sxyicheng.cn"><"5l.jsnjz.cn"><"9s.csxthr.com">
});
app.get('/tasks/:taskName/run', async (req, res) => {
try {
await automationSystem.modules.scheduler.scheduleTask(req.params.taskName);
res.json({ success: true });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
app.listen(PORT, () => {
console.log(`系统监控运行在 http://localhost:${PORT}`);
});
```
通过Mineflayer构建的Minecraft自动化系统展示了全栈开发在游戏自动化中的应用。从基础连接到复杂任务调度,每个模块都解决特定问题。系统设计考虑了扩展性和健壮性,模块化架构允许根据需要添加新功能。这种自动化方法不仅适用于游戏,其任务调度、错误恢复和状态管理理念也可应用于其他机器人流程自动化场景。