forked from mindcraft-bots/mindcraft
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathskills.js
More file actions
2108 lines (1934 loc) · 81.5 KB
/
skills.js
File metadata and controls
2108 lines (1934 loc) · 81.5 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as mc from "../../utils/mcdata.js";
import * as world from "./world.js";
import pf from 'mineflayer-pathfinder';
import Vec3 from 'vec3';
import settings from "../../../settings.js";
const blockPlaceDelay = settings.block_place_delay == null ? 0 : settings.block_place_delay;
const useDelay = blockPlaceDelay > 0;
export function log(bot, message) {
bot.output += message + '\n';
}
async function autoLight(bot) {
if (world.shouldPlaceTorch(bot)) {
try {
const pos = world.getPosition(bot);
return await placeBlock(bot, 'torch', pos.x, pos.y, pos.z, 'bottom', true);
} catch (err) {return false;}
}
return false;
}
async function equipHighestAttack(bot) {
let weapons = bot.inventory.items().filter(item => item.name.includes('sword') || (item.name.includes('axe') && !item.name.includes('pickaxe')));
if (weapons.length === 0)
weapons = bot.inventory.items().filter(item => item.name.includes('pickaxe') || item.name.includes('shovel'));
if (weapons.length === 0)
return;
weapons.sort((a, b) => a.attackDamage < b.attackDamage);
let weapon = weapons[0];
if (weapon)
await bot.equip(weapon, 'hand');
}
export async function craftRecipe(bot, itemName, num=1) {
/**
* Attempt to craft the given item name from a recipe. May craft many items.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item name to craft.
* @returns {Promise<boolean>} true if the recipe was crafted, false otherwise.
* @example
* await skills.craftRecipe(bot, "stick");
**/
let placedTable = false;
if (mc.getItemCraftingRecipes(itemName).length == 0) {
log(bot, `${itemName} is either not an item, or it does not have a crafting recipe!`);
return false;
}
// get recipes that don't require a crafting table
let recipes = bot.recipesFor(mc.getItemId(itemName), null, 1, null);
let craftingTable = null;
const craftingTableRange = 16;
placeTable: if (!recipes || recipes.length === 0) {
recipes = bot.recipesFor(mc.getItemId(itemName), null, 1, true);
if(!recipes || recipes.length === 0) break placeTable; //Don't bother going to the table if we don't have the required resources.
// Look for crafting table
craftingTable = world.getNearestBlock(bot, 'crafting_table', craftingTableRange);
if (craftingTable === null){
// Try to place crafting table
let hasTable = world.getInventoryCounts(bot)['crafting_table'] > 0;
if (hasTable) {
let pos = world.getNearestFreeSpace(bot, 1, 6);
await placeBlock(bot, 'crafting_table', pos.x, pos.y, pos.z);
craftingTable = world.getNearestBlock(bot, 'crafting_table', craftingTableRange);
if (craftingTable) {
recipes = bot.recipesFor(mc.getItemId(itemName), null, 1, craftingTable);
placedTable = true;
}
}
else {
log(bot, `Crafting ${itemName} requires a crafting table.`)
return false;
}
}
else {
recipes = bot.recipesFor(mc.getItemId(itemName), null, 1, craftingTable);
}
}
if (!recipes || recipes.length === 0) {
log(bot, `You do not have the resources to craft a ${itemName}. It requires: ${Object.entries(mc.getItemCraftingRecipes(itemName)[0][0]).map(([key, value]) => `${key}: ${value}`).join(', ')}.`);
if (placedTable) {
await collectBlock(bot, 'crafting_table', 1);
}
return false;
}
if (craftingTable && bot.entity.position.distanceTo(craftingTable.position) > 4) {
await goToNearestBlock(bot, 'crafting_table', 4, craftingTableRange);
}
const recipe = recipes[0];
console.log('crafting...');
//Check that the agent has sufficient items to use the recipe `num` times.
const inventory = world.getInventoryCounts(bot); //Items in the agents inventory
const requiredIngredients = mc.ingredientsFromPrismarineRecipe(recipe); //Items required to use the recipe once.
const craftLimit = mc.calculateLimitingResource(inventory, requiredIngredients);
await bot.craft(recipe, Math.min(craftLimit.num, num), craftingTable);
if(craftLimit.num<num) log(bot, `Not enough ${craftLimit.limitingResource} to craft ${num}, crafted ${craftLimit.num}. You now have ${world.getInventoryCounts(bot)[itemName]} ${itemName}.`);
else log(bot, `Successfully crafted ${itemName}, you now have ${world.getInventoryCounts(bot)[itemName]} ${itemName}.`);
if (placedTable) {
await collectBlock(bot, 'crafting_table', 1);
}
//Equip any armor the bot may have crafted.
//There is probablly a more efficient method than checking the entire inventory but this is all mineflayer-armor-manager provides. :P
bot.armorManager.equipAll();
return true;
}
export async function wait(bot, milliseconds) {
/**
* Waits for the given number of milliseconds.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {number} milliseconds, the number of milliseconds to wait.
* @returns {Promise<boolean>} true if the wait was successful, false otherwise.
* @example
* await skills.wait(bot, 1000);
**/
// setTimeout is disabled to prevent unawaited code, so this is a safe alternative that enables interrupts
let timeLeft = milliseconds;
let startTime = Date.now();
while (timeLeft > 0) {
if (bot.interrupt_code) return false;
let waitTime = Math.min(2000, timeLeft);
await new Promise(resolve => setTimeout(resolve, waitTime));
let elapsed = Date.now() - startTime;
timeLeft = milliseconds - elapsed;
}
return true;
}
export async function smeltItem(bot, itemName, num=1) {
/**
* Puts 1 coal in furnace and smelts the given item name, waits until the furnace runs out of fuel or input items.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item name to smelt. Ores must contain "raw" like raw_iron.
* @param {number} num, the number of items to smelt. Defaults to 1.
* @returns {Promise<boolean>} true if the item was smelted, false otherwise. Fail
* @example
* await skills.smeltItem(bot, "raw_iron");
* await skills.smeltItem(bot, "beef");
**/
if (!mc.isSmeltable(itemName)) {
log(bot, `Cannot smelt ${itemName}. Hint: make sure you are smelting the 'raw' item.`);
return false;
}
let placedFurnace = false;
let furnaceBlock = undefined;
const furnaceRange = 16;
furnaceBlock = world.getNearestBlock(bot, 'furnace', furnaceRange);
if (!furnaceBlock){
// Try to place furnace
let hasFurnace = world.getInventoryCounts(bot)['furnace'] > 0;
if (hasFurnace) {
let pos = world.getNearestFreeSpace(bot, 1, furnaceRange);
await placeBlock(bot, 'furnace', pos.x, pos.y, pos.z);
furnaceBlock = world.getNearestBlock(bot, 'furnace', furnaceRange);
placedFurnace = true;
}
}
if (!furnaceBlock){
log(bot, `There is no furnace nearby and you have no furnace.`)
return false;
}
if (bot.entity.position.distanceTo(furnaceBlock.position) > 4) {
await goToNearestBlock(bot, 'furnace', 4, furnaceRange);
}
bot.modes.pause('unstuck');
await bot.lookAt(furnaceBlock.position);
console.log('smelting...');
const furnace = await bot.openFurnace(furnaceBlock);
// check if the furnace is already smelting something
let input_item = furnace.inputItem();
if (input_item && input_item.type !== mc.getItemId(itemName) && input_item.count > 0) {
// TODO: check if furnace is currently burning fuel. furnace.fuel is always null, I think there is a bug.
// This only checks if the furnace has an input item, but it may not be smelting it and should be cleared.
log(bot, `The furnace is currently smelting ${mc.getItemName(input_item.type)}.`);
if (placedFurnace)
await collectBlock(bot, 'furnace', 1);
return false;
}
// check if the bot has enough items to smelt
let inv_counts = world.getInventoryCounts(bot);
if (!inv_counts[itemName] || inv_counts[itemName] < num) {
log(bot, `You do not have enough ${itemName} to smelt.`);
if (placedFurnace)
await collectBlock(bot, 'furnace', 1);
return false;
}
// fuel the furnace
if (!furnace.fuelItem()) {
let fuel = mc.getSmeltingFuel(bot);
if (!fuel) {
log(bot, `You have no fuel to smelt ${itemName}, you need coal, charcoal, or wood.`);
if (placedFurnace)
await collectBlock(bot, 'furnace', 1);
return false;
}
log(bot, `Using ${fuel.name} as fuel.`);
const put_fuel = Math.ceil(num / mc.getFuelSmeltOutput(fuel.name));
if (fuel.count < put_fuel) {
log(bot, `You don't have enough ${fuel.name} to smelt ${num} ${itemName}; you need ${put_fuel}.`);
if (placedFurnace)
await collectBlock(bot, 'furnace', 1);
return false;
}
await furnace.putFuel(fuel.type, null, put_fuel);
log(bot, `Added ${put_fuel} ${mc.getItemName(fuel.type)} to furnace fuel.`);
console.log(`Added ${put_fuel} ${mc.getItemName(fuel.type)} to furnace fuel.`)
}
// put the items in the furnace
await furnace.putInput(mc.getItemId(itemName), null, num);
// wait for the items to smelt
let total = 0;
let smelted_item = null;
await new Promise(resolve => setTimeout(resolve, 200));
let last_collected = Date.now();
while (total < num) {
await new Promise(resolve => setTimeout(resolve, 1000));
if (furnace.outputItem()) {
smelted_item = await furnace.takeOutput();
if (smelted_item) {
total += smelted_item.count;
last_collected = Date.now();
}
}
if (Date.now() - last_collected > 11000) {
break; // if nothing has been collected in 11 seconds, stop
}
if (bot.interrupt_code) {
break;
}
}
// take all remaining in input/fuel slots
if (furnace.inputItem()) {
await furnace.takeInput();
}
if (furnace.fuelItem()) {
await furnace.takeFuel();
}
await bot.closeWindow(furnace);
if (placedFurnace) {
await collectBlock(bot, 'furnace', 1);
}
if (total === 0) {
log(bot, `Failed to smelt ${itemName}.`);
return false;
}
if (total < num) {
log(bot, `Only smelted ${total} ${mc.getItemName(smelted_item.type)}.`);
return false;
}
log(bot, `Successfully smelted ${itemName}, got ${total} ${mc.getItemName(smelted_item.type)}.`);
return true;
}
export async function clearNearestFurnace(bot) {
/**
* Clears the nearest furnace of all items.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @returns {Promise<boolean>} true if the furnace was cleared, false otherwise.
* @example
* await skills.clearNearestFurnace(bot);
**/
let furnaceBlock = world.getNearestBlock(bot, 'furnace', 32);
if (!furnaceBlock) {
log(bot, `No furnace nearby to clear.`);
return false;
}
if (bot.entity.position.distanceTo(furnaceBlock.position) > 4) {
await goToNearestBlock(bot, 'furnace', 4, 32);
}
console.log('clearing furnace...');
const furnace = await bot.openFurnace(furnaceBlock);
console.log('opened furnace...')
// take the items out of the furnace
let smelted_item, intput_item, fuel_item;
if (furnace.outputItem())
smelted_item = await furnace.takeOutput();
if (furnace.inputItem())
intput_item = await furnace.takeInput();
if (furnace.fuelItem())
fuel_item = await furnace.takeFuel();
console.log(smelted_item, intput_item, fuel_item)
let smelted_name = smelted_item ? `${smelted_item.count} ${smelted_item.name}` : `0 smelted items`;
let input_name = intput_item ? `${intput_item.count} ${intput_item.name}` : `0 input items`;
let fuel_name = fuel_item ? `${fuel_item.count} ${fuel_item.name}` : `0 fuel items`;
log(bot, `Cleared furnace, received ${smelted_name}, ${input_name}, and ${fuel_name}.`);
return true;
}
export async function attackNearest(bot, mobType, kill=true) {
/**
* Attack mob of the given type.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} mobType, the type of mob to attack.
* @param {boolean} kill, whether or not to continue attacking until the mob is dead. Defaults to true.
* @returns {Promise<boolean>} true if the mob was attacked, false if the mob type was not found.
* @example
* await skills.attackNearest(bot, "zombie", true);
**/
bot.modes.pause('cowardice');
if (mobType === 'drowned' || mobType === 'cod' || mobType === 'salmon' || mobType === 'tropical_fish' || mobType === 'squid')
bot.modes.pause('self_preservation'); // so it can go underwater. TODO: have an drowning mode so we don't turn off all self_preservation
const mob = world.getNearbyEntities(bot, 24).find(entity => entity.name === mobType);
if (mob) {
return await attackEntity(bot, mob, kill);
}
log(bot, 'Could not find any '+mobType+' to attack.');
return false;
}
export async function attackEntity(bot, entity, kill=true) {
/**
* Attack mob of the given type.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {Entity} entity, the entity to attack.
* @returns {Promise<boolean>} true if the entity was attacked, false if interrupted
* @example
* await skills.attackEntity(bot, entity);
**/
let pos = entity.position;
await equipHighestAttack(bot)
if (!kill) {
if (bot.entity.position.distanceTo(pos) > 5) {
console.log('moving to mob...')
await goToPosition(bot, pos.x, pos.y, pos.z);
}
console.log('attacking mob...')
await bot.attack(entity);
}
else {
bot.pvp.attack(entity);
while (world.getNearbyEntities(bot, 24).includes(entity)) {
await new Promise(resolve => setTimeout(resolve, 1000));
if (bot.interrupt_code) {
bot.pvp.stop();
return false;
}
}
log(bot, `Successfully killed ${entity.name}.`);
await pickupNearbyItems(bot);
return true;
}
}
export async function defendSelf(bot, range=9) {
/**
* Defend yourself from all nearby hostile mobs until there are no more.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {number} range, the range to look for mobs. Defaults to 8.
* @returns {Promise<boolean>} true if the bot found any enemies and has killed them, false if no entities were found.
* @example
* await skills.defendSelf(bot);
* **/
bot.modes.pause('self_defense');
bot.modes.pause('cowardice');
let attacked = false;
let enemy = world.getNearestEntityWhere(bot, entity => mc.isHostile(entity), range);
while (enemy) {
await equipHighestAttack(bot);
if (bot.entity.position.distanceTo(enemy.position) >= 4 && enemy.name !== 'creeper' && enemy.name !== 'phantom') {
try {
bot.pathfinder.setMovements(new pf.Movements(bot));
await bot.pathfinder.goto(new pf.goals.GoalFollow(enemy, 3.5), true);
} catch (err) {/* might error if entity dies, ignore */}
}
if (bot.entity.position.distanceTo(enemy.position) <= 2) {
try {
bot.pathfinder.setMovements(new pf.Movements(bot));
let inverted_goal = new pf.goals.GoalInvert(new pf.goals.GoalFollow(enemy, 2));
await bot.pathfinder.goto(inverted_goal, true);
} catch (err) {/* might error if entity dies, ignore */}
}
bot.pvp.attack(enemy);
attacked = true;
await new Promise(resolve => setTimeout(resolve, 500));
enemy = world.getNearestEntityWhere(bot, entity => mc.isHostile(entity), range);
if (bot.interrupt_code) {
bot.pvp.stop();
return false;
}
}
bot.pvp.stop();
if (attacked)
log(bot, `Successfully defended self.`);
else
log(bot, `No enemies nearby to defend self from.`);
return attacked;
}
export async function collectBlock(bot, blockType, num=1, exclude=null) {
/**
* Collect one of the given block type.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} blockType, the type of block to collect.
* @param {number} num, the number of blocks to collect. Defaults to 1.
* @param {list} exclude, a list of positions to exclude from the search. Defaults to null.
* @returns {Promise<boolean>} true if the block was collected, false if the block type was not found.
* @example
* await skills.collectBlock(bot, "oak_log");
**/
if (num < 1) {
log(bot, `Invalid number of blocks to collect: ${num}.`);
return false;
}
let blocktypes = [blockType];
if (blockType === 'coal' || blockType === 'diamond' || blockType === 'emerald' || blockType === 'iron' || blockType === 'gold' || blockType === 'lapis_lazuli' || blockType === 'redstone')
blocktypes.push(blockType+'_ore');
if (blockType.endsWith('ore'))
blocktypes.push('deepslate_'+blockType);
if (blockType === 'dirt')
blocktypes.push('grass_block');
if (blockType === 'cobblestone')
blocktypes.push('stone');
const isLiquid = blockType === 'lava' || blockType === 'water';
let collected = 0;
const movements = new pf.Movements(bot);
movements.dontMineUnderFallingBlock = false;
movements.dontCreateFlow = true;
// Blocks to ignore safety for, usually next to lava/water
const unsafeBlocks = ['obsidian'];
for (let i=0; i<num; i++) {
let blocks = world.getNearestBlocksWhere(bot, block => {
if (!blocktypes.includes(block.name)) {
return false;
}
if (exclude) {
for (let position of exclude) {
if (block.position.x === position.x && block.position.y === position.y && block.position.z === position.z) {
return false;
}
}
}
if (isLiquid) {
// collect only source blocks
return block.metadata === 0;
}
return movements.safeToBreak(block) || unsafeBlocks.includes(block.name);
}, 64, 1);
if (blocks.length === 0) {
if (collected === 0)
log(bot, `No ${blockType} nearby to collect.`);
else
log(bot, `No more ${blockType} nearby to collect.`);
break;
}
const block = blocks[0];
await bot.tool.equipForBlock(block);
if (isLiquid) {
const bucket = bot.inventory.items().find(item => item.name === 'bucket');
if (!bucket) {
log(bot, `Don't have bucket to harvest ${blockType}.`);
return false;
}
await bot.equip(bucket, 'hand');
}
const itemId = bot.heldItem ? bot.heldItem.type : null
if (!block.canHarvest(itemId)) {
log(bot, `Don't have right tools to harvest ${blockType}.`);
return false;
}
try {
let success = false;
if (isLiquid) {
success = await useToolOnBlock(bot, 'bucket', block);
}
else if (mc.mustCollectManually(blockType)) {
await goToPosition(bot, block.position.x, block.position.y, block.position.z, 2);
await bot.dig(block);
await pickupNearbyItems(bot);
success = true;
}
else {
await bot.collectBlock.collect(block);
success = true;
}
if (success)
collected++;
await autoLight(bot);
}
catch (err) {
if (err.name === 'NoChests') {
log(bot, `Failed to collect ${blockType}: Inventory full, no place to deposit.`);
break;
}
else {
log(bot, `Failed to collect ${blockType}: ${err}.`);
continue;
}
}
if (bot.interrupt_code)
break;
}
log(bot, `Collected ${collected} ${blockType}.`);
return collected > 0;
}
export async function pickupNearbyItems(bot) {
/**
* Pick up all nearby items.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @returns {Promise<boolean>} true if the items were picked up, false otherwise.
* @example
* await skills.pickupNearbyItems(bot);
**/
const distance = 8;
const getNearestItem = bot => bot.nearestEntity(entity => entity.name === 'item' && bot.entity.position.distanceTo(entity.position) < distance);
let nearestItem = getNearestItem(bot);
let pickedUp = 0;
while (nearestItem) {
let movements = new pf.Movements(bot);
movements.canDig = false;
bot.pathfinder.setMovements(movements);
await goToGoal(bot, new pf.goals.GoalFollow(nearestItem, 1));
await new Promise(resolve => setTimeout(resolve, 200));
let prev = nearestItem;
nearestItem = getNearestItem(bot);
if (prev === nearestItem) {
break;
}
pickedUp++;
}
log(bot, `Picked up ${pickedUp} items.`);
return true;
}
export async function breakBlockAt(bot, x, y, z) {
/**
* Break the block at the given position. Will use the bot's equipped item.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {number} x, the x coordinate of the block to break.
* @param {number} y, the y coordinate of the block to break.
* @param {number} z, the z coordinate of the block to break.
* @returns {Promise<boolean>} true if the block was broken, false otherwise.
* @example
* let position = world.getPosition(bot);
* await skills.breakBlockAt(bot, position.x, position.y - 1, position.x);
**/
if (x == null || y == null || z == null) throw new Error('Invalid position to break block at.');
let block = bot.blockAt(Vec3(x, y, z));
if (block.name !== 'air' && block.name !== 'water' && block.name !== 'lava') {
if (bot.modes.isOn('cheat')) {
if (useDelay) { await new Promise(resolve => setTimeout(resolve, blockPlaceDelay)); }
let msg = '/setblock ' + Math.floor(x) + ' ' + Math.floor(y) + ' ' + Math.floor(z) + ' air';
bot.chat(msg);
log(bot, `Used /setblock to break block at ${x}, ${y}, ${z}.`);
return true;
}
if (bot.entity.position.distanceTo(block.position) > 4.5) {
let pos = block.position;
let movements = new pf.Movements(bot);
movements.canPlaceOn = false;
movements.allow1by1towers = false;
bot.pathfinder.setMovements(movements);
await goToGoal(bot, new pf.goals.GoalNear(pos.x, pos.y, pos.z, 4));
}
if (bot.game.gameMode !== 'creative') {
await bot.tool.equipForBlock(block);
const itemId = bot.heldItem ? bot.heldItem.type : null
if (!block.canHarvest(itemId)) {
log(bot, `Don't have right tools to break ${block.name}.`);
return false;
}
}
await bot.dig(block, true);
log(bot, `Broke ${block.name} at x:${x.toFixed(1)}, y:${y.toFixed(1)}, z:${z.toFixed(1)}.`);
}
else {
log(bot, `Skipping block at x:${x.toFixed(1)}, y:${y.toFixed(1)}, z:${z.toFixed(1)} because it is ${block.name}.`);
return false;
}
return true;
}
export async function placeBlock(bot, blockType, x, y, z, placeOn='bottom', dontCheat=false) {
/**
* Place the given block type at the given position. It will build off from any adjacent blocks. Will fail if there is a block in the way or nothing to build off of.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} blockType, the type of block to place, which can be a block or item name.
* @param {number} x, the x coordinate of the block to place.
* @param {number} y, the y coordinate of the block to place.
* @param {number} z, the z coordinate of the block to place.
* @param {string} placeOn, the preferred side of the block to place on. Can be 'top', 'bottom', 'north', 'south', 'east', 'west', or 'side'. Defaults to bottom. Will place on first available side if not possible.
* @param {boolean} dontCheat, overrides cheat mode to place the block normally. Defaults to false.
* @returns {Promise<boolean>} true if the block was placed, false otherwise.
* @example
* let p = world.getPosition(bot);
* await skills.placeBlock(bot, "oak_log", p.x + 2, p.y, p.x);
* await skills.placeBlock(bot, "torch", p.x + 1, p.y, p.x, 'side');
**/
const target_dest = new Vec3(Math.floor(x), Math.floor(y), Math.floor(z));
if (blockType === 'air') {
log(bot, `Placing air (removing block) at ${target_dest}.`);
return await breakBlockAt(bot, x, y, z);
}
if (bot.modes.isOn('cheat') && !dontCheat) {
if (bot.restrict_to_inventory) {
let block = bot.inventory.items().find(item => item.name === blockType);
if (!block) {
log(bot, `Cannot place ${blockType}, you are restricted to your current inventory.`);
return false;
}
}
// invert the facing direction
let face = placeOn === 'north' ? 'south' : placeOn === 'south' ? 'north' : placeOn === 'east' ? 'west' : 'east';
if (blockType.includes('torch') && placeOn !== 'bottom') {
// insert wall_ before torch
blockType = blockType.replace('torch', 'wall_torch');
if (placeOn !== 'side' && placeOn !== 'top') {
blockType += `[facing=${face}]`;
}
}
if (blockType.includes('button') || blockType === 'lever') {
if (placeOn === 'top') {
blockType += `[face=ceiling]`;
}
else if (placeOn === 'bottom') {
blockType += `[face=floor]`;
}
else {
blockType += `[facing=${face}]`;
}
}
if (blockType === 'ladder' || blockType === 'repeater' || blockType === 'comparator') {
blockType += `[facing=${face}]`;
}
if (blockType.includes('stairs')) {
blockType += `[facing=${face}]`;
}
if (useDelay) { await new Promise(resolve => setTimeout(resolve, blockPlaceDelay)); }
let msg = '/setblock ' + Math.floor(x) + ' ' + Math.floor(y) + ' ' + Math.floor(z) + ' ' + blockType;
bot.chat(msg);
if (blockType.includes('door'))
if (useDelay) { await new Promise(resolve => setTimeout(resolve, blockPlaceDelay)); }
bot.chat('/setblock ' + Math.floor(x) + ' ' + Math.floor(y+1) + ' ' + Math.floor(z) + ' ' + blockType + '[half=upper]');
if (blockType.includes('bed'))
if (useDelay) { await new Promise(resolve => setTimeout(resolve, blockPlaceDelay)); }
bot.chat('/setblock ' + Math.floor(x) + ' ' + Math.floor(y) + ' ' + Math.floor(z-1) + ' ' + blockType + '[part=head]');
log(bot, `Used /setblock to place ${blockType} at ${target_dest}.`);
return true;
}
let item_name = blockType;
if (item_name == "redstone_wire")
item_name = "redstone";
else if (item_name === 'water') {
item_name = 'water_bucket';
}
else if (item_name === 'lava') {
item_name = 'lava_bucket';
}
let block_item = bot.inventory.items().find(item => item.name === item_name);
if (!block_item && bot.game.gameMode === 'creative' && !bot.restrict_to_inventory) {
await bot.creative.setInventorySlot(36, mc.makeItem(item_name, 1)); // 36 is first hotbar slot
block_item = bot.inventory.items().find(item => item.name === item_name);
}
if (!block_item) {
log(bot, `Don't have any ${item_name} to place.`);
return false;
}
const targetBlock = bot.blockAt(target_dest);
if (targetBlock.name === blockType || (targetBlock.name === 'grass_block' && blockType === 'dirt')) {
log(bot, `${blockType} already at ${targetBlock.position}.`);
return false;
}
const empty_blocks = ['air', 'water', 'lava', 'grass', 'short_grass', 'tall_grass', 'snow', 'dead_bush', 'fern'];
if (!empty_blocks.includes(targetBlock.name)) {
log(bot, `${targetBlock.name} in the way at ${targetBlock.position}.`);
const removed = await breakBlockAt(bot, x, y, z);
if (!removed) {
log(bot, `Cannot place ${blockType} at ${targetBlock.position}: block in the way.`);
return false;
}
await new Promise(resolve => setTimeout(resolve, 200)); // wait for block to break
}
// get the buildoffblock and facevec based on whichever adjacent block is not empty
let buildOffBlock = null;
let faceVec = null;
const dir_map = {
'top': Vec3(0, 1, 0),
'bottom': Vec3(0, -1, 0),
'north': Vec3(0, 0, -1),
'south': Vec3(0, 0, 1),
'east': Vec3(1, 0, 0),
'west': Vec3(-1, 0, 0),
}
let dirs = [];
if (placeOn === 'side') {
dirs.push(dir_map['north'], dir_map['south'], dir_map['east'], dir_map['west']);
}
else if (dir_map[placeOn] !== undefined) {
dirs.push(dir_map[placeOn]);
}
else {
dirs.push(dir_map['bottom']);
log(bot, `Unknown placeOn value "${placeOn}". Defaulting to bottom.`);
}
dirs.push(...Object.values(dir_map).filter(d => !dirs.includes(d)));
for (let d of dirs) {
const block = bot.blockAt(target_dest.plus(d));
if (!empty_blocks.includes(block.name)) {
buildOffBlock = block;
faceVec = new Vec3(-d.x, -d.y, -d.z); // invert
break;
}
}
if (!buildOffBlock) {
log(bot, `Cannot place ${blockType} at ${targetBlock.position}: nothing to place on.`);
return false;
}
const pos = bot.entity.position;
const pos_above = pos.plus(Vec3(0,1,0));
const dont_move_for = ['torch', 'redstone_torch', 'redstone', 'lever', 'button', 'rail', 'detector_rail',
'powered_rail', 'activator_rail', 'tripwire_hook', 'tripwire', 'water_bucket', 'string'];
if (!dont_move_for.includes(item_name) && (pos.distanceTo(targetBlock.position) < 1.1 || pos_above.distanceTo(targetBlock.position) < 1.1)) {
// too close
let goal = new pf.goals.GoalNear(targetBlock.position.x, targetBlock.position.y, targetBlock.position.z, 2);
let inverted_goal = new pf.goals.GoalInvert(goal);
bot.pathfinder.setMovements(new pf.Movements(bot));
await bot.pathfinder.goto(inverted_goal);
}
if (bot.entity.position.distanceTo(targetBlock.position) > 4.5) {
// too far
let pos = targetBlock.position;
let movements = new pf.Movements(bot);
bot.pathfinder.setMovements(movements);
await goToGoal(bot, new pf.goals.GoalNear(pos.x, pos.y, pos.z, 4));
}
// will throw error if an entity is in the way, and sometimes even if the block was placed
try {
if (item_name.includes('bucket')) {
await useToolOnBlock(bot, item_name, buildOffBlock);
}
else {
await bot.equip(block_item, 'hand');
await bot.lookAt(buildOffBlock.position.offset(0.5, 0.5, 0.5));
await bot.placeBlock(buildOffBlock, faceVec);
log(bot, `Placed ${blockType} at ${target_dest}.`);
await new Promise(resolve => setTimeout(resolve, 200));
return true;
}
} catch (err) {
log(bot, `Failed to place ${blockType} at ${target_dest}.`);
return false;
}
}
export async function equip(bot, itemName) {
/**
* Equip the given item to the proper body part, like tools or armor.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item or block name to equip.
* @returns {Promise<boolean>} true if the item was equipped, false otherwise.
* @example
* await skills.equip(bot, "iron_pickaxe");
**/
if (itemName === 'hand') {
await bot.unequip('hand');
log(bot, `Unequipped hand.`);
return true;
}
let item = bot.inventory.slots.find(slot => slot && slot.name === itemName);
if (!item) {
if (bot.game.gameMode === "creative") {
await bot.creative.setInventorySlot(36, mc.makeItem(itemName, 1));
item = bot.inventory.items().find(item => item.name === itemName);
}
else {
log(bot, `You do not have any ${itemName} to equip.`);
return false;
}
}
if (itemName.includes('leggings')) {
await bot.equip(item, 'legs');
}
else if (itemName.includes('boots')) {
await bot.equip(item, 'feet');
}
else if (itemName.includes('helmet')) {
await bot.equip(item, 'head');
}
else if (itemName.includes('chestplate') || itemName.includes('elytra')) {
await bot.equip(item, 'torso');
}
else if (itemName.includes('shield')) {
await bot.equip(item, 'off-hand');
}
else {
await bot.equip(item, 'hand');
}
log(bot, `Equipped ${itemName}.`);
return true;
}
export async function discard(bot, itemName, num=-1) {
/**
* Discard the given item.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item or block name to discard.
* @param {number} num, the number of items to discard. Defaults to -1, which discards all items.
* @returns {Promise<boolean>} true if the item was discarded, false otherwise.
* @example
* await skills.discard(bot, "oak_log");
**/
let discarded = 0;
// Helper: find an item by name anywhere in the inventory slots (including off-hand)
function findItemByName(name) {
// prefer the inventory.items() convenience list
let it = bot.inventory.items().find(i => i.name === name);
if (it) return it;
// fallback: scan all slots (this will include off-hand and armor slots)
const slots = bot.inventory.slots || {};
for (const key of Object.keys(slots)) {
const slot = slots[key];
if (slot && slot.name === name) return slot;
}
return null;
}
while (true) {
let item = findItemByName(itemName);
if (!item) {
break;
}
let to_discard = num === -1 ? item.count : Math.min(num - discarded, item.count);
// Use toss with the item type (toss will remove from any slot containing that type)
await bot.toss(item.type, null, to_discard);
discarded += to_discard;
if (num !== -1 && discarded >= num) {
break;
}
}
if (discarded === 0) {
log(bot, `You do not have any ${itemName} to discard.`);
return false;
}
log(bot, `Discarded ${discarded} ${itemName}.`);
return true;
}
export async function putInChest(bot, itemName, num=-1) {
/**
* Put the given item in the nearest chest.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item or block name to put in the chest.
* @param {number} num, the number of items to put in the chest. Defaults to -1, which puts all items.
* @returns {Promise<boolean>} true if the item was put in the chest, false otherwise.
* @example
* await skills.putInChest(bot, "oak_log");
**/
let chest = world.getNearestBlock(bot, 'chest', 32);
if (!chest) {
log(bot, `Could not find a chest nearby.`);
return false;
}
let item = bot.inventory.items().find(item => item.name === itemName);
if (!item) {
log(bot, `You do not have any ${itemName} to put in the chest.`);
return false;
}
let to_put = num === -1 ? item.count : Math.min(num, item.count);
await goToPosition(bot, chest.position.x, chest.position.y, chest.position.z, 2);
const chestContainer = await bot.openContainer(chest);
await chestContainer.deposit(item.type, null, to_put);
await chestContainer.close();
log(bot, `Successfully put ${to_put} ${itemName} in the chest.`);
return true;
}
export async function takeFromChest(bot, itemName, num=-1) {
/**
* Take the given item from the nearest chest, potentially from multiple slots.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item or block name to take from the chest.
* @param {number} num, the number of items to take from the chest. Defaults to -1, which takes all items.
* @returns {Promise<boolean>} true if the item was taken from the chest, false otherwise.
* @example
* await skills.takeFromChest(bot, "oak_log");
* **/
let chest = world.getNearestBlock(bot, 'chest', 32);
if (!chest) {
log(bot, `Could not find a chest nearby.`);
return false;
}
await goToPosition(bot, chest.position.x, chest.position.y, chest.position.z, 2);
const chestContainer = await bot.openContainer(chest);
// Find all matching items in the chest
let matchingItems = chestContainer.containerItems().filter(item => item.name === itemName);
if (matchingItems.length === 0) {
log(bot, `Could not find any ${itemName} in the chest.`);
await chestContainer.close();
return false;
}
let totalAvailable = matchingItems.reduce((sum, item) => sum + item.count, 0);
let remaining = num === -1 ? totalAvailable : Math.min(num, totalAvailable);
let totalTaken = 0;
// Take items from each slot until we've taken enough or run out
for (const item of matchingItems) {
if (remaining <= 0) break;
let toTakeFromSlot = Math.min(remaining, item.count);
await chestContainer.withdraw(item.type, null, toTakeFromSlot);
totalTaken += toTakeFromSlot;
remaining -= toTakeFromSlot;
}
await chestContainer.close();
log(bot, `Successfully took ${totalTaken} ${itemName} from the chest.`);
return totalTaken > 0;
}
export async function viewChest(bot) {
/**
* View the contents of the nearest chest.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @returns {Promise<boolean>} true if the chest was viewed, false otherwise.
* @example
* await skills.viewChest(bot);
* **/
let chest = world.getNearestBlock(bot, 'chest', 32);
if (!chest) {
log(bot, `Could not find a chest nearby.`);
return false;
}
await goToPosition(bot, chest.position.x, chest.position.y, chest.position.z, 2);
const chestContainer = await bot.openContainer(chest);
let items = chestContainer.containerItems();
if (items.length === 0) {
log(bot, `The chest is empty.`);
}
else {
log(bot, `The chest contains:`);
for (let item of items) {
log(bot, `${item.count} ${item.name}`);
}
}
await chestContainer.close();
return true;
}
export async function consume(bot, itemName="") {
/**
* Eat/drink the given item.
* @param {MinecraftBot} bot, reference to the minecraft bot.
* @param {string} itemName, the item to eat/drink.
* @returns {Promise<boolean>} true if the item was eaten, false otherwise.
* @example
* await skills.eat(bot, "apple");
**/
let item, name;
if (itemName) {
item = bot.inventory.items().find(item => item.name === itemName);
name = itemName;