powerguns-cd2025/workbench.lua
2024-12-27 20:33:21 +01:00

97 lines
2.4 KiB
Lua

local desc, tiles = ...
local S = core.get_translator(core.get_current_modname())
local t = {}
local modname = core.get_current_modname()
local name = modname .. ":workbench"
local recipes = {}
local function make_formspec(selected_item)
local f = {}
table.insert(f,"formspec_version[5]size[10,10]")
local i = 0.3
for k,v in pairs(recipes) do
if not v.alias then
table.insert(f,"item_image_button["..(i%10)..","..(math.floor(i/10)+0.3)..";1,1;"..k..";"..k..";]")
i = i + 1
end
end
if selected_item then
local i = 0.3
for _,v in ipairs(recipes[selected_item]) do
table.insert(f,"item_image_button[".. (i%7) ..","..(math.floor(i/7)+7.7)..";1,1;"..v..";"..v..";]")
i = i + 1
end
table.insert(f,"button[8,8.3;2,1;craft_"..selected_item..";"..S("Craft").."]")
end
return table.concat(f)
end
t.register_craft = function(craft, is_alias)
local counting = {}
for _,v in ipairs(craft.recipe) do
for _,w in ipairs(v) do
local is = ItemStack(w)
w = is:get_name()
if recipes[w] and recipes[w].alias then
for k,v in pairs(recipes[w]) do
if k ~= "alias" then
counting[k] = (counting[k] or 0) + v*is:get_count()
end
end
else
counting[w] = (counting[w] or 0) + is:get_count()
end
end
end
local new_recipe = {}
if is_alias then
counting.alias = true
recipes[craft.output] = counting
else
for k,v in pairs(counting) do
table.insert(new_recipe, k.." "..v)
end
recipes[craft.output] = new_recipe
end
end
core.register_node(name, {
description = desc,
groups = {cracky = 3, oddly_breakable_by_hand = 3},
tiles = tiles,
on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
if clicker:is_player() then
core.show_formspec(clicker:get_player_name(), name, make_formspec())
end
end,
})
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= name then
return
end
for k,v in pairs(fields) do
if k:find("^craft_") then
local result = k:sub(7)
local inv = player:get_inventory()
if inv:room_for_item("main", result) then
for _,v in ipairs(recipes[result]) do
if not inv:contains_item("main", v) then return end
end
for _,v in ipairs(recipes[result]) do
inv:remove_item("main", v)
end
inv:add_item("main", result)
end
return
end
if k:find(modname..":") then
minetest.show_formspec(player:get_player_name(), name, make_formspec(k))
return
end
end
end)
return t