89 lines
2.8 KiB
Lua
89 lines
2.8 KiB
Lua
-- server/leaderboard.lua
|
||
print("^2[turfwar]^7 server/leaderboard.lua LOADED")
|
||
|
||
-- We assume Turfs runtime table exists in server/main.lua as `local Turfs = {}`
|
||
-- and Config.GANGS exists.
|
||
-- We will be defensive: if Turfs isn't visible here, we’ll use an exported getter you can add (optional).
|
||
|
||
local function getTurfsRuntime()
|
||
-- If Turfs is global somewhere, use it.
|
||
if Turfs then return Turfs end
|
||
|
||
-- If Turfs is local in main.lua (as in your paste), this file cannot see it.
|
||
-- In that case, you must either:
|
||
-- A) Move leaderboard code into server/main.lua, OR
|
||
-- B) Make Turfs global in main.lua: change `local Turfs = {}` to `Turfs = {}`
|
||
return nil
|
||
end
|
||
|
||
local function buildLeaderboard()
|
||
local t = getTurfsRuntime()
|
||
if not t then
|
||
return {
|
||
title = "Most influence",
|
||
rows = {},
|
||
error = "Turfs runtime not visible. In server/main.lua change `local Turfs = {}` to `Turfs = {}`."
|
||
}
|
||
end
|
||
|
||
-- count owned turfs per gang
|
||
local counts = {} -- [gangId] = n
|
||
for _, turf in pairs(t) do
|
||
local owner = tonumber(turf.owner) or 0
|
||
if owner ~= 0 then
|
||
counts[owner] = (counts[owner] or 0) + 1
|
||
end
|
||
end
|
||
|
||
-- build sortable rows
|
||
local rows = {}
|
||
for gangId, info in pairs(Config.GANGS or {}) do
|
||
gangId = tonumber(gangId) or 0
|
||
if gangId ~= 0 then
|
||
local c = counts[gangId] or 0
|
||
rows[#rows + 1] = {
|
||
gangId = gangId,
|
||
name = info.name or ("Gang " .. tostring(gangId)),
|
||
value = c
|
||
}
|
||
end
|
||
end
|
||
|
||
table.sort(rows, function(a, b)
|
||
if a.value == b.value then
|
||
return a.name < b.name
|
||
end
|
||
return a.value > b.value
|
||
end)
|
||
|
||
-- Keep only gangs that exist in config; you can also filter out zeroes if you want:
|
||
-- (comment in if you only want gangs with >0)
|
||
-- local filtered = {}
|
||
-- for _, r in ipairs(rows) do if r.value > 0 then filtered[#filtered+1]=r end end
|
||
-- rows = filtered
|
||
|
||
return {
|
||
title = "Most influence",
|
||
rows = rows
|
||
}
|
||
end
|
||
|
||
local function broadcastLeaderboard()
|
||
local payload = buildLeaderboard()
|
||
TriggerClientEvent("turfwar:leaderboard:update", -1, payload)
|
||
end
|
||
|
||
-- Clients can request snapshot
|
||
RegisterNetEvent("turfwar:leaderboard:request", function()
|
||
local src = source
|
||
TriggerClientEvent("turfwar:leaderboard:update", src, buildLeaderboard())
|
||
end)
|
||
|
||
-- Let other server code trigger refresh
|
||
RegisterNetEvent("turfwar:leaderboard:refresh", function()
|
||
broadcastLeaderboard()
|
||
end)
|
||
|
||
-- Export for other resources if needed
|
||
exports("BroadcastLeaderboard", broadcastLeaderboard)
|