From 9865ab72f7438fff9d74f2fe19a138da870c41aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=96=B9=E8=80=8C=E9=9D=99?= Date: Sat, 30 Dec 2023 22:14:38 +0800 Subject: [PATCH] Fix `bot.heldItem` and `bot.entity.equipment` (#3225) * implement `bot.heldItem` with getter function * fix bot.entity.equipment * restart CI * add test for `bot.heldItem` --- lib/plugins/inventory.js | 24 ++++++++++++++++++++---- test/externalTests/heldItem.js | 16 ++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 test/externalTests/heldItem.js diff --git a/lib/plugins/inventory.js b/lib/plugins/inventory.js index b532b95c2..1ca28f8fb 100644 --- a/lib/plugins/inventory.js +++ b/lib/plugins/inventory.js @@ -43,8 +43,26 @@ function inject (bot, { hideErrors }) { bot.quickBarSlot = null bot.inventory = windows.createWindow(0, 'minecraft:inventory', 'Inventory') bot.currentWindow = null - bot.heldItem = null bot.usingHeldItem = false + Object.defineProperty(bot, 'heldItem', { + get: function () { + return bot.inventory.slots[bot.QUICK_BAR_START + bot.quickBarSlot] + } + }) + + bot.on('spawn', () => { + Object.defineProperty(bot.entity, 'equipment', { + get: bot.supportFeature('doesntHaveOffHandSlot') + ? function () { + return [bot.heldItem, bot.inventory.slots[8], bot.inventory.slots[7], + bot.inventory.slots[6], bot.inventory.slots[5]] + } + : function () { + return [bot.heldItem, bot.inventory.slots[45], bot.inventory.slots[8], + bot.inventory.slots[7], bot.inventory.slots[6], bot.inventory.slots[5]] + } + }) + }) bot._client.on('entity_status', (packet) => { if (packet.entityId === bot.entity.id && packet.entityStatus === 9 && !eatingTask.done) { @@ -364,9 +382,7 @@ function inject (bot, { hideErrors }) { } function updateHeldItem () { - bot.heldItem = bot.inventory.slots[bot.QUICK_BAR_START + bot.quickBarSlot] - bot.entity.heldItem = bot.heldItem - bot.emit('heldItemChanged', bot.entity.heldItem) + bot.emit('heldItemChanged', bot.heldItem) } function closeWindow (window) { diff --git a/test/externalTests/heldItem.js b/test/externalTests/heldItem.js new file mode 100644 index 000000000..51286db0a --- /dev/null +++ b/test/externalTests/heldItem.js @@ -0,0 +1,16 @@ +const assert = require('assert') + +module.exports = () => async (bot) => { + const Item = require('prismarine-item')(bot.registry) + + await bot.test.becomeCreative() + await bot.test.clearInventory() + assert.equal(bot.heldItem, null) + + const stoneId = bot.registry.itemsByName.stone.id + await bot.test.setInventorySlot(36, new Item(stoneId, 1)) + assert.strictEqual(bot.heldItem.id, bot.stoneId) + + await bot.tossStack(bot.heldItem) + assert.equal(bot.heldItem, null) +}