feat(turtle-utils): add compactInventory
This commit is contained in:
parent
66e9eff8ac
commit
8483ffc696
@ -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
|
||||
Loading…
Reference in New Issue
Block a user