Here is the updated code with the movement handling completely rewritten. The movement is now simplified to directly manage the control states without using timeouts or the physicsTick event. This should resolve the issue where the movement gets canceled unexpectedly.
const mineflayer = require('mineflayer');
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder');
const express = require('express');
const Vec3 = require('vec3');
const { GoalBlock } = goals;
const app = express();
const port = 8000;
// Bot configuration
const botConfig = {
host: 'localhost',
port: 25565,
username: 'ChunkScanner',
version: '1.18.2'
};
// Optimization: Use Set for O(1) lookups
const transparentBlocks = new Set([
'air', 'water', 'lava', 'chain', 'grass_block', 'grass', 'tall_grass'
]);
// Optimization: Compile patterns into a single regex for faster matching
const transparentBlockPattern = new RegExp(
'(glass|leaves|fence|door|trapdoor|bars|rod|lantern|vine|sapling|coral|kelp|' +
'bamboo|mushroom|rail|torch|sign|banner|button|pressure|carpet|ladder)'
);
// Cache frequently accessed values
const CHUNK_SIZE = 16;
const CHUNK_RANGE = { X: 3, Z: 3 };
const ENABLE_CULLING = true;
// Preallocate vectors for better memory usage
const NEIGHBOR_OFFSETS = [
new Vec3(1, 0, 0), new Vec3(-1, 0, 0),
new Vec3(0, 1, 0), new Vec3(0, -1, 0),
new Vec3(0, 0, 1), new Vec3(0, 0, -1)
];
// State management
let bot;
let chunksLoaded = false;
let cachedBlockData = [];
// Configure express to parse JSON
app.use(express.json());
// Optimization: Use faster lookup for transparent blocks
function isTransparentBlock(blockName) {
return transparentBlocks.has(blockName) || transparentBlockPattern.test(blockName);
}
function isBlockExposed(bot, blockPos) {
for (const offset of NEIGHBOR_OFFSETS) {
const neighborPos = blockPos.plus(offset);
const neighborBlock = bot.blockAt(neighborPos);
if (!neighborBlock || isTransparentBlock(neighborBlock.name)) {
return true;
}
}
return false;
}
// Scan loaded chunks and cache block data
function scanLoadedChunks(bot) {
const blocks = [];
const world = bot.world;
const playerPos = bot.entity.position;
const playerChunk = {
x: Math.floor(playerPos.x / CHUNK_SIZE),
z: Math.floor(playerPos.z / CHUNK_SIZE)
};
const minY = world.minY || 0;
const maxY = world.maxY || 256;
const blockPos = new Vec3(0, 0, 0); // Reuse Vec3 instance
const batchSize = 4;
for (let cx = -CHUNK_RANGE.X; cx <= CHUNK_RANGE.X; cx += batchSize) {
for (let cz = -CHUNK_RANGE.Z; cz <= CHUNK_RANGE.Z; cz += batchSize) {
processChunkBatch(cx, cz, Math.min(batchSize, CHUNK_RANGE.X - cx + 1),
Math.min(batchSize, CHUNK_RANGE.Z - cz + 1));
}
}
function processChunkBatch(startCX, startCZ, batchWidth, batchHeight) {
for (let cx = startCX; cx < startCX + batchWidth; cx++) {
for (let cz = startCZ; cz < startCZ + batchHeight; cz++) {
const chunkX = playerChunk.x + cx;
const chunkZ = playerChunk.z + cz;
for (let x = 0; x < CHUNK_SIZE; x++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const absoluteX = chunkX * CHUNK_SIZE + x;
const absoluteZ = chunkZ * CHUNK_SIZE + z;
if (Math.abs(absoluteX - playerPos.x) > CHUNK_SIZE * CHUNK_RANGE.X ||
Math.abs(absoluteZ - playerPos.z) > CHUNK_SIZE * CHUNK_RANGE.Z) {
continue;
}
for (let y = minY; y < maxY; y++) {
try {
blockPos.set(absoluteX, y, absoluteZ);
const block = bot.blockAt(blockPos);
if (!block || block.type === 0) continue;
if (isTransparentBlock(block.name)) {
blocks.push({
block_name: block.name,
x: absoluteX,
y,
z: absoluteZ,
direction: block.metadata
});
continue;
}
if (ENABLE_CULLING && y < playerPos.y && !isBlockExposed(bot, blockPos)) {
continue;
}
blocks.push({
block_name: block.name,
x: absoluteX,
y,
z: absoluteZ,
direction: block.metadata
});
} catch (err) {
continue;
}
}
}
}
}
}
}
return blocks;
}
// Start bot and listen for chunk loading
function initializeBot() {
bot = mineflayer.createBot(botConfig);
// Load the pathfinder plugin
bot.loadPlugin(pathfinder);
bot.once('spawn', () => {
// Initialize movements with default values
const movements = new Movements(bot);
bot.pathfinder.setMovements(movements);
console.log('Bot spawned, waiting for chunks to load...');
});
bot.on('chunkColumnLoad', (point) => {
if (!chunksLoaded) {
chunksLoaded = true;
console.log('First chunk loaded at', point);
setTimeout(() => {
cachedBlockData = scanLoadedChunks(bot);
console.log(`Scanned ${cachedBlockData.length} blocks`);
}, 2000);
}
});
bot.on('error', console.error);
bot.on('kicked', console.log);
}
// API Endpoints
app.get('/blocks', (req, res) => {
res.json(cachedBlockData);
});
// Get the current coordinates of the bot
app.get('/bot/coordinates', (req, res) => {
if (bot && bot.entity) {
const position = bot.entity.position;
res.json({
x: position.x,
y: position.y,
z: position.z
});
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
// Set bot coordinates using pathfinding
app.post('/bot/coordinates', (req, res) => {
const { x, y, z } = req.body;
if (bot) {
try {
// Use pathfinding to move to the target position
bot.pathfinder.setGoal(new GoalBlock(x, y, z));
res.json({
success: true,
message: `Bot pathfinding to ${x}, ${y}, ${z}`
});
} catch (err) {
res.status(500).json({
success: false,
error: err.message
});
}
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
// Rewritten movement endpoint without timeouts or physicsTick
app.post('/bot/move', (req, res) => {
const controls = req.body.controls;
if (bot) {
try {
// Set control states based on the controls object
for (const control in controls) {
if (controls.hasOwnProperty(control)) {
bot.setControlState(control, controls[control]);
}
}
res.json({
success: true,
message: `Bot control states updated.`,
controls: bot.controlState
});
} catch (err) {
res.status(500).json({
success: false,
error: err.message
});
}
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
// Set bot's head look position
app.post('/bot/look', (req, res) => {
const { x, y, z } = req.body;
if (bot) {
try {
const targetPosition = new Vec3(x, y, z);
bot.lookAt(targetPosition, true, () => {
res.json({
success: true,
message: `Bot looking at ${x}, ${y}, ${z}`
});
});
} catch (err) {
res.status(500).json({
success: false,
error: err.message
});
}
} else {
res.status(404).json({
success: false,
error: 'Bot is not available'
});
}
});
// Start the server
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
initializeBot();
});
Usage of the /bot/move Endpoint:
To control the bot's movement, send a POST request to /bot/move with a JSON body containing the control states you want to set. For example:
-
Start Moving Forward:
{
"controls": {
"forward": true
}
}
-
Stop Moving Forward:
{
"controls": {
"forward": false
}
}
-
Start Sprinting:
{
"controls": {
"sprint": true
}
}
-
Jump:
{
"controls": {
"jump": true
}
}
Note: Since jump is a control state, setting it to true makes the bot start jumping continuously. To make the bot jump once, you can set it to true and then immediately to false:
{
"controls": {
"jump": true
}
}
Then, after a short delay:
{
"controls": {
"jump": false
}
}
-
Combine Multiple Controls:
{
"controls": {
"forward": true,
"sprint": true,
"jump": true
}
}
Explanation of Changes:
-
Removed Timeouts and physicsTick Handler:
The movement handling no longer relies on timeouts or the physicsTick event. This simplifies the movement logic and prevents movements from being canceled unexpectedly.
-
Direct Control State Management:
The bot's control states are now managed directly based on the input from the /bot/move endpoint. This allows movements to persist until explicitly changed by the client.
-
Simplified Movement Endpoint:
The /bot/move endpoint accepts a controls object that directly sets the bot's control states. This provides more flexibility and control over the bot's movements.
By making these changes, the bot's movement should now operate smoothly without getting canceled. Clients can control the bot's movements more precisely by setting and unsetting control states as needed.