diff --git a/craftingTurtle.lua b/craftingTurtle.lua index 0907585..19cd725 100644 --- a/craftingTurtle.lua +++ b/craftingTurtle.lua @@ -180,30 +180,56 @@ local function handleCraftCommand(message) for turtleSlotStr, info in pairs(slots) do local turtleSlot = tonumber(turtleSlotStr) - local chestName = info.chestName - local chestSlot = info.chestSlot local itemName = info.itemName local count = info.count or 1 + local placed = 0 - print(string.format("[CRAFT] Pulling %s from %s slot %d -> turtle slot %d", - itemName, chestName, chestSlot, turtleSlot)) - - local chest = peripheral.wrap(chestName) - if not chest then - print(string.format("[CRAFT] Cannot wrap chest: %s", chestName)) - allPlaced = false - break - end - local ok, n = pcall(chest.pushItems, selfName, chestSlot, count, turtleSlot) - if ok and n and n > 0 then - placedItems[turtleSlot] = itemName - print(string.format("[CRAFT] Placed %s x%d in slot %d", itemName, n, turtleSlot)) - else - if not ok then - print(string.format("[CRAFT] pullItems error: %s", tostring(n))) - else - print(string.format("[CRAFT] pullItems returned %s (expected %d)", tostring(n), count)) + -- Try the suggested chest+slot first + local chest = peripheral.wrap(info.chestName) + if chest then + local ok, n = pcall(chest.pushItems, selfName, info.chestSlot, count, turtleSlot) + if ok and n and n > 0 then + placed = n end + end + + -- If we didn't get enough, search ALL chests on the network for this item + if placed < count then + local remaining = count - placed + if placed == 0 then + print(string.format("[CRAFT] %s not at %s:%d, searching network...", + itemName, info.chestName, info.chestSlot)) + else + print(string.format("[CRAFT] Got %d/%d %s from hint, searching for %d more...", + placed, count, itemName, remaining)) + end + + for _, chestName in ipairs(returnChests) do + if remaining <= 0 then break end + local ch = peripheral.wrap(chestName) + if ch then + local contents = ch.list() + if contents then + for slot, slotItem in pairs(contents) do + if slotItem.name == itemName then + local ok, n = pcall(ch.pushItems, selfName, slot, remaining, turtleSlot) + if ok and n and n > 0 then + placed = placed + n + remaining = remaining - n + if remaining <= 0 then break end + end + end + end + end + end + end + end + + if placed > 0 then + placedItems[turtleSlot] = itemName + print(string.format("[CRAFT] Placed %s x%d in slot %d", itemName, placed, turtleSlot)) + else + print(string.format("[CRAFT] Could not find %s anywhere on network!", itemName)) allPlaced = false break end