From 8483ffc6961f37dc7de6c475bf0249f80dd16871 Mon Sep 17 00:00:00 2001 From: Guillaume ARM Date: Sun, 19 May 2024 19:37:16 +0200 Subject: [PATCH] feat(turtle-utils): add compactInventory --- libs/turtle-utils.lua | 72 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 3 deletions(-) diff --git a/libs/turtle-utils.lua b/libs/turtle-utils.lua index 1f58076..e247b3a 100644 --- a/libs/turtle-utils.lua +++ b/libs/turtle-utils.lua @@ -13,6 +13,15 @@ turtleUtils.getInventory = function(side) return nil end +turtleUtils.getItemName = function(slotIndex) + local item = turtle.getItemDetail(i) + return item and item.name +end + +turtleUtils.getItemCount = function(slotIndex) + return turtle.getItemCount(slotIndex) +end + local function waitFor(predicate, sleepTime) sleepTime = sleepTime or DEFAULT_IDLE_TIME @@ -151,9 +160,7 @@ end turtleUtils.selectItemByName = function(itemName) for i = 1, 16, 1 do - local item = turtle.getItemDetail(i) - - if item and item.name == itemName then + if itemName == turtleUtils.getItemName(i) then turtle.select(i) return true end @@ -202,4 +209,63 @@ turtleUtils.refuelAllFromInventory = function() end end +-- utils function used by "compactInventory" +local function getItemsMap() + local result = {} + + for i=1, 16, 1 do + local itemName = turtleUtils.getItemName(i) + + if itemName then + local nbSlotUsed = result[itemName] or 0 + result[itemName] = nbSlotUsed + 1 + end + end + + return result +end + +local function getSlotsWithSpaces(itemName) + local slots = {} + + for i=1, 16, 1 do + if turtleUtils.getItemName(i) == itemName then + if turtle.getItemSpace(i) > 0 then + table.insert(slots, i) + end + end + end + + return slots +end + +local function compactItem(itemName) + while true do + local slots = getSlotsWithSpaces(itemName) + + if #slots < 2 then + break + end + + turtle.select(slots[1]) + turtle.transferTo(slots[2], turtle.getItemSpace(slots[2])) + end +end + +-- Compact the internal turtle inventory +turtleUtils.compactInventory = function() + local initialSelectedSlot = turtle.getSelectedSlot() + local itemsMap = getItemsMap() + + for itemName, nbSlotUsed in pairs(itemsMap) do + if nbSlotUsed > 1 then + compactItem(itemName) + end + end + + if initialSelectedSlot ~= turtle.getSelectedSlot() then + turtle.select(initialSelectedSlot) + end +end + return turtleUtils \ No newline at end of file