people/actions/craft.lua

81 lines
2.8 KiB
Lua

local dbg
if moddebug then dbg=moddebug.dbg("people") else dbg={v1=function() end,v2=function() end,v3=function() end} end
people.actions.craft = function(state)
if type(state.action.num) ~= "number" then
dbg.v1(state.ent.name.." has invalid num for craft action")
return true, false
end
if type(state.action.item) ~= "string" then
dbg.v1(state.ent.name.." has invalid item for craft action")
return true, false
end
-- TODO check it's a real item too!
local recipes = minetest.get_all_craft_recipes(state.action.item)
if not recipes or #recipes == 0 then
dbg.v2(state.ent.name.." can't craft "..state.action.item.. " - no recipes")
return true, false
end
local tomake = state.action.num
for _, recipe in pairs(recipes) do
dbg.v3(state.ent.name.." trying recipe "..minetest.serialize(recipe))
if recipe.type == "normal" then
local output = ItemStack(recipe.output)
local needed = {}
for _, item in pairs(recipe.items) do
-- TODO - we can't handle groups in recipes here yet, so
-- we'll just translate things as we come across
-- them for now.
if item == "group:stick" then
item = "default:stick"
elseif item == "group:wood" then
item = "default:wood"
end
if needed[item] then
needed[item] = needed[item] + 1
else
needed[item] = 1
end
end
while tomake > 0 do
local gotingredients = true
for item, count in pairs(needed) do
if not state.ent.inventory:contains_item("main", ItemStack(item.." "..count)) then
dbg.v3(state.ent.name.." doesn't have the "..count.." "..item.." needed")
gotingredients = false
break
end
end
if not gotingredients then break end
for item, count in pairs(needed) do
state.ent.inventory:remove_item("main", ItemStack(item.." "..count))
end
state.ent.inventory:add_item("main", output)
dbg.v3(state.ent.name.." crafted "..output:get_count().." "..state.action.item)
tomake = tomake - output:get_count()
end
else
dbg.v3(state.ent.name.." doesn't know how to do '"..recipe.type.."'")
end
end
if tomake <= 0 then
dbg.v1(state.ent.name.." successfully crafted "..state.action.num.." "..state.action.item)
return true, true
end
dbg.v1(state.ent.name.." couldn't craft (any or enough) "..state.action.item)
return true, false
end