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

+145
View File
@@ -0,0 +1,145 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Controller } from "@clusterio/controller";
import entrypoint from "../dist/node/controller.js";
import * as messages from "../dist/node/messages.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
// The controller validates message classes against the link registry
for (const Message of pluginDeclaration.messages) {
lib.Link.register(Message);
}
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
// Silence the singleton logger to avoid polluting the test output
lib.logger.silent = true;
t.after(() => {
lib.logger.silent = false;
});
const fromInstance = lib.Address.fromShorthand({ instanceId: 1 });
/** Run the plugin on a real controller, which is side effect free while not started, returns its handlers. */
async function startPlugin(t2, databaseDirectory = t2.testdir()) {
const controllerConfig = new lib.ControllerConfig("controller", {
"controller.database_directory": databaseDirectory,
});
const controller = new Controller(logger, [], controllerConfig);
const state = { broadcasts: [] };
controller.subscriptions.broadcast = event => {
state.broadcasts.push(event);
};
const handlers = new Map();
const handle = controller.handle.bind(controller);
controller.handle = (Class, handler) => {
handlers.set(Class, handler);
handle(Class, handler);
};
const subscriptionHandle = controller.subscriptions.handle.bind(controller.subscriptions);
controller.subscriptions.handle = (Class, handler) => {
handlers.set(Class, handler);
subscriptionHandle(Class, handler);
};
await entrypoint({ plugin: { name: "exp_statistics" }, controller, logger });
const delta = (name, stats) => new messages.StatisticsDelta(name, stats);
return {
controller,
state,
update: (...deltas) => handlers.get(messages.StatisticsUpdateEvent)(
new messages.StatisticsUpdateEvent(deltas.map(([name, stats]) => delta(name, stats))), fromInstance,
),
get: name => handlers.get(messages.StatisticsGetRequest)(new messages.StatisticsGetRequest(name), fromInstance),
list: () => handlers.get(messages.StatisticsListRequest)(new messages.StatisticsListRequest(), fromInstance),
subscription: lastRequestTimeMs => handlers.get(messages.PlayerStatisticsUpdatedEvent)({ lastRequestTimeMs }),
};
}
t.test("entrypoint attaches to save and shutdown", async t2 => {
const { controller } = await startPlugin(t2);
for (const hook of ["save", "shutdown"]) {
t2.ok([...controller.hooks[hook].attached].includes("exp_statistics"), `attached to ${hook}`);
}
});
t.test("controller plugin", t2 => {
t2.test("StatisticsUpdateEvent adds the deltas to the totals", async t3 => {
const { update, get } = await startPlugin(t3);
await update(["alice", { Kills: 2, Playtime: 5 }], ["bob", { Deaths: 1 }]);
await update(["alice", { Kills: 3, Deaths: 1 }]);
t3.strictSame((await get("alice")).stats, { Kills: 5, Playtime: 5, Deaths: 1 }, "deltas are summed per stat");
t3.strictSame((await get("bob")).stats, { Deaths: 1 });
});
t2.test("StatisticsUpdateEvent merges deltas for the same player in one update", async t3 => {
const { update, get, state } = await startPlugin(t3);
await update(["alice", { Kills: 1 }], ["alice", { Kills: 2 }]);
t3.strictSame((await get("alice")).stats, { Kills: 3 });
t3.equal(state.broadcasts.length, 1, "one broadcast");
t3.strictSame(state.broadcasts[0].updates.map(player => player.id), ["alice"], "with the player once");
});
t2.test("StatisticsUpdateEvent ignores values which are not finite or zero", async t3 => {
const { update, get } = await startPlugin(t3);
await update(["alice", { Kills: 1, Deaths: 0, Bad: Infinity, Worse: NaN }]);
t3.strictSame((await get("alice")).stats, { Kills: 1 });
});
t2.test("StatisticsGetRequest gives an empty record for an unknown player", async t3 => {
const { get, list } = await startPlugin(t3);
const record = await get("carol");
t3.equal(record.id, "carol");
t3.strictSame(record.stats, {});
t3.strictSame(await list(), [], "nothing is stored");
});
t2.test("StatisticsListRequest lists every player", async t3 => {
const { update, list } = await startPlugin(t3);
await update(["alice", { Kills: 1 }], ["bob", { Kills: 2 }]);
t3.strictSame((await list()).map(player => player.id).sort(), ["alice", "bob"]);
});
t2.test("subscribing replays only newer records", async t3 => {
const { update, subscription } = await startPlugin(t3);
await update(["alice", { Kills: 1 }]);
const all = await subscription(0);
t3.strictSame(all.updates.map(player => player.id), ["alice"]);
t3.equal(await subscription(all.updates[0].updatedAtMs), null, "nothing newer");
});
t2.test("totals are saved and loaded", async t3 => {
const directory = t3.testdir();
const first = await startPlugin(t3, directory);
await first.update(["alice", { Kills: 4 }]);
await first.controller.hooks.save.invoke();
const second = await startPlugin(t3, directory);
t3.strictSame((await second.get("alice")).stats, { Kills: 4 });
});
t2.end();
});
t.test("permissions", async t2 => {
const names = pluginDeclaration.permissions.map(permission => permission.name);
t2.strictSame(names, ["exp_statistics.view"]);
for (const Message of [
messages.StatisticsGetRequest, messages.StatisticsListRequest, messages.PlayerStatisticsUpdatedEvent,
]) {
t2.equal(Message.permission, "exp_statistics.view", `${Message.name} needs view`);
}
t2.equal(messages.StatisticsUpdateEvent.permission, null, "updates only come from instances");
t2.strictSame(messages.StatisticsUpdateEvent.src, "instance");
});
t.test("messages round trip through json", async t2 => {
const record = new messages.PlayerStatistics("alice", { Kills: 1 }, 10);
t2.strictSame(messages.PlayerStatistics.fromJSON(JSON.parse(JSON.stringify(record))), record);
const event = new messages.StatisticsUpdateEvent([new messages.StatisticsDelta("bob", { Deaths: 2 })]);
t2.strictSame(messages.StatisticsUpdateEvent.fromJSON(JSON.parse(JSON.stringify(event))), event);
});
+132
View File
@@ -0,0 +1,132 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { Instance } from "@clusterio/host";
import entrypoint from "../dist/node/instance.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import * as messages from "../dist/node/messages.js";
// The instance validates message classes against the link registry
for (const Message of pluginDeclaration.messages) {
lib.Link.register(Message);
}
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
class TestConnector extends lib.BaseConnector {
constructor() {
super(lib.Address.fromShorthand({ instanceId: 1 }), lib.Address.fromShorthand({ hostId: 1 }));
this.valid = true;
this.connected = true;
this.hasSession = true;
}
send() {}
}
/** Run the plugin on a real instance with spies on what leaves it, returns the IPC handlers it registered. */
async function startPlugin(t2, { status = "running", stats = { Kills: 3 } } = {}) {
const instanceConfig = new lib.InstanceConfig("host");
instanceConfig.set("instance.id", 1);
instanceConfig.set("instance.name", "test");
const instance = new Instance(
{ assignGamePort: () => 1 }, new TestConnector(), t2.testdir(), "factorioDir", instanceConfig
);
const state = { sent: [], rcons: [], warnings: [] };
const ipc = new Map();
instance.server = {
handle: (name, handler) => ipc.set(name, handler),
};
instance.sendRcon = async command => {
state.rcons.push(command);
return "";
};
instance.sendTo = async (dst, message) => {
state.sent.push(message);
if (message instanceof messages.StatisticsGetRequest) {
return new messages.PlayerStatistics(message.name, stats);
}
return undefined;
};
instance.notifyStatus(status);
state.sent.length = 0;
const pluginLogger = { ...logger, warn: message => state.warnings.push(message) };
await entrypoint({ plugin: { name: "exp_statistics" }, instance, host: {}, logger: pluginLogger });
return { instance, state, updateIPC: event => ipc.get("exp_statistics:update")(event) };
}
/** The payload of a recorded receive_totals command. */
function decodeTotals(command) {
const match = command.match(/^\/sc exp_statistics\.receive_totals\(helpers\.json_to_table\[(=+)\[(.*)\]\1\]\)$/s);
return JSON.parse(match[2]);
}
t.test("instance plugin", t2 => {
t2.test("exp_statistics:update is forwarded to the controller", async t3 => {
const { state, updateIPC } = await startPlugin(t3);
await updateIPC({ players: [{ name: "alice", stats: { Kills: 1 } }, { name: "bob", stats: { Deaths: 2 } }] });
t3.equal(state.sent.length, 1, "one event");
const event = state.sent[0];
t3.ok(event instanceof messages.StatisticsUpdateEvent);
t3.strictSame(event.deltas.map(delta => [delta.name, delta.stats]), [
["alice", { Kills: 1 }],
["bob", { Deaths: 2 }],
]);
});
t2.test("a player joining is sent their totals", async t3 => {
const { instance, state } = await startPlugin(t3);
await instance.hooks.playerEvent.invoke({ type: "join", name: "alice" });
const request = state.sent[0];
t3.ok(request instanceof messages.StatisticsGetRequest);
t3.equal(request.name, "alice");
t3.equal(state.rcons.length, 1);
t3.strictSame(decodeTotals(state.rcons[0]), { name: "alice", stats: { Kills: 3 } });
});
t2.test("the long bracket is not in the json", async t3 => {
const { instance, state } = await startPlugin(t3, { stats: { "]=]": 1 } });
await instance.hooks.playerEvent.invoke({ type: "join", name: "alice" });
t3.ok(state.rcons[0].includes("[==["), "a longer bracket is used");
t3.strictSame(decodeTotals(state.rcons[0]).stats, { "]=]": 1 });
});
t2.test("leaving and other player events send nothing", async t3 => {
const { instance, state } = await startPlugin(t3);
await instance.hooks.playerEvent.invoke({ type: "leave", name: "alice", reason: "quit" });
await instance.hooks.playerEvent.invoke({ type: "promote", name: "alice" });
t3.strictSame(state.sent, []);
t3.strictSame(state.rcons, []);
});
t2.test("totals are not sent once the instance is no longer running", async t3 => {
const { instance, state } = await startPlugin(t3, { status: "stopping" });
await instance.hooks.playerEvent.invoke({ type: "join", name: "alice" });
t3.strictSame(state.rcons, []);
});
t2.test("a failed request is logged", async t3 => {
const { instance, state } = await startPlugin(t3);
instance.sendTo = async () => { throw new Error("controller gone"); };
await instance.hooks.playerEvent.invoke({ type: "join", name: "alice" });
t3.strictSame(state.rcons, []);
t3.match(state.warnings[0], /alice: controller gone/);
});
t2.test("start drops what was unsent and stop sends the rest", async t3 => {
const { instance, state } = await startPlugin(t3);
await instance.hooks.start.invoke();
await instance.hooks.stop.invoke();
t3.strictSame(state.rcons, [
"/sc exp_statistics.discard_unsent()",
"/sc exp_statistics.send_all()",
]);
});
t2.end();
});
+13
View File
@@ -0,0 +1,13 @@
import path from "node:path";
import t from "tap";
import { reportLuaTests } from "../../test/lua/runner.js";
const envFile = path.join(import.meta.dirname, "module", "env.lua");
// Each file runs in its own lua state, and each test in a fresh environment
t.test("lua module", t2 => {
for (const file of ["control.lua", "events.lua"]) {
t2.test(file, t3 => reportLuaTests(t3, envFile, path.join(import.meta.dirname, "module", file)));
}
t2.end();
});
+120
View File
@@ -0,0 +1,120 @@
local Suite = ... --- @type Suite<ExpStatistics.TestEnv>
Suite.test("increment() adds to the unsent statistics", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
Stats.increment(alice, "Kills")
Stats.increment(alice, "Kills", 4)
Suite.eq(Stats.get(alice, "Kills"), 5, "by one, then by the amount")
Suite.eq(Stats.get("alice", "Kills"), 5, "by player name")
Suite.eq(Stats.get(alice, "Deaths"), 0, "missing statistics are zero")
end)
Suite.test("send_all() sends every player with changes in one update", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob" }
env.add_player{ name = "carol" }
Stats.increment(alice, "Kills", 2)
Stats.increment(bob, "Deaths")
Stats.send_all()
Suite.eq(#env.sent, 1, "one update")
Suite.eq(assert(env.sent[1]).channel, "exp_statistics:update", "on the update channel")
local players = assert(env.sent[1]).data.players
table.sort(players, function(a, b) return a.name < b.name end)
Suite.eq(players, {
{ name = "alice", stats = { Kills = 2 } },
{ name = "bob", stats = { Deaths = 1 } },
}, "players without changes are left out")
end)
Suite.test("sending clears the unsent statistics but keeps the total", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
Stats.increment(alice, "Kills", 2)
Stats.send_all()
Suite.eq(Stats.get(alice, "Kills"), 2, "moved into the totals")
env.reset_log()
Stats.send_all()
Suite.empty(env.sent, "nothing is sent twice")
Stats.increment(alice, "Kills")
Stats.send_all()
Suite.eq(assert(env.sent[1]).data.players, { { name = "alice", stats = { Kills = 1 } } }, "only the new delta is sent")
Suite.eq(Stats.get(alice, "Kills"), 3, "the total includes it")
end)
Suite.test("send() sends one player", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob" }
Stats.increment(alice, "Kills")
Stats.increment(bob, "Kills")
Stats.send("alice")
Suite.eq(env.sent, { { channel = "exp_statistics:update", data = { players = { { name = "alice", stats = { Kills = 1 } } } } } }, "only that player")
env.reset_log()
Stats.send("carol")
Suite.empty(env.sent, "nothing is sent for a player without changes")
end)
Suite.test("receive_totals() adds the unsent statistics to the totals", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
Stats.increment(alice, "Kills", 2)
Stats.receive_totals{ name = "alice", stats = { Kills = 10, Deaths = 1 } }
Suite.eq(Stats.get(alice, "Kills"), 12, "received plus unsent")
Suite.eq(Stats.get(alice, "Deaths"), 1, "received only")
Stats.send_all()
Suite.eq(assert(env.sent[1]).data.players[1].stats, { Kills = 2 }, "the received totals are not sent back")
Suite.eq(Stats.get(alice, "Kills"), 12, "the total is unchanged by sending")
end)
Suite.test("receive_totals() ignores players who are not online", function(env)
local Stats = env.Statistics
env.add_player{ name = "bob", connected = false }
Stats.receive_totals{ name = "bob", stats = { Kills = 10 } }
Stats.receive_totals{ name = "nobody", stats = { Kills = 10 } }
Suite.eq(Stats.get("bob", "Kills"), 0, "offline")
Suite.eq(Stats.get("nobody", "Kills"), 0, "never joined")
end)
Suite.test("send_and_forget() sends then drops the totals", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
Stats.receive_totals{ name = "alice", stats = { Kills = 10 } }
Stats.increment(alice, "Kills")
Stats.send_and_forget("alice")
Suite.eq(assert(env.sent[1]).data.players[1].stats, { Kills = 1 }, "the unsent delta is sent")
Suite.eq(Stats.get(alice, "Kills"), 0, "nothing is kept")
end)
Suite.test("discard_unsent() drops what was not sent", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
Stats.receive_totals{ name = "alice", stats = { Kills = 10 } }
Stats.increment(alice, "Kills")
Stats.discard_unsent()
Suite.eq(Stats.get(alice, "Kills"), 10, "only the totals remain")
Stats.send_all()
Suite.empty(env.sent, "nothing to send")
end)
Suite.test("format() shows times and numbers", function(env)
local Stats = env.Statistics
Suite.eq(Stats.format("Playtime", 90), { "time-long", 90 }, "long time")
Suite.eq(Stats.format("AfkTime", 90, true), { "time-short", 90 }, "short time")
Suite.eq(Stats.format("Kills", 7), "7", "number")
Suite.eq(Stats.units.DistanceTravelled, " tiles", "distance has a unit")
end)
Suite.test("display_order lists every enabled statistic", function(env)
local order = env.Statistics.display_order
Suite.eq(#order, 24, "all enabled by default")
Suite.eq(order[1], "Playtime", "in the configured order")
end)
return Suite.run()
+101
View File
@@ -0,0 +1,101 @@
--[[-- Test environment for the statistics module
Extends the shared stubs with fresh copies of module/control.lua and
module/events.lua, stubs of the exp_util functions they use, and players with
the fields the trackers read.
Run as a chunk by test/lua/runner.js, receiving the shared folder. The suite
returned here becomes `...` in each test file.
]]
local shared_root = ... --- @type string
local source = assert(debug.getinfo(1, "S")).source:gsub("\\", "/")
local plugin_root = assert(source:match("^@(.*)/test/module/env%.lua$"))
local Framework = assert(loadfile(shared_root .. "/framework.lua"))() --- @type Framework
--- Every event the module listens to, ids start after the shared stubs
local event_names = {
"on_player_left_game", "on_player_created", "on_player_changed_position",
"on_marked_for_deconstruction", "on_player_mined_entity", "on_entity_damaged",
"on_entity_died", "on_rocket_launched", "on_research_finished",
"on_built_entity", "on_chart_tag_added", "on_console_chat", "on_console_command",
"on_picked_up_item", "on_player_built_tile", "on_player_crafted_item",
"on_player_deconstructed_area", "on_player_died", "on_player_mined_tile",
"on_player_used_capsule", "on_player_repaired_entity",
}
--- @class ExpStatistics.TestEnv : Stubs
--- @field Statistics ExpStatistics A fresh copy of the statistics module
--- @field handlers { events: table<number, fun(event: table)>, on_nth_tick: table<number, fun()> } From events.lua
--- @field force fun(name: string): table A force stub with the online players added to it
--- @field raise fun(name: string, event: table) Call the handler of an event by its name
--- @field add_player fun(params: ExpStatistics.TestPlayerParams): ExpStatistics.TestPlayer
--- @class ExpStatistics.TestPlayerParams : Stubs.PlayerParams
--- @field afk_time number? Defaults to 0
--- @field force string? Defaults to "player"
--- @class ExpStatistics.TestPlayer : Stubs.Player
--- @field afk_time number
--- @field force table
return Framework.suite(function(env)
--- @cast env ExpStatistics.TestEnv
local events = {}
for index, name in ipairs(event_names) do
events[name] = 10 + index
end
env.extend_defines{ events = events }
env.extend_requires{
["modules/exp_util"] = {
format_time_factory_locale = function(opts)
return function(value) return { "time-" .. opts.format, value } end
end,
},
["modules/exp_util/storage"] = {
register = function() end,
},
["util"] = {
format_number = function(value) return tostring(value) end,
},
}
env.extend_requires{
["modules/exp_statistics/config"] = assert(loadfile(plugin_root .. "/module/config.lua"))(),
}
env.Statistics = assert(loadfile(plugin_root .. "/module/control.lua"))() --- @type ExpStatistics
env.extend_requires{ ["modules/exp_statistics/control"] = env.Statistics }
env.handlers = assert(loadfile(plugin_root .. "/module/events.lua"))()
local forces = {}
function env.force(name)
local force = forces[name]
if not force then
force = { name = name, valid = true, connected_players = {} }
forces[name] = force
end
return force
end
local add_player = env.add_player
function env.add_player(params)
local player = add_player(params) --[[@as ExpStatistics.TestPlayer]]
local force = env.force(params.force or "player")
rawset(player, "afk_time", params.afk_time or 0)
rawset(player, "force", force)
rawset(player, "object_name", "LuaPlayer")
if player.connected then
force.connected_players[#force.connected_players + 1] = player
end
return player
end
function env.raise(name, event)
local id = (defines.events --[[@as table<string, number>]])[name]
local handler = env.handlers.events[id]
assert(handler, "no handler for " .. name)
handler(event)
end
return env
end)
+133
View File
@@ -0,0 +1,133 @@
local Suite = ... --- @type Suite<ExpStatistics.TestEnv>
Suite.test("counters go up by one for online players", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob", connected = false }
env.raise("on_console_chat", { player_index = alice.index })
env.raise("on_console_chat", { player_index = alice.index })
env.raise("on_player_died", { player_index = alice.index })
env.raise("on_console_chat", { player_index = bob.index })
env.raise("on_console_chat", {})
Suite.eq(Stats.get(alice, "ChatMessages"), 2, "chat")
Suite.eq(Stats.get(alice, "Deaths"), 1, "deaths")
Suite.eq(Stats.get(bob, "ChatMessages"), 0, "offline players are skipped")
end)
Suite.test("a player is counted once per map", function(env)
local alice = env.add_player{ name = "alice" }
env.raise("on_player_created", { player_index = alice.index })
Suite.eq(env.Statistics.get(alice, "MapsPlayed"), 1, "maps played")
end)
Suite.test("playtime and afk time go up each minute", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob", afk_time = 6 * 3600 }
local tick = env.handlers.on_nth_tick[3600]
game.tick = 3600
tick()
tick()
Suite.eq(Stats.get(alice, "Playtime"), 2, "playtime")
Suite.eq(Stats.get(alice, "AfkTime"), 0, "not afk")
Suite.eq(Stats.get(bob, "AfkTime"), 2, "afk")
end)
Suite.test("distance is not counted while afk", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob", afk_time = 6 * 3600 }
env.raise("on_player_changed_position", { player_index = alice.index })
env.raise("on_player_changed_position", { player_index = bob.index })
Suite.eq(Stats.get(alice, "DistanceTravelled"), 1, "moving")
Suite.eq(Stats.get(bob, "DistanceTravelled"), 0, "afk")
end)
Suite.test("removed entities count as ore, trees or machines", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local function entity(type, force)
return { valid = true, type = type, force = force or env.force("neutral") }
end
env.raise("on_player_mined_entity", { player_index = alice.index, entity = entity("resource") })
env.raise("on_marked_for_deconstruction", { player_index = alice.index, entity = entity("tree") })
env.raise("on_player_mined_entity", { player_index = alice.index, entity = entity("assembling-machine", alice.force) })
env.raise("on_player_mined_entity", { player_index = alice.index, entity = entity("assembling-machine", env.force("enemy")) })
env.raise("on_marked_for_deconstruction", { entity = entity("tree") })
Suite.eq(Stats.get(alice, "OreMined"), 1, "ore")
Suite.eq(Stats.get(alice, "TreesDestroyed"), 1, "trees, by players only")
Suite.eq(Stats.get(alice, "MachinesRemoved"), 1, "own force only")
end)
Suite.test("damage and kills count against hostile entities", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local character = { valid = true, type = "character", object_name = "LuaEntity", player = alice }
local enemy = { valid = true, force = env.force("enemy") }
local ally = { valid = true, force = alice.force }
env.raise("on_entity_damaged", { cause = character, entity = enemy, final_damage_amount = 12.7 })
env.raise("on_entity_damaged", { cause = character, entity = ally, final_damage_amount = 5 })
env.raise("on_entity_died", { cause = character, entity = enemy })
env.raise("on_entity_died", { entity = enemy })
Suite.eq(Stats.get(alice, "DamageDealt"), 12, "damage is floored, allies are skipped")
Suite.eq(Stats.get(alice, "Kills"), 1, "kills without a cause are skipped")
end)
Suite.test("vehicles credit their driver", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local enemy = { valid = true, force = env.force("enemy") }
local car = {
valid = true, type = "car",
get_driver = function() return alice end,
get_passenger = function() return nil end,
}
local empty_train = {
valid = true, type = "locomotive",
get_driver = function() return nil end,
get_passenger = function() return nil end,
}
env.raise("on_entity_died", { cause = car, entity = enemy })
env.raise("on_entity_died", { cause = empty_train, entity = enemy })
Suite.eq(Stats.get(alice, "Kills"), 1, "the driver, not the empty train")
end)
Suite.test("rockets and research count for every online player on the force", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob" }
local carol = env.add_player{ name = "carol", force = "other" }
env.raise("on_rocket_launched", { rocket_silo = { valid = true, force = alice.force } })
env.raise("on_research_finished", { research = { valid = true, force = alice.force } })
env.raise("on_research_finished", { by_script = true, research = { valid = true, force = alice.force } })
Suite.eq({ Stats.get(alice, "RocketsLaunched"), Stats.get(bob, "RocketsLaunched") }, { 1, 1 }, "rockets")
Suite.eq(Stats.get(alice, "ResearchCompleted"), 1, "research by script is skipped")
Suite.eq(Stats.get(carol, "RocketsLaunched"), 0, "other forces are skipped")
end)
Suite.test("leaving sends the player and forgets them", function(env)
local Stats = env.Statistics
local alice = env.add_player{ name = "alice" }
local bob = env.add_player{ name = "bob" }
Stats.increment(alice, "Kills")
Stats.increment(bob, "Kills")
env.raise("on_player_left_game", { player_index = alice.index })
Suite.eq(assert(env.sent[1]).data.players, { { name = "alice", stats = { Kills = 1 } } }, "only the player leaving")
Suite.eq(Stats.get(alice, "Kills"), 0, "forgotten")
Suite.eq(Stats.get(bob, "Kills"), 1, "others are kept")
end)
Suite.test("everyone is sent every 5 minutes", function(env)
local alice = env.add_player{ name = "alice" }
env.Statistics.increment(alice, "Kills")
env.handlers.on_nth_tick[5 * 3600]()
Suite.eq(#env.sent, 1, "one update")
end)
return Suite.run()