PrismarineJS / mineflayer-pathfinder

Pathfinding plugin that gives bot the ability to go from A to B
MIT License
222 stars 68 forks source link
bot minecraft pathfinding

Mineflayer-pathfinder

npm version npm Try it on gitpod Issue Hunt

Pathfinding plugin for the Minecraft Bot API Mineflayer. Create static, dynamic or composite goals to navigate Minecraft terrain fully autonomously.

Mostly stable. Feel free to contribute by making suggestions or posting issues.

Install

npm install mineflayer-pathfinder

Tutorial & Explanation

For a basic explanation of how to use mineflayer-pathfinder, you can read this tutorial.

Video Tutorials

For a video tutorial explaining the usage of mineflayer-pathfinder, you can watch the following Youtube videos:

part 1 part 2

Example

const mineflayer = require('mineflayer')
const pathfinder = require('mineflayer-pathfinder').pathfinder
const Movements = require('mineflayer-pathfinder').Movements
const { GoalNear } = require('mineflayer-pathfinder').goals
const bot = mineflayer.createBot({ username: 'Player' })

bot.loadPlugin(pathfinder)

bot.once('spawn', () => {
  const defaultMove = new Movements(bot)

  bot.on('chat', function(username, message) {

    if (username === bot.username) return

    const target = bot.players[username] ? bot.players[username].entity : null
    if (message === 'come') {
      if (!target) {
        bot.chat('I don\'t see you !')
        return
      }
      const p = target.position

      bot.pathfinder.setMovements(defaultMove)
      bot.pathfinder.setGoal(new GoalNear(p.x, p.y, p.z, 1))
    } 
  })
})

Features

API

Considering there are a lot of deep changes that are being worked on, it could take some time before it's done

Also, for now, there is only the pathfinder module, movements and goals still need to be done

Functions:

bot.pathfinder.goto(goal)

Returns a Promise with the path result. Resolves when the goal is reached. Rejects on error.

bot.pathfinder.bestHarvestTool(block)

Returns the best harvesting tool in the inventory for the specified block.

bot.pathfinder.getPathTo(movements, goal, timeout)

bot.pathfinder.getPathFromTo* (movements, startPos, goal, options = {})

Returns a Generator. The generator computes the path for as longs as no full path is found or options.timeout is reached. The generator will block the event loop until a path is found or options.tickTimeout (default to 50ms) is reached.

bot.pathfinder.setGoal(Goal, dynamic)

bot.pathfinder.setMovements(movements)

Assigns the movements config.

bot.pathfinder.stop()

Stops pathfinding as soon as the bot has reached the next node in the path (this prevents the bot from stopping mid-air). Emits path_stop when called. Note: to force stop immediately, use bot.pathfinder.setGoal(null)

bot.pathfinder.isMoving()

A function that checks if the bot is currently moving.

bot.pathfinder.isMining()

A function that checks if the bot is currently mining blocks.

bot.pathfinder.isBuilding()

A function that checks if the bot is currently placing blocks.

Properties:

bot.pathfinder.thinkTimeout

Think Timeout in milliseconds.

bot.pathfinder.tickTimeout

How many milliseconds per tick are allocated to thinking.

bot.pathfinder.searchRadius

The search limiting radius, in blocks, if -1 the search is not limited by distance.

Movement class

This class configures how pathfinder plans its paths. It configures things like block breaking or different costs for moves. This class can be extended to add or change how pathfinder calculates its moves.

Usage

Pathfinder instantiates the default movement class by itself if no instance is specified. If you want to change values you should create a new instance of the Movements class, change it's values and set it as pathfinders new movement class.

Example:

const { Movements } = require('mineflayer-pathfinder') // Import the Movements class from pathfinder

bot.once('spawn', () => {
  // A new movement instance for specific behavior
  const defaultMove = new Movements(bot)

  defaultMove.allow1by1towers = false // Do not build 1x1 towers when going up
  defaultMove.canDig = false // Disable breaking of blocks when pathing 
  defaultMove.scafoldingBlocks.push(bot.registry.itemsByName['netherrack'].id) // Add nether rack to allowed scaffolding items
  bot.pathfinder.setMovements(defaultMove) // Update the movement instance pathfinder uses

  // Do pathfinder things
  // ...
})

Movements class default properties

Movement class properties and their default values.

canDig

Boolean to allow breaking blocks.

digCost

Additional cost for breaking blocks.

placeCost

Additional cost for placing blocks.

maxDropDown

Max drop down distance. Only considers drops that have blocks to land on.

infiniteLiquidDropdownDistance

Option to ignore maxDropDown distance when the landing position is in water.

liquidCost

Additional cost for interacting with liquids.

entityCost

Additional cost for moving through an entity hitbox (besides passable ones).

dontCreateFlow

Do not break blocks that touch liquid blocks.

dontMineUnderFallingBlock

Do not break blocks that have a gravityBlock above.

allow1by1towers

Allow pillaring up on 1x1 towers.

allowFreeMotion

Allow to walk to the next node/goal in a straight line if terrain allows it.

allowParkour

Allow parkour jumps like jumps over gaps bigger then 1 block.

allowSprinting

Allow sprinting when moving.

allowEntityDetection

Test for entities that may obstruct path or prevent block placement. Grabs updated entities every new path.

entitiesToAvoid

Set of entities (by bot.registry name) to completely avoid when using entity detection.

passableEntities

Set of entities (by bot.registry name) to ignore when using entity detection.

interactableBlocks

Set of blocks (by bot.registry name) that pathfinder should not attempt to place blocks or 'right click' on.

blocksCantBreak

Set of block id's pathfinder cannot break. Includes chests and all unbreakable blocks.

blocksToAvoid

Set of block id's to avoid.

liquids

Set of liquid block id's.

climbables

Set of block id's that are climable. Note: Currently unused as pathfinder cannot use climables.

replaceables

Set of block id's that can be replaced when placing blocks.

scafoldingBlocks

Array of item id's that can be used as scaffolding blocks.

gravityBlocks

Set of block id's that can fall on bot's head.

fences

Set of block id's that are fences or blocks that have a collision box taller then 1 block.

carpets

Set of all carpet block id's or blocks that have a collision box smaller then 0.1. These blocks are considered safe to walk in.

exclusionAreasStep

An array of functions that define an area or block to be step on excluded. Every function in the array is parsed the Block the bot is planing to step on. Each function should return a positive number (includes 0) that defines extra cost for that specific Block. 0 means no extra cost, 100 means it is impossible for pathfinder to consider this move.

exclusionAreasBreak

An array of functions that define an area or block to be break excluded. Every function in the array is parsed the Block the bot is planing to break. Each function should return a positive number (includes 0) that defines extra cost for that specific Block. 0 means no extra cost, 100 means it is impossible for pathfinder to consider this move.

exclusionAreasPlace

An array of functions that define an area to be block placement excluded. Every function in the array is parsed the current Block the bot is planing to place a block inside (should be air or a replaceable block most of the time). Each function should return a positive number (includes 0) that defines extra cost for that specific Block. 0 means no extra cost, 100 makes it impossible for pathfinder to consider this move.

entityIntersections

A dictionary of the number of entities intersecting each floored block coordinate. Updated automatically for each path, but you may mix in your own entries before calculating a path if desired (generally for testing). To prevent this from being cleared automatically before generating a path,s see the path gen options.

canOpenDoors

Enable feature to open Fence Gates. Unreliable and known to be buggy.

Events:

goal_reached

Called when the goal has been reached. Not called for dynamic goals.

path_update

Called whenever the path is recalculated. Status may be:

goal_updated

Called whenever a new goal is assigned to the pathfinder.

path_reset

Called when the path is reset, with a reason:

Goals:

Goal

Abstract Goal class. Do not instantiate this class. Instead extend it to make a new Goal class.

Has abstract methods:

Implements default methods for:

GoalBlock(x, y, z)

One specific block that the player should stand inside at foot level

GoalNear(x, y, z, range)

A block position that the player should get within a certain radius of

GoalXZ(x, z)

Useful for long-range goals that don't have a specific Y level

GoalNearXZ(x, z, range)

Useful for finding builds that you don't have an exact Y level for, just an approximate X and Z level.

GoalY(y)

Get to a Y level.

GoalGetToBlock(x, y, z)

Don't get into the block, but get directly adjacent to it. Useful for chests.

GoalCompositeAny(Array\?)

A composite of many goals, any one of which satisfies the composite. For example, a GoalCompositeAny of block goals for every oak log in loaded chunks would result in it pathing to the easiest oak log to get to.

GoalCompositeAll(Array\?)

A composite of multiple goals, requiring all of them to be satisfied.

GoalInvert(goal)

Inverts the goal.

GoalFollow(entity, range)

Follows an entity.

GoalPlaceBlock(pos, world, options)

Position the bot in order to place a block.