Add rp_checkitem mod

This commit is contained in:
Wuzzy 2023-02-01 22:40:35 +01:00
parent 53cc15d5f3
commit a647f216ca
3 changed files with 75 additions and 0 deletions

19
mods/rp_checkitem/API.md Normal file
View File

@ -0,0 +1,19 @@
This tiny mod lets you know when a player got a new item.
This mod is currently not recommended to be used outside of Repixture yet.
Its only function is:
## `rp_checkitem.register_on_got_item(item, callback)`
Registers the function `callback(player)` as an callback for when a player got
or has an item. `callback` might be called repeatedly.
* `item`: Raw item name of item to check for (no `ItemStack` or item count)
* `callback(player)`: Function that is called if `player` has the item
NOTE: `callback` is currently very limited. It might not be called instantly,
depending on how the item got into the player inventory, and it might not
always recognize a gotten item if it was too briefly in the inventory.
Only when the player held on to the item for at least 10 seconds, `callback` is
guaranteed to be called. This behavior might be improved in later versions.

View File

@ -0,0 +1,54 @@
rp_checkitem = {}
-- Time in seconds to check inventory for items
local ITEM_CHECK_TIME = 10
local items_to_watch = {}
function rp_checkitem.register_on_got_item(item, callback)
table.insert(items_to_watch, {item=item, callback=callback})
end
minetest.register_on_joinplayer(function(player)
local inv = player:get_inventory()
for i=1, #items_to_watch do
local entry = items_to_watch[i]
if inv:contains_item("main", entry.item) then
entry.callback(player)
end
end
end)
minetest.register_on_player_inventory_action(function(player, action, inventory, inventory_info)
if action == "put" then
local itemname = inventory_info.stack:get_name()
for i=1, #items_to_watch do
local entry = items_to_watch[i]
if inventory_info.stack:get_name() == entry.item then
entry.callback(player)
end
end
end
end)
local timer = 0
minetest.register_globalstep(function(dtime)
timer = timer + dtime
if timer < ITEM_CHECK_TIME then
return
end
timer = 0
local players = minetest.get_connected_players()
for p=1, #players do
local player = players[p]
local inv = player:get_inventory()
for i=1, #items_to_watch do
local entry = items_to_watch[i]
if inv:contains_item("main", entry.item) then
entry.callback(player)
end
end
end
end)

View File

@ -0,0 +1,2 @@
name = rp_checkitem
description = Helper mod, provides callback to be called when player got an item