diff --git a/lib/plugins/digging.js b/lib/plugins/digging.js index d9d26a0fd..c355adfc9 100644 --- a/lib/plugins/digging.js +++ b/lib/plugins/digging.js @@ -7,12 +7,23 @@ module.exports = inject function inject (bot) { let swingInterval = null - let waitTimeout = null + let waitInterval = null let diggingTask = createDoneTask() bot.targetDigBlock = null bot.lastDigTime = null + bot.digPercentage = 0 + bot.lastHeldItemName = '' + if (bot.heldItem) { bot.lastHeldItemName = bot.heldItem.name } + bot.on('heldItemChanged', () => { + let nameToCompare = '' + if (bot.heldItem) { nameToCompare = bot.heldItem.name } + if (bot.lastHeldItemName !== nameToCompare) { + bot.lastHeldItemName = nameToCompare + bot.digPercentage = 0 + } + }) async function dig (block, forceLook, digFace) { if (block === null || block === undefined) { @@ -110,20 +121,30 @@ function inject (bot) { location: block.position, face: diggingFace // default face is 1 (top) }) - const waitTime = bot.digTime(block) - waitTimeout = setTimeout(finishDigging, waitTime) + if (waitInterval) { clearInterval(waitInterval) } + waitInterval = setInterval(() => { + bot.digPercentage += (50 / bot.digTime(block)) + if (bot.digPercentage >= 1.0) { + finishDigging() + } + }, 50) bot.targetDigBlock = block bot.swingArm() swingInterval = setInterval(() => { - bot.swingArm() - }, 350) + if (bot.targetDigBlock) { + bot.swingArm() + } else { + clearInterval(swingInterval) + } + }, 250) function finishDigging () { + bot.digPercentage = 0 clearInterval(swingInterval) - clearTimeout(waitTimeout) + clearInterval(waitInterval) swingInterval = null - waitTimeout = null + waitInterval = null if (bot.targetDigBlock) { bot._client.write('block_dig', { status: 2, // finish digging @@ -143,9 +164,10 @@ function inject (bot) { if (!bot.targetDigBlock) return bot.removeListener(eventName, onBlockUpdate) clearInterval(swingInterval) - clearTimeout(waitTimeout) + bot.digPercentage = 0 + clearInterval(waitInterval) swingInterval = null - waitTimeout = null + waitInterval = null bot._client.write('block_dig', { status: 1, // cancel digging location: bot.targetDigBlock.position, @@ -162,13 +184,13 @@ function inject (bot) { function onBlockUpdate (oldBlock, newBlock) { // vanilla server never actually interrupt digging, but some server send block update when you start digging // so ignore block update if not air - // All block update listeners receive (null, null) when the world is unloaded. So newBlock can be null. if (newBlock?.type !== 0) return bot.removeListener(eventName, onBlockUpdate) clearInterval(swingInterval) - clearTimeout(waitTimeout) + clearInterval(waitInterval) swingInterval = null - waitTimeout = null + waitInterval = null + bot.digPercentage = 0.0 bot.targetDigBlock = null bot.lastDigTime = performance.now() bot.emit('diggingCompleted', newBlock)