86 lines
2.1 KiB
Lua
86 lines
2.1 KiB
Lua
local itemstack = require("itemstack")
|
|
local stackgroup = require("stackgroup")
|
|
local util = require("util")
|
|
|
|
|
|
local prototype = {}
|
|
function prototype:getCost()
|
|
local costs = {}
|
|
for _,input in pairs(self.inputs) do
|
|
local itemCost = util.find(costs, function(_, item) return item == input.item end)
|
|
if itemCost == nil then
|
|
itemCost = 0
|
|
end
|
|
|
|
costs[input.item] = itemCost + input.count
|
|
end
|
|
|
|
return costs
|
|
end
|
|
|
|
-- Returns table of item -> missing-count mappings. Empty table if recipe can be afforded
|
|
function prototype:canAfford(chests)
|
|
local storage = stackgroup.fromChests(table.unpack(chests))
|
|
local costs = self:getCost()
|
|
|
|
local missing = {}
|
|
for item,cost in pairs(costs) do
|
|
local group = storage:findGroup(item)
|
|
if group == nil or group.total < cost then
|
|
local totalMissing = cost
|
|
if group ~= nil then
|
|
totalMissing = totalMissing - group.total
|
|
end
|
|
missing[item] = totalMissing
|
|
end
|
|
end
|
|
|
|
return missing
|
|
end
|
|
|
|
function prototype:beginCrafting(chests)
|
|
local storage = stackgroup.fromChests(table.unpack(chests))
|
|
|
|
for _,input in pairs(self.inputs) do
|
|
local group = storage:findGroup(input.item)
|
|
group:moveItemsToPeripheral(chests, input.count, input.machine, input.slot)
|
|
end
|
|
|
|
-- Return poll function to check for readiness
|
|
return function()
|
|
for _,output in pairs(self.outputs) do
|
|
local stackdata = itemstack.fromSlot(output.machine, output.slot)
|
|
|
|
if output.item ~= stackdata.item or output.count > stackdata.count then
|
|
return false
|
|
end
|
|
end
|
|
|
|
return true
|
|
end
|
|
end
|
|
|
|
local recipe = {}
|
|
|
|
-- Input or output of a recipe
|
|
function recipe.component(machine, slot, item, count)
|
|
return {
|
|
machine = machine,
|
|
slot = slot,
|
|
item = item,
|
|
count = count
|
|
}
|
|
end
|
|
|
|
function recipe.create(inputs, outputs)
|
|
local recipeDef = {
|
|
inputs = inputs,
|
|
outputs = outputs
|
|
}
|
|
|
|
setmetatable(recipeDef, { __index = prototype })
|
|
|
|
return recipeDef
|
|
end
|
|
|
|
return recipe |