commit 2c5c73917d909fb0865ebf2abab437350c96b22b Author: D4VID Date: Sat Oct 5 22:21:51 2024 +0200 Crafting a recipe diff --git a/craft.lua b/craft.lua new file mode 100644 index 0000000..b36d927 --- /dev/null +++ b/craft.lua @@ -0,0 +1,78 @@ +local component = require("component") +local robot = require("robot") +local sides = require("sides") + +local crafting = component.crafting +local inventory = component.inventory_controller + +RESULT_SLOT = 4 + +local iron_pickaxe_recipe = { + result = { + name = 'minecraft:iron_pickaxe', + count = 1, + }, + ingredients = { + 'minecraft:iron_ingot', 'minecraft:iron_ingot', 'minecraft:iron_ingot', + nil, 'minecraft:stick', nil, + nil, 'minecraft:stick', nil, + } +} + +-- robots inventory is 4 wide and crafting uses the top left portion +local slot_map = { + 1,2,3, + 5,6,7, + 9,10,11 +} + +-- Search the facing chest for "item" and take "count" items and place them in "slot" +-- Returns number of items fetched +local function fetch_item(item, output_slot) + robot.select(output_slot) + local size = inventory.getInventorySize(sides.forward) + if not size then + print('Not facing a chest') + return false + end + + for slot = 1, size do + local stack = inventory.getStackInSlot(sides.forward, slot) + if stack then + if stack.name == item then + inventory.suckFromSlot(sides.forward, slot, 1) + return true + end + end + end + + print('Missing ' .. item) + return false +end + +-- accepts a recipe table containing result and ingredients +local function craft_recipe(recipe) + for i, ingredient in pairs(recipe.ingredients) do + print('Fetching ' .. ingredient) + fetch_item(ingredient, slot_map[i]) + end + + -- select slot for the result + robot.select(RESULT_SLOT) + + -- craft the resulting item + local crafted = crafting.craft(1) + + if not crafted then + print('Crafting failed') + end +end + +-- local target = ... + +-- if not target then +-- print("Usage: craft ") +-- return +-- end + +craft_recipe(iron_pickaxe_recipe)