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