-
Notifications
You must be signed in to change notification settings - Fork 11
/
highscore.lua
64 lines (51 loc) · 1.38 KB
/
highscore.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
-- ordered list: { name: '', xp: 0 }
xp_redo.highscore = {}
local fname = minetest.get_worldpath().."/highscore.txt"
local write_file = function()
local f = io.open(fname, "w")
local data_string = minetest.serialize(xp_redo.highscore)
f:write(data_string)
io.close(f)
end
local f = io.open(fname, "r")
if f then -- file exists
local data_string = f:read("*all")
xp_redo.highscore = minetest.deserialize(data_string)
io.close(f)
else
write_file()
end
local update_highscore = function()
local players = minetest.get_connected_players()
for _,player in pairs(players) do
local name = player:get_player_name()
local xp = player:get_meta():get_int("xp")
local found = false
for _,entry in pairs(xp_redo.highscore) do
if entry.name == name then
-- connected player already exists in highscore, update value
entry.xp = xp
found = true
end
end
if not found then
-- create new entry
table.insert(xp_redo.highscore, { name=name, xp=xp })
end
end
-- sort
table.sort(xp_redo.highscore, function(a,b) return a.xp > b.xp end)
-- truncate
while table.getn(xp_redo.highscore) > 10 do
table.remove(xp_redo.highscore, table.getn(xp_redo.highscore))
end
end
local timer = 0
minetest.register_globalstep(function(dtime)
timer = timer + dtime;
if timer >= 60 then
update_highscore()
write_file()
timer = 0
end
end)