Add exp_statistics plugin for player statistics

Player statistics move out of exp_legacy into their own plugin, with the
totals kept on the controller instead of the PlayerData datastore, which
was never synced anywhere.

The lua module tracks the same statistics with the same rules. Gains are
kept per player as unsent in storage and sent over IPC every 5 minutes
for every player with changes, and for one player when they leave. Sent
values move into the totals the controller gave when the player joined,
so get() is the total on every server either way.

Nothing is resent. The instance plugin sends everything left when the
server stops and drops anything unsent when it starts. A leftover can
only come from a save made before it was sent, such as the autosave
loaded after a crash, so dropping it loses a few minutes at worst but
never counts twice.

The controller adds the deltas to a record per player name in
database/exp_statistics/players.json. Instances fetch a player's totals
on join and hand them to lua over rcon. The web UI gets a sortable table
of every player at /exp_statistics, behind exp_statistics.view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bbassieandClaude Opus 5.5 committed 2026-10-14 22:44:59 +00:00
1 parent 420506451e
commit d1b22dd4e7
27 files changed
+1806

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
--[[-- ExpStatistics - Config
Which statistics are tracked, and the order they are shown in.
]]
local e = defines.events
return {
MapsPlayed = true, -- Maps a player has joined at least once
Playtime = true, -- Minutes online
AfkTime = true, -- Minutes online after doing nothing for 5 minutes
DistanceTravelled = true, -- Tiles moved while not afk
MachinesRemoved = true, -- Own force entities marked for deconstruction or mined
TreesDestroyed = true, -- Trees marked for deconstruction or mined
OreMined = true, -- Resources mined by hand
DamageDealt = true, -- Damage to entities not on the same force or neutral
Kills = true, -- Entities killed which are not on the same force or neutral
RocketsLaunched = true, -- Counted for every online player on the force
ResearchCompleted = true, -- Counted for every online player on the force
--- Statistics that go up by one each time the event is raised for a player
--- @type table<string, defines.events>
counters = {
MachinesBuilt = e.on_built_entity,
MapTagsMade = e.on_chart_tag_added,
ChatMessages = e.on_console_chat,
CommandsUsed = e.on_console_command,
ItemsPickedUp = e.on_picked_up_item,
TilesBuilt = e.on_player_built_tile,
ItemsCrafted = e.on_player_crafted_item,
DeconstructionPlannerUsed = e.on_player_deconstructed_area,
Deaths = e.on_player_died,
JoinCount = e.on_player_joined_game,
TilesRemoved = e.on_player_mined_tile,
CapsulesUsed = e.on_player_used_capsule,
EntityRepaired = e.on_player_repaired_entity,
},
--- The order statistics are shown in, disabled ones are skipped
display_order = {
"Playtime", "AfkTime",
"MapsPlayed", "JoinCount",
"ChatMessages", "CommandsUsed",
"RocketsLaunched", "ResearchCompleted",
"MachinesBuilt", "MachinesRemoved",
"TilesBuilt", "TilesRemoved",
"TreesDestroyed", "OreMined",
"ItemsCrafted", "ItemsPickedUp",
"Kills", "Deaths",
"DamageDealt", "DistanceTravelled",
"CapsulesUsed", "EntityRepaired",
"DeconstructionPlannerUsed", "MapTagsMade",
},
}
+161
View File
@@ -0,0 +1,161 @@
--[[-- ExpStatistics
Player statistics kept on the controller.
What each player gains is kept here as unsent until it is sent to the
controller, every 5 minutes and when the player leaves. Once sent it is added
to the totals the controller gave when the player joined, so get() is the
total across every server either way.
Updates which are lost are not sent again. Anything unsent when the server
starts is from a save made before it was sent, so it is dropped rather than
risk counting it twice.
local ExpStatistics = require("modules/exp_statistics")
ExpStatistics.increment(player, "Kills")
ExpStatistics.get(player, "Kills")
for _, name in ipairs(ExpStatistics.display_order) do end
]]
local clusterio_api = require("modules/clusterio/api")
local ExpUtil = require("modules/exp_util")
local Storage = require("modules/exp_util/storage")
local config = require("modules/exp_statistics/config")
local format_number = require("util").format_number
--- @alias ExpStatistics.Stats table<string, number>
--- @class ExpStatistics.Totals
--- @field name string
--- @field stats ExpStatistics.Stats
--- @class ExpStatistics
local ExpStatistics = {
config = config,
--- Enabled statistics in the order they are shown
--- @type string[]
display_order = {},
--- Shown after the value
--- @type table<string, string>
units = { DistanceTravelled = " tiles" },
}
--- Measured in minutes and shown as a time
local time_statistics = { Playtime = true, AfkTime = true }
local long_time_format = ExpUtil.format_time_factory_locale{ format = "long", coefficient = 3600, hours = true, minutes = true }
local short_time_format = ExpUtil.format_time_factory_locale{ format = "short", coefficient = 3600, hours = true, minutes = true }
for _, name in ipairs(config.display_order) do
if config[name] == true or config.counters[name] then
ExpStatistics.display_order[#ExpStatistics.display_order + 1] = name
end
end
local unsent = {} --- @type table<string, ExpStatistics.Stats>
local totals = {} --- @type table<string, ExpStatistics.Stats>
Storage.register({ unsent, totals }, function(tbl)
unsent = tbl[1]
totals = tbl[2]
end)
--- Add to a statistic of a player
--- @param player LuaPlayer
--- @param statistic string
--- @param amount number? Defaults to 1
function ExpStatistics.increment(player, statistic, amount)
local name = player.name
local stats = unsent[name]
if not stats then
stats = {}
unsent[name] = stats
end
stats[statistic] = (stats[statistic] or 0) + (amount or 1)
end
--- Get the total of a statistic for a player, on every server
--- @param player LuaPlayer | string
--- @param statistic string
--- @return number
function ExpStatistics.get(player, statistic)
local name = type(player) == "string" and player or player.name
local received = totals[name]
local pending = unsent[name]
return (received and received[statistic] or 0) + (pending and pending[statistic] or 0)
end
--- Get the value of a statistic as it is shown to players
--- @param statistic string
--- @param value number
--- @param short boolean? Use the short time format
--- @return LocalisedString
function ExpStatistics.format(statistic, value, short)
if time_statistics[statistic] then
return short and short_time_format(value) or long_time_format(value)
end
return format_number(value, false)
end
--- Move the unsent statistics of a player into their totals
--- @param name string
--- @return ExpStatistics.Stats?
local function take_unsent(name)
local stats = unsent[name]
if not stats then return nil end
unsent[name] = nil
local received = totals[name]
if not received then
received = {}
totals[name] = received
end
for statistic, value in pairs(stats) do
received[statistic] = (received[statistic] or 0) + value
end
return stats
end
--- Send what a player gained to the controller
--- @param name string
function ExpStatistics.send(name)
local stats = take_unsent(name)
if stats then
clusterio_api.send_json("exp_statistics:update", { players = { { name = name, stats = stats } } })
end
end
--- Send what every player gained to the controller, in one update
function ExpStatistics.send_all()
local players, count = {}, 0
for name in pairs(unsent) do
count = count + 1
players[count] = { name = name, stats = take_unsent(name) }
end
if count > 0 then
clusterio_api.send_json("exp_statistics:update", { players = players })
end
end
--- Send what a player gained and forget them, called when they leave
--- @param name string
function ExpStatistics.send_and_forget(name)
ExpStatistics.send(name)
totals[name] = nil
end
--- Called by the instance plugin over rcon when the server starts
function ExpStatistics.discard_unsent()
for name in pairs(unsent) do
unsent[name] = nil
end
end
--- Called by the instance plugin over rcon when a player joins
--- @param payload ExpStatistics.Totals
function ExpStatistics.receive_totals(payload)
local player = game.get_player(payload.name)
if not player or not player.connected then return end
totals[payload.name] = payload.stats
end
return ExpStatistics
+188
View File
@@ -0,0 +1,188 @@
--[[-- ExpStatistics - Events
Tracks the statistics enabled in config.lua, and sends them to the controller.
]]
local ExpStatistics = require("modules/exp_statistics/control")
local config = ExpStatistics.config
local increment = ExpStatistics.increment
local floor = math.floor
local afk_required = 5 * 3600 -- 5 minutes
local send_interval = 5 * 3600 -- 5 minutes
--- @type table<defines.events, fun(event: EventData)>
local events = {}
--- Add a handler, chained after any other for the same event
--- @param event_id defines.events
--- @param handler fun(event: EventData)
local function add(event_id, handler)
local existing = events[event_id]
if existing then
events[event_id] = function(event)
existing(event)
handler(event)
end
else
events[event_id] = handler
end
end
--- Get the player of an event if they are online
--- @param event { player_index: uint? }
--- @return LuaPlayer?
local function get_online_player(event)
if not event.player_index then return nil end
local player = game.players[event.player_index]
if not player or not player.valid or not player.connected then return nil end
return player
end
--- @param event EventData.on_player_left_game
add(defines.events.on_player_left_game, function(event)
local player = game.players[event.player_index]
ExpStatistics.send_and_forget(player.name)
end)
--- @type table<number, fun()>
local on_nth_tick = {
[send_interval] = ExpStatistics.send_all,
}
if config.MapsPlayed then
--- @param event EventData.on_player_created
add(defines.events.on_player_created, function(event)
increment(game.players[event.player_index], "MapsPlayed")
end)
end
if config.Playtime or config.AfkTime then
on_nth_tick[3600] = function()
if game.tick == 0 then return end
for _, player in pairs(game.connected_players) do
if config.Playtime then increment(player, "Playtime") end
if config.AfkTime and player.afk_time > afk_required then increment(player, "AfkTime") end
end
end
end
if config.DistanceTravelled then
--- @param event EventData.on_player_changed_position
add(defines.events.on_player_changed_position, function(event)
local player = get_online_player(event)
if not player or player.afk_time > afk_required then return end
increment(player, "DistanceTravelled")
end)
end
if config.MachinesRemoved or config.TreesDestroyed or config.OreMined then
--- @param event EventData.on_marked_for_deconstruction | EventData.on_player_mined_entity
local function on_removed(event)
local player = get_online_player(event)
if not player then return end
local entity = event.entity
if not entity.valid then return end
if entity.type == "resource" then
if config.OreMined then increment(player, "OreMined") end
elseif entity.type == "tree" then
if config.TreesDestroyed then increment(player, "TreesDestroyed") end
elseif entity.force == player.force then
if config.MachinesRemoved then increment(player, "MachinesRemoved") end
end
end
add(defines.events.on_marked_for_deconstruction, on_removed)
add(defines.events.on_player_mined_entity, on_removed)
end
--- Vehicles which credit their driver, or failing that their passenger, with what they hit
local crewed_vehicles = { car = true, ["spider-vehicle"] = true, locomotive = true }
--- Get the connected player behind the cause of damage or a death, nil for turrets, trains without a crew and the like
--- @param cause LuaEntity?
--- @return LuaPlayer?
local function get_cause_player(cause)
if not cause or not cause.valid then return nil end
local occupant = cause --- @type LuaEntity | LuaPlayer
if crewed_vehicles[cause.type] then
local crew = cause.get_driver() or cause.get_passenger()
if not crew then return nil end
occupant = crew
end
local player --- @type LuaPlayer?
if occupant.object_name == "LuaPlayer" then
player = occupant --[[@as LuaPlayer]]
elseif occupant.type == "character" then
player = occupant.player
end
if not player or not player.valid or not player.connected then return nil end
return player
end
--- Check that damage or a death counts against an entity, it must be hostile to the player
--- @param entity LuaEntity
--- @param player LuaPlayer
--- @return boolean
local function is_hostile(entity, player)
return entity.valid and entity.force ~= player.force and entity.force.name ~= "neutral"
end
if config.DamageDealt then
--- @param event EventData.on_entity_damaged
add(defines.events.on_entity_damaged, function(event)
local player = get_cause_player(event.cause)
if not player or not is_hostile(event.entity, player) then return end
increment(player, "DamageDealt", floor(event.final_damage_amount))
end)
end
if config.Kills then
--- @param event EventData.on_entity_died
add(defines.events.on_entity_died, function(event)
local player = get_cause_player(event.cause)
if not player or not is_hostile(event.entity, player) then return end
increment(player, "Kills")
end)
end
--- Increment a statistic for every online player on a force
--- @param force LuaForce?
--- @param statistic string
local function increment_force(force, statistic)
if not force or not force.valid then return end
for _, player in pairs(force.connected_players) do
increment(player, statistic)
end
end
if config.RocketsLaunched then
--- @param event EventData.on_rocket_launched
add(defines.events.on_rocket_launched, function(event)
local silo = event.rocket_silo
if not silo or not silo.valid then return end
increment_force(silo.force --[[@as LuaForce]], "RocketsLaunched")
end)
end
if config.ResearchCompleted then
--- @param event EventData.on_research_finished
add(defines.events.on_research_finished, function(event)
local research = event.research
if event.by_script or not research or not research.valid then return end
increment_force(research.force, "ResearchCompleted")
end)
end
for statistic, event_id in pairs(config.counters) do
add(event_id, function(event)
local player = get_online_player(event)
if player then increment(player, statistic) end
end)
end
return {
events = events,
on_nth_tick = on_nth_tick,
}
+4
View File
@@ -0,0 +1,4 @@
--- @diagnostic disable: global-in-non-module
-- Access using `/sc exp_statistics.foo()`
exp_statistics = require("modules/exp_statistics/control")
+67
View File
@@ -0,0 +1,67 @@
[exp-statistics]
MapsPlayed=Maps Played
MapsPlayed-tooltip=The number of unique maps you have played on
JoinCount=Join Count
JoinCount-tooltip=The number of times you have joined our servers
Playtime=Playtime
Playtime-tooltip=The amount of time you have spent on our servers
AfkTime=AFK Time
AfkTime-tooltip=The amount of time you have been AFK on our servers
ChatMessages=Messages
ChatMessages-tooltip=The number of messages you have sent in chat
CommandsUsed=Commands
CommandsUsed-tooltip=The number of commands you have used
RocketsLaunched=Rockets Launched
RocketsLaunched-tooltip=The number of rockets launched while you were online
ResearchCompleted=Research Completed
ResearchCompleted-tooltip=The number of research projects completed while you were online
MachinesBuilt=Machines Built
MachinesBuilt-tooltip=The number of machines you have built
MachinesRemoved=Machines Removed
MachinesRemoved-tooltip=The number of machines you have removed
TilesBuilt=Tiles Placed
TilesBuilt-tooltip=The number of tiles you have placed
TilesRemoved=Tiles Removed
TilesRemoved-tooltip=The number of tiles you have removed
TreesDestroyed=Trees Destroyed
TreesDestroyed-tooltip=The number of trees you have destroyed
OreMined=Ore Mined
OreMined-tooltip=The amount of ore you have mined
ItemsCrafted=Items Crafted
ItemsCrafted-tooltip=The number of items you have crafted
ItemsPickedUp=Items Picked Up
ItemsPickedUp-tooltip=The number of items you have picked up
Kills=Kills
Kills-tooltip=The number of biters and biter bases you have squished
Deaths=Deaths
Deaths-tooltip=The number of times you have died
DamageDealt=Damage Dealt
DamageDealt-tooltip=The amount of damage you have dealt to other forces
DistanceTravelled=Distance Travelled
DistanceTravelled-tooltip=The total distance in tiles that you have travelled
CapsulesUsed=Capsules Used
CapsulesUsed-tooltip=The number of capsules you have used
EntityRepaired=Machines Repaired
EntityRepaired-tooltip=The number of machines which you have repaired
DeconstructionPlannerUsed=Decon Planner Used
DeconstructionPlannerUsed-tooltip=The number of times you have used the deconstruction planner
MapTagsMade=Map Tags Created
MapTagsMade-tooltip=The number of map tags you have created
DamageDeathRatio=Damage Death Ratio
DamageDeathRatio-tooltip=Damage over Death
KillDeathRatio=Kill Death Ratio
KillDeathRatio-tooltip=Kill over Death
SessionTime=Session Time
SessionTime-tooltip=Session Time
BuildRatio=Build Ratio
BuildRatio-tooltip=Build over Remove
RocketPerHour=Rocket Per Hour
RocketPerHour-tooltip=Rocket Launched Over Play Time in Hour
TreeKillPerMinute=Tree Kill Per Minute
TreeKillPerMinute-tooltip=Tree Destroyed Per Minute
NetPlayTime=Net Play Time
NetPlayTime-tooltip=Net Play Time
AFKTimeRatio=AFK Time Ratio
AFKTimeRatio-tooltip=AFK Time over Play Time
Locale=Locale
Locale-tooltip=The language of player interface
+67
View File
@@ -0,0 +1,67 @@
[exp-statistics]
MapsPlayed=地圖遊玩次數
MapsPlayed-tooltip=你在本服務器遊玩過的地圖數
JoinCount=登入次數
JoinCount-tooltip=你在本服務器遊玩的次數
Playtime=遊玩時間
Playtime-tooltip=你在本服務器遊玩的時間
AfkTime=掛機時間
AfkTime-tooltip=你在本服務器掛機的時間
ChatMessages=傳送信息次數
ChatMessages-tooltip=你在本服務器發送信息的次數
CommandsUsed=使用指令次數
CommandsUsed-tooltip=你在本服務器使用指令的次數
RocketsLaunched=火箭發射次數
RocketsLaunched-tooltip=你在本服務器在線時所發射過火箭的次數
ResearchCompleted=研究次數
ResearchCompleted-tooltip=你在本服務器在線時完成研究的次數
MachinesBuilt=機器建造次數
MachinesBuilt-tooltip=你在本服務器建造過機器的次數
MachinesRemoved=機器拆除次數
MachinesRemoved-tooltip=你在本服務器拆除過機器的次數
TilesBuilt=地磚建造次數
TilesBuilt-tooltip=你在本服務器建造過地磚的次數
TilesRemoved=地磚拆除次數
TilesRemoved-tooltip=你在本服務器拆除過地磚的次數
TreesDestroyed=樹木拆除次數
TreesDestroyed-tooltip=你在本服務器拆除過樹木的次數
OreMined=挖礦次數
OreMined-tooltip=你在本服務器挖掘礦的次數
ItemsCrafted=物品合成數
ItemsCrafted-tooltip=你在本服務器合成過物品的次數
ItemsPickedUp=物品拾起數
ItemsPickedUp-tooltip=你在本服務器起過物品的次數
Kills=撃殺數
Kills-tooltip=你在本服務器殺過的敵人數量
Deaths=死亡次數
Deaths-tooltip=你在本服務器死過的數量
DamageDealt=傷害量
DamageDealt-tooltip=你在本伺服器對敵人所造成的傷害量
DistanceTravelled=移動距離
DistanceTravelled-tooltip=你在本服務器的總移動距離
CapsulesUsed=膠囊使用次數
CapsulesUsed-tooltip=你在本服務器使用過膠囊的次數
EntityRepaired=機器維修次數
EntityRepaired-tooltip=你在本服務器維修過機器的次數
DeconstructionPlannerUsed=拆除規劃器使用次數
DeconstructionPlannerUsed-tooltip=你在本服務器使用過拆除規劃器的次數
MapTagsMade=地圖標籤數量
MapTagsMade-tooltip=你在本服務器放過的地圖標籤數量
DamageDeathRatio=傷害死亡比
DamageDeathRatio-tooltip=傷害除以死亡
KillDeathRatio=撃殺死亡比
KillDeathRatio-tooltip=撃殺除以死亡
SessionTime=平均遊玩時間
SessionTime-tooltip=平均遊玩時間
BuildRatio=建築比
BuildRatio-tooltip=建築次數除以拆除次數
RocketPerHour=每小時火箭發射次數
RocketPerHour-tooltip=火箭發射次數除以遊玩時間
TreeKillPerMinute=每分鐘樹木拆除數
TreeKillPerMinute-tooltip=樹木拆除數除以遊玩時間
NetPlayTime=淨遊玩時間
NetPlayTime-tooltip=遊玩時間減掛機時間
AFKTimeRatio=掛機時間比
AFKTimeRatio-tooltip=掛機時間除以遊玩時間
Locale=語言
Locale-tooltip=用戶介面語言
+67
View File
@@ -0,0 +1,67 @@
[exp-statistics]
MapsPlayed=地圖遊玩次數
MapsPlayed-tooltip=你在本服務器遊玩過的地圖數
JoinCount=登入次數
JoinCount-tooltip=你在本服務器遊玩的次數
Playtime=遊玩時間
Playtime-tooltip=你在本服務器遊玩的時間
AfkTime=掛機時間
AfkTime-tooltip=你在本服務器掛機的時間
ChatMessages=傳送信息次數
ChatMessages-tooltip=你在本服務器發送信息的次數
CommandsUsed=使用指令次數
CommandsUsed-tooltip=你在本服務器使用指令的次數
RocketsLaunched=火箭發射次數
RocketsLaunched-tooltip=你在本服務器在線時所發射過火箭的次數
ResearchCompleted=研究次數
ResearchCompleted-tooltip=你在本服務器在線時完成研究的次數
MachinesBuilt=機器建造次數
MachinesBuilt-tooltip=你在本服務器建造過機器的次數
MachinesRemoved=機器拆除次數
MachinesRemoved-tooltip=你在本服務器拆除過機器的次數
TilesBuilt=地磚建造次數
TilesBuilt-tooltip=你在本服務器建造過地磚的次數
TilesRemoved=地磚拆除次數
TilesRemoved-tooltip=你在本服務器拆除過地磚的次數
TreesDestroyed=樹木拆除次數
TreesDestroyed-tooltip=你在本服務器拆除過樹木的次數
OreMined=挖礦次數
OreMined-tooltip=你在本服務器挖掘礦的次數
ItemsCrafted=物品合成數
ItemsCrafted-tooltip=你在本服務器合成過物品的次數
ItemsPickedUp=物品拾起數
ItemsPickedUp-tooltip=你在本服務器起過物品的次數
Kills=撃殺數
Kills-tooltip=你在本服務器殺過的敵人數量
Deaths=死亡次數
Deaths-tooltip=你在本服務器死過的數量
DamageDealt=傷害量
DamageDealt-tooltip=你在本伺服器對敵人所造成的傷害量
DistanceTravelled=移動距離
DistanceTravelled-tooltip=你在本服務器的總移動距離
CapsulesUsed=膠囊使用次數
CapsulesUsed-tooltip=你在本服務器使用過膠囊的次數
EntityRepaired=機器維修次數
EntityRepaired-tooltip=你在本服務器維修過機器的次數
DeconstructionPlannerUsed=拆除規劃器使用次數
DeconstructionPlannerUsed-tooltip=你在本服務器使用過拆除規劃器的次數
MapTagsMade=地圖標籤數量
MapTagsMade-tooltip=你在本服務器放過的地圖標籤數量
DamageDeathRatio=傷害死亡比
DamageDeathRatio-tooltip=傷害除以死亡
KillDeathRatio=撃殺死亡比
KillDeathRatio-tooltip=撃殺除以死亡
SessionTime=平均遊玩時間
SessionTime-tooltip=平均遊玩時間
BuildRatio=建築比
BuildRatio-tooltip=建築次數除以拆除次數
RocketPerHour=每小時火箭發射次數
RocketPerHour-tooltip=火箭發射次數除以遊玩時間
TreeKillPerMinute=每分鐘樹木拆除數
TreeKillPerMinute-tooltip=樹木拆除數除以遊玩時間
NetPlayTime=淨遊玩時間
NetPlayTime-tooltip=遊玩時間減掛機時間
AFKTimeRatio=掛機時間比
AFKTimeRatio-tooltip=掛機時間除以遊玩時間
Locale=語言
Locale-tooltip=用戶介面語言
+13
View File
@@ -0,0 +1,13 @@
{
"name": "exp_statistics",
"load": [
"events.lua"
],
"require": [
"globals.lua"
],
"dependencies": {
"clusterio": "*",
"exp_util": "*"
}
}
+2
View File
@@ -0,0 +1,2 @@
-- Access the exports from other modules using require("modules/exp_statistics")
return require("modules/exp_statistics/control")