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/crossbower.js
Views: 789
1
// This example will shoot the player that said "fire" in chat, when it is said in chat.
2
const mineflayer = require('mineflayer')
3
4
if (process.argv.length < 4 || process.argv.length > 6) {
5
console.log('Usage : node crossbower.js <host> <port> [<name>] [<password>]')
6
process.exit(1)
7
}
8
9
const bot = mineflayer.createBot({
10
host: process.argv[2],
11
port: parseInt(process.argv[3]),
12
username: process.argv[4] ? process.argv[4] : 'crossbower',
13
password: process.argv[5]
14
})
15
16
bot.on('spawn', function () {
17
bot.chat(`/give ${bot.username} crossbow{Enchantments:[{id:quick_charge,lvl:3},{id:unbreaking,lvl:3}]} 1`) // Test with fast charge
18
// bot.chat(`/give ${bot.username} crossbow 1`) // Test with slow charge
19
bot.chat(`/give ${bot.username} minecraft:arrow 64`)
20
})
21
22
bot.on('chat', async (username, message) => {
23
if (message === 'fire') {
24
// Check if weapon is equipped
25
const slotID = bot.getEquipmentDestSlot('hand')
26
if (bot.inventory.slots[slotID] === null || bot.inventory.slots[slotID].name !== 'crossbow') {
27
const weaponFound = bot.inventory.items().find(item => item.name === 'crossbow')
28
if (weaponFound) {
29
await bot.equip(weaponFound, 'hand')
30
} else {
31
console.log('No weapon in inventory')
32
return
33
}
34
}
35
36
const isEnchanted = bot.heldItem.nbt.value.Enchantments ? bot.heldItem.nbt.value.Enchantments.value.value.find(enchant => enchant.id.value === 'quick_charge') : undefined
37
38
const timeForCharge = 1250 - ((isEnchanted ? isEnchanted.lvl.value : 0) * 250)
39
40
bot.activateItem() // charge
41
await sleep(timeForCharge) // wait for crossbow to charge
42
bot.deactivateItem() // raise weapon
43
44
try {
45
bot.lookAt(bot.players[username].entity.position, true)
46
await bot.waitForTicks(5) // wait for lookat to finish
47
bot.activateItem() // fire
48
bot.deactivateItem()
49
} catch (err) {
50
bot.chat('Player disappeared, crossbow is charged now.')
51
}
52
}
53
})
54
55
function sleep (ms) {
56
return new Promise(resolve => setTimeout(resolve, ms))
57
}
58
59