Improve initial_stuff

This commit is contained in:
LoneWolfHT 2020-10-13 16:22:19 -07:00
parent 973f01b0a9
commit eb5ea25d54
2 changed files with 57 additions and 8 deletions

View file

@ -58,6 +58,8 @@ ctf_classes.register_on_changed(function(player, old, new)
for i = 1, #items do
give_initial_stuff.give_item(inv, ItemStack(items[i]))
end
give_initial_stuff(player, "replace_tools")
end
end)

View file

@ -1,7 +1,43 @@
give_initial_stuff = {}
local tools = {"default:sword_", "default:pick_", "default:axe_", "default:shovel_"}
local tool_materials = {"stone", "steel", "bronze", "mese", "diamond"}
-- Add item to inv. Split item if count > stack_max using recursion
function give_initial_stuff.give_item(inv, item)
-- Remove any lower tier tools of the same type as the item
for _, tool in pairs(tools) do
if item:get_name():find(tool) then -- Find what tool the new item is
-- Get the 'tier' of the new item
local newtier = table.indexof(tool_materials, item:get_name():sub(tool:len() + 1))
for tier, mat in ipairs(tool_materials) do
if tier < newtier then
inv:remove_item("main", tool..mat) -- Will do nothing if tool doesn't exist
elseif inv:contains_item("main", tool..mat) then
return -- A higher tier tool is already in inventory
end
end
end
end
-- Don't duplicate stacks
if inv:contains_item("main", item:get_name()) then
local safeguard = 1
-- Do a fast refill of stack if needed
while not inv:contains_item("main", item:get_name().." "..item:get_stack_max()-5) do
safeguard = safeguard + 1
inv:add_item("main", item:get_name().." 5")
if safeguard >= 500 then
minetest.log("error", "[give_initial_stuff] Something went wrong when filling stack "..dump(item:get_name()))
break
end
end
return
end
inv:add_item("main", item:take_item(item:get_stack_max()))
-- If item isn't empty, add the leftovers again
@ -11,23 +47,34 @@ function give_initial_stuff.give_item(inv, item)
end
setmetatable(give_initial_stuff, {
__call = function(self, player)
__call = function(self, player, mode)
minetest.log("action", "Giving initial stuff to player "
.. player:get_player_name())
local inv = player:get_inventory()
if mode ~= "replace_tools" then
inv:set_list("main", {})
inv:set_list("craft", {})
inv:set_size("craft", 1)
inv:set_size("craftresult", 0)
inv:set_size("hand", 0)
end
local items = give_initial_stuff.get_stuff(player)
for _, item in pairs(items) do
if mode == "replace_tools" then
for _, tool in pairs(tools) do
if item:find(tool) then
give_initial_stuff.give_item(inv, ItemStack(item))
end
end
else
give_initial_stuff.give_item(inv, ItemStack(item))
end
end
end
})
local registered_stuff_providers = {}