Помощь миновых жителей с блочными взаимодействиямиJavascript

Форум по Javascript
Ответить
Anonymous
 Помощь миновых жителей с блочными взаимодействиями

Сообщение Anonymous »

Я пытаюсь создать бот Minecraft Mineflayer, который загружает Ender Pearls в камеры Pearl Stasis, заставляя его взаимодействовать с люком в координатах, которые указаны в базе данных Postgres. Я много пробовал, но это не меняет состояние люка. Вот мой код. Есть предложения? < /P>
import mineflayer from 'mineflayer';
import pathfinderPkg from 'mineflayer-pathfinder';
const { pathfinder, Movements, goals } = pathfinderPkg;

import pg from 'pg';
import fetch from 'node-fetch';
import { Vec3 } from 'vec3';
import mcData from 'minecraft-data';

const { Client } = pg;
const { GoalNear } = goals;

const BOT_CONFIG = {
host: 'localhost',
port: 25565,
username: '33_x',
auth: 'microsoft',
version: '1.21.4',
dbConfig: {
user: 'postgres',
host: 'localhost',
database: 'remotepearl',
password: 'postgres',
port: 5432,
},
tableName: 'accounts',
columnUUID: 'uuid',
columnX: 'x',
columnY: 'y',
columnZ: 'z',
columnWorld: 'world',
TPLookupCommand: '?tp',
ActivationRetryCount: 3,
ActivationRetryDelay: 1500,
TrapdoorSearchRadius: 3,
AntiAFKSneakInterval: 10000,
AntiAFKSneakDuration: 500,
};

const taskQueue = [];
let isProcessingTask = false;

function addTask(task) {
taskQueue.push(task);
processQueue();
}

async function processQueue() {
if (isProcessingTask || taskQueue.length === 0) return;
isProcessingTask = true;
const task = taskQueue.shift();
try {
await task();
} catch (error) {
console.error('Task failed:', error);
} finally {
isProcessingTask = false;
processQueue();
}
}

async function getUuidFromUsername(username) {
try {
const response = await fetch(`https://api.mojang.com/users/profiles/m ... ${username}`);
if (!response.ok) return null;
const data = await response.json();
return data?.id;
} catch {
return null;
}
}

async function retryOperation(func, maxRetries, delayMs) {
for (let i = 0; i < maxRetries; i++) {
try {
return await func();
} catch (error) {
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, delayMs));
} else {
throw error;
}
}
}
}

function getNearbyTrapdoor(center, range) {
for (let dx = -range; dx {
if (username === bot.username) return;
const args = message.trim().split(' ');
const command = args[0];
const targetPlayer = args[1];
if (command === BOT_CONFIG.TPLookupCommand && targetPlayer) {
addTask(() => handleTpCommand(username, targetPlayer));
}
});

function startAntiAFK() {
setInterval(() => {
if (!isProcessingTask) {
bot.setControlState('sneak', true);
setTimeout(() => bot.setControlState('sneak', false), BOT_CONFIG.AntiAFKSneakDuration);
}
}, BOT_CONFIG.AntiAFKSneakInterval);
}

async function handleTpCommand(requesterName, targetName) {
const dbClient = new Client(BOT_CONFIG.dbConfig);
try {
const uuid = await getUuidFromUsername(targetName);
if (!uuid) return;
await dbClient.connect();
const dbResult = await dbClient.query(
`SELECT "${BOT_CONFIG.columnX}", "${BOT_CONFIG.columnY}", "${BOT_CONFIG.columnZ}", "${BOT_CONFIG.columnWorld}"
FROM ${BOT_CONFIG.tableName}
WHERE "${BOT_CONFIG.columnUUID}" = $1`,
[uuid]
);
if (dbResult.rows.length === 0) return;
const { x, y, z, world } = dbResult.rows[0];
const dbCenterPos = new Vec3(x, y, z);
const targetDimension = world.toLowerCase().replace('minecraft:', '');
if (!bot.game.dimension.includes(targetDimension)) return;
const blockToClick = getNearbyTrapdoor(dbCenterPos, BOT_CONFIG.TrapdoorSearchRadius);
if (!blockToClick) throw new Error('Trapdoor not found');
const trapdoorPos = blockToClick.position;
const botStandPos = trapdoorPos.offset(0, 0, 1);
const pathfindingGoal = new GoalNear(botStandPos.x, botStandPos.y, botStandPos.z, 0);
bot.clearControlStates();
try {
await bot.pathfinder.goto(pathfindingGoal);
} catch {
if (bot.entity.position.distanceTo(botStandPos.offset(0.5, 0.5, 0.5)) > 1.5) throw new Error('Pathfinding failed');
}
bot.pathfinder.stop();
bot.clearControlStates();
await bot.waitForTicks(2);
await safeActivateBlock(blockToClick, targetName);
} catch (error) {
bot.pathfinder.stop();
bot.clearControlStates();
bot.setControlState('sneak', false);
console.error(error.message);
} finally {
if (dbClient) await dbClient.end();
}
}

< /code>
Я попытался изменить способ взаимодействия, но ничего не работает. Если он работает хорошо, он должен взаимодействовать с определенным блоком и сделать это состояниями этого блока, блок, который является люком, который он должен закрыть, что делает Ender Pearl Despawn и телепортируя игрока.

Подробнее здесь: https://stackoverflow.com/questions/797 ... teractions
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»