ns09005264

turtle_crafting_v2

Jul 5th, 2023 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.29 KB | Gaming | 0 0
  1. CHANNEL_BROADCAST = 11
  2. CHANNEL_PROTOCOL = "recipe_11"
  3. CHANNEL_FEEDBACK_PROTOCOL = "recipe_11_feedback"
  4. rednet.open("right")
  5. local storage_slots = { 1, 2, 3, 4, 8, 12 }
  6.  
  7. local function transferTo(slots, targetSlot, count)
  8.     for _, slot in ipairs(slots) do
  9.         if slot.count > 0 then
  10.             turtle.select(slot.slot)
  11.             if count > slot.count then
  12.                 turtle.transferTo(targetSlot, slot.count)
  13.                 count = count - slot.count
  14.                 slot.count = 0
  15.             else
  16.                 turtle.transferTo(targetSlot, count)
  17.                 slot.count = slot.count - count
  18.                 break
  19.             end
  20.         end
  21.     end
  22. end
  23.  
  24. local function clearInventory()
  25.     for i = 1, 16 do
  26.         local count = turtle.getItemCount(i)
  27.         if count > 0 then
  28.             turtle.select(i)
  29.             turtle.dropDown(count)
  30.         end
  31.     end
  32. end
  33.  
  34. local function craft(recipe)
  35.     local materials = {}
  36.     for slot = 1, 9 do
  37.         turtle.select(slot)
  38.         if turtle.suck() == false then
  39.             break
  40.         end
  41.         local itemDetail = turtle.getItemDetail(slot)
  42.         if materials[itemDetail.name] == nil then
  43.             materials[itemDetail.name] = { total = 0, slots = {} }
  44.         end
  45.         materials[itemDetail.name].total = materials[itemDetail.name].total + itemDetail.count
  46.         table.insert(materials[itemDetail.name].slots, { slot = slot, count = itemDetail.count })
  47.         -- 排序slots, 从大到小
  48.         table.sort(materials[itemDetail.name].slots, function(a, b) return a.slot > b.slot end)
  49.     end
  50.     for index = #recipe, 1, -1 do
  51.         if recipe[index] ~= nil then
  52.             local name = recipe[index].name
  53.             transferTo(materials[name].slots, recipe[index].slot, recipe[index].count)
  54.         end
  55.     end
  56.     turtle.select(1)
  57.     turtle.craft()
  58.     for slot = 1, 16 do
  59.         turtle.select(slot)
  60.         local success = turtle.dropUp()
  61.         if success == false then
  62.             break
  63.         end
  64.     end
  65. end
  66.  
  67. while true do
  68.     local _, message = rednet.receive(CHANNEL_PROTOCOL)
  69.     print("received recipe: " .. message)
  70.     clearInventory()
  71.     local recipe = textutils.unserialise(message)
  72.     craft(recipe)
  73.     rednet.broadcast("done", CHANNEL_FEEDBACK_PROTOCOL)
  74. end
  75.  
Add Comment
Please, Sign In to add comment