Skip to content

Add configurable leaderboard income columns - #4452

Closed
jsshap wants to merge 1 commit into
openfrontio:mainfrom
jsshap:feature/4074-leaderboard-income-columns
Closed

jsshap wants to merge 1 commit into
openfrontio:mainfrom
jsshap:feature/4074-leaderboard-income-columns

Conversation

@jsshap

@jsshap jsshap commented Jun 29, 2026 •

Copy link
Copy Markdown

Before opening a PR: discuss new features on Discord first, and file bugs or small improvements as issues. You must be assigned to an approved issue — unsolicited PRs will be auto-closed.

Add approved & assigned issue number here:

Resolves #4074

Description:

Adds gold/min and configurable scoreboard columns. Adds optional cities column.

Leaderboard

Leaderboard column chooser

Testing: npm test

Please complete the following:

  • I have added screenshots for all UI updates
  • I process any text displayed to the user through translateText() and I've added it to the en.json file
  • I have added relevant tests to the test directory

Please put your Discord username so you can be contacted if a bug or regression is found:

jsshap

@jsshap
jsshap requested a review from a team as a code owner June 29, 2026 23:56
@CLAassistant

CLAassistant commented Jun 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Adds a gold-per-minute metric to the game. PlayerImpl tracks gold income using tick buckets and exposes goldPerMinute(). This value flows through PlayerUpdate, PlayerState, diff/apply utilities, and PlayerView. The leaderboard HUD is refactored to support configurable visible columns (stored via UserSettings), and a column-settings panel lets players toggle columns on or off.

Changes

Gold-per-minute leaderboard column

Layer / File(s) Summary
Data model: PlayerUpdate, PlayerState, column types
src/core/game/GameUpdates.ts, src/client/render/types/Renderer.ts, src/core/game/UserSettings.ts
Adds optional goldPerMinute to PlayerUpdate, adds it to PlayerState, and defines LeaderboardColumnKey union type plus allowlist and defaults in UserSettings.
Gold-per-minute bucket computation
src/core/game/PlayerImpl.ts
Introduces tick-bucket constants and per-bucket state; addGold() records income into the current bucket; goldPerMinute() sums recent buckets with lazy rollover; toFullUpdate() emits the computed value.
Diff and apply pipeline
src/core/game/GameUpdateUtils.ts, src/client/view/PlayerView.ts
diffPlayerUpdate detects goldPerMinute changes; applyStateUpdate merges the field; stateFromUpdate maps it into PlayerState; PlayerView.goldPerMinute() exposes it publicly.
UserSettings leaderboard column persistence
src/core/game/UserSettings.ts
Adds leaderboardColumns(), setLeaderboardColumns(), and toggleLeaderboardColumn() backed by localStorage JSON, with validation and default fallback.
Dynamic leaderboard columns and config UI
src/client/hud/layers/Leaderboard.ts, resources/lang/en.json
Refactors the leaderboard to drive header cells, row cells, sort logic, and grid template from COLUMN_DEFINITIONS; adds renderColumnSettings() panel with checkboxes; adds columns, configure_columns, and gold_per_min translation keys.
Tests
tests/GameUpdateUtils.test.ts, tests/PlayerUpdateDiff.test.ts, tests/client/view/GameView.test.ts, tests/util/viewStubs.ts, tests/client/render/frame/derive/*
Extends diff/apply tests, adds bucket-behavior integration tests for goldPerMinute, adds a GameView packed-channel test, and updates fixture defaults.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • openfrontio/OpenFrontIO#3967: Directly extends the same diffPlayerUpdate/applyStateUpdate machinery in GameUpdateUtils.ts that this PR adds goldPerMinute support to.
  • openfrontio/OpenFrontIO#4244: Restructured PlayerUpdate packed-channel diff/apply plumbing that this PR extends with the new field.
  • openfrontio/OpenFrontIO#4379: Modifies the same leaderboard sorting and maxtroops code paths that this PR generalizes into column-driven sort values.

Suggested reviewers

  • evanpelle

Poem

🪙 Gold flows in, bucket by bucket it grows,
Ticked and summed as each minute goes.
The board now bends to columns you choose,
Toggle them on — or toggle to lose!
Gold per minute, tracked and displayed,
Your economy scored, your empire weighed. 📊

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Configurable column settings and the optional cities column go beyond #4074's gold/min requirement. Move the column-chooser and cities changes to a separate PR, and keep this one focused on gold/min income.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main leaderboard income-column work.
Description check ✅ Passed The description matches the gold/min and configurable leaderboard column changes.
Linked Issues check ✅ Passed Implements #4074 by adding server-side gold/min tracking, client updates, and scoreboard display.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the auto-closed-needs-issue PR closed by gate — see comment for next steps label Jun 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hi @jsshap, thanks for the contribution.

This PR was automatically closed because it doesn't fit our contribution workflow:

  • You aren't currently assigned to an issue labelled approved, and
  • The change is larger than 50 lines (our cap for unsolicited contributions).

To contribute to OpenFront:

  1. For bugs or small quality-of-life improvements: open an issue. A maintainer will label it approved if it's something we'll work on.
  2. For feature ideas: discuss in the dev Discord first. We don't accept unsolicited feature PRs — even if they're good ideas, every merged feature is a permanent maintenance burden.
  3. Once an issue is labelled approved, comment asking to be assigned. After you're assigned, you can open a PR referencing that issue.

If you believe this was closed in error, please reach out on our Discord or comment below.

See CONTRIBUTING.md for the full contribution process.

— Automated PR gate. Source.

@github-actions github-actions Bot closed this Jun 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/core/game/PlayerImpl.ts`:
- Around line 93-95: The gold income stat in PlayerImpl is still using a
60-second raw total, not the requested 120-second moving average shown as
gold/min. Update the income sampling logic tied to GOLD_INCOME_BUCKET_TICKS,
GOLD_INCOME_BUCKET_COUNT, and GOLD_INCOME_SAMPLE_TICKS so the window spans 120
seconds, then convert the accumulated window total back to a per-minute rate
before exposing it. Make the change in the PlayerImpl gold income calculation
path so the reported value is normalized gold/min instead of the unscaled window
sum.
- Around line 1128-1130: The gold income tracking in PlayerImpl.addGold is
currently counting donated gold as economy income because donateGold() credits
the recipient through addGold(removed). Update the Player interface and
PlayerImpl.addGold signature to accept a flag or equivalent so donation
transfers can skip recordGoldIncome, and make donateGold pass false for the
recipient credit while keeping normal gold gains recorded as income.

In `@src/core/game/UserSettings.ts`:
- Around line 153-193: The leaderboard column settings logic in
UserSettings.leaderboardColumns, setLeaderboardColumns, and
toggleLeaderboardColumn needs test coverage for the missing edge cases. Add
tests that verify invalid JSON falls back to DEFAULT_LEADERBOARD_COLUMNS,
unknown keys are filtered out, an empty or fully invalid selection also falls
back to defaults, and toggleLeaderboardColumn preserves the last remaining
column instead of removing it when only one is selected.

In `@tests/PlayerUpdateDiff.test.ts`:
- Around line 133-166: The goldPerMinute assertion in PlayerUpdateDiff.test is
encoding the wrong contract for PlayerUpdate gold tracking. Update the test
around income.addGold and the goldPerMinute expectation so it validates a
120-second moving average emitted on the 10-second update cadence, not an
immediate 60-second burst/expiry. Adjust the expectations in the PlayerUpdate
flow for income_id to match the intended moving-average behavior and remove the
60-second zeroing assumption.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 485ed1ea-8020-4e3b-8399-e8700d45c802

📥 Commits

Reviewing files that changed from the base of the PR and between f4b47ce and 9cfba90.

📒 Files selected for processing (14)
  • resources/lang/en.json
  • src/client/hud/layers/Leaderboard.ts
  • src/client/render/types/Renderer.ts
  • src/client/view/PlayerView.ts
  • src/core/game/GameUpdateUtils.ts
  • src/core/game/GameUpdates.ts
  • src/core/game/PlayerImpl.ts
  • src/core/game/UserSettings.ts
  • tests/GameUpdateUtils.test.ts
  • tests/PlayerUpdateDiff.test.ts
  • tests/client/render/frame/derive/nuke-telegraphs.test.ts
  • tests/client/render/frame/derive/player-status.test.ts
  • tests/client/view/GameView.test.ts
  • tests/util/viewStubs.ts

Comment on lines +93 to +95
const GOLD_INCOME_BUCKET_TICKS = 10;
const GOLD_INCOME_BUCKET_COUNT = 60;
const GOLD_INCOME_SAMPLE_TICKS = 100;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the requested 120-second average window.

The current setup sums 60 buckets of 10 ticks, so the stat is based on about 60 seconds and reports the raw window total. Issue #4074 asks for a 120-second moving average expressed as gold/min, so this should use a 120-second window and normalize back to one minute.

🐛 Possible fix
 const GOLD_INCOME_BUCKET_TICKS = 10;
-const GOLD_INCOME_BUCKET_COUNT = 60;
+const GOLD_INCOME_BUCKET_COUNT = 120;
 const GOLD_INCOME_SAMPLE_TICKS = 100;
+const GOLD_INCOME_WINDOW_MINUTES = 2;
-    this._goldPerMinute = Number(total);
+    this._goldPerMinute = Number(
+      total / BigInt(GOLD_INCOME_WINDOW_MINUTES),
+    );

Also applies to: 1153-1169

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/game/PlayerImpl.ts` around lines 93 - 95, The gold income stat in
PlayerImpl is still using a 60-second raw total, not the requested 120-second
moving average shown as gold/min. Update the income sampling logic tied to
GOLD_INCOME_BUCKET_TICKS, GOLD_INCOME_BUCKET_COUNT, and GOLD_INCOME_SAMPLE_TICKS
so the window spans 120 seconds, then convert the accumulated window total back
to a per-minute rate before exposing it. Make the change in the PlayerImpl gold
income calculation path so the reported value is normalized gold/min instead of
the unscaled window sum.

Comment on lines 1128 to +1130
addGold(toAdd: Gold, tile?: TileRef): void {
this._gold += toAdd;
this.recordGoldIncome(toAdd);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not count transferred donations as income.

addGold() now records every positive credit, but donateGold() also credits the recipient through recipient.addGold(removed). That makes donated gold appear as newly earned economy income, so players can inflate the leaderboard GPM by transferring gold.

🐛 Possible direction
-  addGold(toAdd: Gold, tile?: TileRef): void {
+  addGold(toAdd: Gold, tile?: TileRef, countAsIncome = true): void {
     this._gold += toAdd;
-    this.recordGoldIncome(toAdd);
+    if (countAsIncome) this.recordGoldIncome(toAdd);

Then pass false from the donation path and update the Player interface accordingly.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/game/PlayerImpl.ts` around lines 1128 - 1130, The gold income
tracking in PlayerImpl.addGold is currently counting donated gold as economy
income because donateGold() credits the recipient through addGold(removed).
Update the Player interface and PlayerImpl.addGold signature to accept a flag or
equivalent so donation transfers can skip recordGoldIncome, and make donateGold
pass false for the recipient credit while keeping normal gold gains recorded as
income.

Comment on lines +153 to +193
leaderboardColumns(): LeaderboardColumnKey[] {
const raw = this.getString(LEADERBOARD_COLUMNS_KEY, "");
if (!raw) return DEFAULT_LEADERBOARD_COLUMNS.slice();
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
const columns = LEADERBOARD_COLUMN_KEYS.filter((key) =>
parsed.includes(key),
);
if (columns.length > 0) return columns;
}
} catch {
// Fall back to defaults below.
}
return DEFAULT_LEADERBOARD_COLUMNS.slice();
}

setLeaderboardColumns(columns: readonly LeaderboardColumnKey[]): void {
const normalized = LEADERBOARD_COLUMN_KEYS.filter((key) =>
columns.includes(key),
);
this.setString(
LEADERBOARD_COLUMNS_KEY,
JSON.stringify(
normalized.length > 0 ? normalized : DEFAULT_LEADERBOARD_COLUMNS,
),
);
}

toggleLeaderboardColumn(key: LeaderboardColumnKey): LeaderboardColumnKey[] {
if (!isLeaderboardColumnKey(key)) return this.leaderboardColumns();
const columns = this.leaderboardColumns();
const next = columns.includes(key)
? columns.length === 1
? columns
: columns.filter((column) => column !== key)
: [...columns, key];
this.setLeaderboardColumns(next);
return this.leaderboardColumns();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n --glob 'tests/**/*.test.ts' 'leaderboardColumns|setLeaderboardColumns|toggleLeaderboardColumn|LEADERBOARD_COLUMNS_KEY'

Repository: openfrontio/OpenFrontIO

Length of output: 161


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n-- tracked files matching UserSettings or tests --\n'
git ls-files 'src/core/**' 'tests/**' | sed -n '1,200p'

printf '\n-- locate UserSettings.ts and related test files --\n'
fd -i 'UserSettings.ts|*.test.ts|*.spec.ts' src tests

printf '\n-- outline src/core/game/UserSettings.ts if present --\n'
if [ -f src/core/game/UserSettings.ts ]; then
  ast-grep outline src/core/game/UserSettings.ts --view expanded
fi

printf '\n-- search for leaderboard settings identifiers across repo --\n'
rg -n 'leaderboardColumns|setLeaderboardColumns|toggleLeaderboardColumn|LEADERBOARD_COLUMNS_KEY' src tests

Repository: openfrontio/OpenFrontIO

Length of output: 7660


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n-- UserSettings outline --\n'
ast-grep outline src/core/game/UserSettings.ts --view expanded

printf '\n-- leaderboard-related tests and usage --\n'
rg -n 'leaderboardColumns|setLeaderboardColumns|toggleLeaderboardColumn|LEADERBOARD_COLUMNS_KEY|LeaderboardColumnKey' src tests

printf '\n-- inspect the client leaderboard modal test if it exists --\n'
if [ -f tests/client/LeaderboardModal.test.ts ]; then
  cat -n tests/client/LeaderboardModal.test.ts | sed -n '1,240p'
fi

printf '\n-- inspect UserSettings.ts around the target methods --\n'
sed -n '1,260p' src/core/game/UserSettings.ts

Repository: openfrontio/OpenFrontIO

Length of output: 23129


Add tests for leaderboard column settings. src/core/game/UserSettings.ts:153-193 should cover invalid JSON, unknown keys, empty selections, and the last-column toggle path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/game/UserSettings.ts` around lines 153 - 193, The leaderboard column
settings logic in UserSettings.leaderboardColumns, setLeaderboardColumns, and
toggleLeaderboardColumn needs test coverage for the missing edge cases. Add
tests that verify invalid JSON falls back to DEFAULT_LEADERBOARD_COLUMNS,
unknown keys are filtered out, an empty or fully invalid selection also falls
back to defaults, and toggleLeaderboardColumn preserves the last remaining
column instead of removing it when only one is selected.

Source: Coding guidelines

Comment on lines +133 to +166
test("goldPerMinute is positive gold credited during the last 60 seconds", () => {
const info = new PlayerInfo(
"income",
PlayerType.Human,
"income_client",
"income_id",
);
game.addPlayer(info);
const income = game.player("income_id");
income.toUpdate();

income.addGold(600n);
let diff: PlayerUpdate | undefined;
for (let i = 0; i < 100; i++) {
const updates = game.executeNextTick();
diff = (updates[GameUpdateType.Player] as PlayerUpdate[]).find(
(u) => u.id === "income_id" && u.goldPerMinute !== undefined,
);
if (diff !== undefined) break;
}

expect(diff?.goldPerMinute).toBe(600);

let expired: PlayerUpdate | undefined;
for (let i = 0; i < 600; i++) {
const updates = game.executeNextTick();
expired = (updates[GameUpdateType.Player] as PlayerUpdate[]).find(
(u) => u.id === "income_id" && u.goldPerMinute !== undefined,
);
if (expired?.goldPerMinute === 0) break;
}

expect(expired?.goldPerMinute).toBe(0);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

This test locks in the wrong gold-per-minute contract.

Line 154 expects a single addGold(600n) event to produce 600, and the test name/expiry path encode a 60-second window. But issue #4074 says this stat should be a 120-second moving average emitted every 10 seconds. With that contract, this test should not bless immediate full-rate 600 behavior or a 60-second expiry.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/PlayerUpdateDiff.test.ts` around lines 133 - 166, The goldPerMinute
assertion in PlayerUpdateDiff.test is encoding the wrong contract for
PlayerUpdate gold tracking. Update the test around income.addGold and the
goldPerMinute expectation so it validates a 120-second moving average emitted on
the 10-second update cadence, not an immediate 60-second burst/expiry. Adjust
the expectations in the PlayerUpdate flow for income_id to match the intended
moving-average behavior and remove the 60-second zeroing assumption.

@jsshap

jsshap commented Jun 30, 2026

Copy link
Copy Markdown
Author

Addressed review items:\n- donated gold no longer counts as recipient income\n- added leaderboard column settings tests\n\nKeeping the rolling window at 60s per current requirement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-closed-needs-issue PR closed by gate — see comment for next steps

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add income (as gold per minute) to the scoreboard

2 participants