CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PrismarineJS

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: PrismarineJS/mineflayer
Path: blob/master/examples/guard.js
Views: 789
1
/**
2
* This bot example shows the basic usage of the mineflayer-pvp plugin for guarding a defined area from nearby mobs.
3
*/
4
5
if (process.argv.length < 4 || process.argv.length > 6) {
6
console.log('Usage : node guard.js <host> <port> [<name>] [<password>]')
7
process.exit(1)
8
}
9
10
const mineflayer = require('mineflayer')
11
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
12
const pvp = require('mineflayer-pvp').plugin
13
14
const bot = mineflayer.createBot({
15
host: process.argv[2],
16
port: parseInt(process.argv[3]),
17
username: process.argv[4] ? process.argv[4] : 'Guard',
18
password: process.argv[5]
19
})
20
21
bot.loadPlugin(pathfinder)
22
bot.loadPlugin(pvp)
23
24
let guardPos = null
25
26
// Assign the given location to be guarded
27
function guardArea (pos) {
28
guardPos = pos
29
30
// We we are not currently in combat, move to the guard pos
31
if (!bot.pvp.target) {
32
moveToGuardPos()
33
}
34
}
35
36
// Cancel all pathfinder and combat
37
function stopGuarding () {
38
guardPos = null
39
bot.pvp.stop()
40
bot.pathfinder.setGoal(null)
41
}
42
43
// Pathfinder to the guard position
44
function moveToGuardPos () {
45
bot.pathfinder.setMovements(new Movements(bot))
46
bot.pathfinder.setGoal(new goals.GoalBlock(guardPos.x, guardPos.y, guardPos.z))
47
}
48
49
// Called when the bot has killed it's target.
50
bot.on('stoppedAttacking', () => {
51
if (guardPos) {
52
moveToGuardPos()
53
}
54
})
55
56
// Check for new enemies to attack
57
bot.on('physicsTick', () => {
58
if (!guardPos) return // Do nothing if bot is not guarding anything
59
60
// Only look for mobs within 16 blocks
61
const filter = e => e.type === 'mob' && e.position.distanceTo(bot.entity.position) < 16 &&
62
e.displayName !== 'Armor Stand' // Mojang classifies armor stands as mobs for some reason?
63
64
const entity = bot.nearestEntity(filter)
65
if (entity) {
66
// Start attacking
67
bot.pvp.attack(entity)
68
}
69
})
70
71
// Listen for player commands
72
bot.on('chat', (username, message) => {
73
// Guard the location the player is standing
74
if (message === 'guard') {
75
const player = bot.players[username]
76
77
if (!player) {
78
bot.chat("I can't see you.")
79
return
80
}
81
82
bot.chat('I will guard that location.')
83
guardArea(player.entity.position)
84
}
85
86
// Stop guarding
87
if (message === 'stop') {
88
bot.chat('I will no longer guard this area.')
89
stopGuarding()
90
}
91
})
92
93