Add statistics queries for the Modern game statistics menu

ModernSession::read_statistics answers JSON requests evaluated from the
almanac: the competitions with results, the winners of every
competition by season, and player statistics per competition and season
or all-time (goals, assists, yellow, second yellow and red cards,
appearances). Replays of postponed league matches are now recorded as
matches of their league and original matchday. Engine texts with code
page 437 umlauts convert to UTF-8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-24 09:16:10 +02:00
1 parent 7c08e39607
commit 7742d014f9
9 files changed
+375 -3

No files matched your search

+2 -1
View File
@@ -344,7 +344,8 @@ add_subdirectory(src/import)
# Modern world packages: the world tables and the Classic payload of a Modern data set.
add_library(bmh_modern_content STATIC src/modern/content/world.cpp src/modern/content/world_package.cpp
src/modern/content/world_save.cpp
src/modern/content/world_expand.cpp)
src/modern/content/world_expand.cpp
src/modern/content/statistics.cpp)
target_link_libraries(bmh_modern_content PUBLIC bmh_content bmh_season_modern PRIVATE bmh_miniz)
if(MSVC)
target_compile_options(bmh_modern_content PRIVATE /W4 /utf-8)
+32
View File
@@ -0,0 +1,32 @@
# Spielstatistik (Engine-Abfragen)
Datenquelle für den Button **Spielstatistik** der Modern-Oberfläche (nicht für den Almanach). Die Abfragen werten den [Almanach](almanach.md) der laufenden Karriere aus; der Almanach wird damit zur allgemeinen Datenquelle für Statistiken. Weitere Auswertungen kommen nach demselben Muster dazu.
Code: `src/modern/content/statistics.hpp/.cpp`, Aufruf über `ModernSession::read_statistics(request)`. Nur lesend, keine Wirkung auf Spielstand oder Zufallszahlen.
## Anfragen
| Anfrage | Antwort (zusätzlich zu `ok: true`) |
|---|---|
| `{kind: "competitions"}` | `competitions: [{id, name, type, seasons: ["2026/27", …]}]` – alle Ligen und Pokale mit Ergebnissen, Ligen zuerst |
| `{kind: "winners", competition?}` | `competitions: [{id, name, type, winners: [{season, year, edition, date, winner, runner_up}]}]` – Sieger nach Jahren; ohne `competition` alle Wettbewerbe |
| `{kind: "player_stats", competition, season?, sort?, limit?}` | `players: [{rank, player, club, appearances, goals, assists, yellow, second_yellow, red}]` |
- `competition`: Ligen mit der Liga-ID der Welt (z. B. `comp:de-1`), Pokale als `cup:<Pokal-ID>`, das Hallen-Masters als `cup:11:masters`.
- `season`: `"2026/27"`; fehlt oder `null` = alle Saisons (ewige Liste).
- `sort`: `goals` (Standard), `assists`, `yellow`, `red` (Rot und Gelb-Rot zusammen). Gleichstand: weniger Einsätze zuerst, dann Name. Gleiche Werte haben denselben Rang.
- `limit`: Anzahl Zeilen, Standard 50, `0` = alle. Es erscheinen nur Spieler mit einem Wert > 0 im Sortierkriterium.
- `club`: der Verein des letzten Spiels des Spielers in dieser Auswahl.
- `appearances`: Startelf plus Einwechslungen (nur Ligavereine haben Aufstellungen).
- `winner`/`runner_up`: `{id, name}`; `runner_up` ist `null`, wenn es keinen gibt (Masters, Länderturniere ohne Finale). `edition` zählt mehrere Austragungen einer Saison (Hallenturniere).
- Fehler: `{ok: false, error}` mit `invalid_statistics_request` (Form, Art, Wert) oder `statistics_unavailable`.
## Zuordnung
- Nachgeholte Ligaspiele (intern Wettbewerb 9 „Verlegte Spiele“) zählen zu ihrer Liga und ihrem ursprünglichen Spieltag.
- Freundschaftsspiele (Wettbewerb 10) stehen in `competitions`, haben aber keine Sieger.
- Wettbewerbsnamen: Ligen aus der Welt, Pokale aus den Texten der Ausgabe; die einzelnen Hallenturniere heißen „Hallenturnier“, das Masters „Hallen-Masters“.
## Prüfen
`MODERN_STATS=1 modern_season_sim <welt.obw> 60 0 1` zeigt am Laufende Beispielanfragen und ihre Antworten.
+1
View File
@@ -52,6 +52,7 @@ bmh::modern::app::ModernSession session(path, seed); // erweitert den
| Post | `Mail[]`: Datum, Absender, Betreff, Text | Gelesen markieren | M3 |
| Spieltag | Fortschritt und Ereignisse über den bestehenden Match-Kern | Weiter, Eingriffe | M3 |
| Fußball-Almanach | `ModernState::almanac`: alle Spiele aller Saisons ([Almanach](almanach.md)); Auswertungs-Projektionen folgen, sobald die Oberfläche feststeht | – | M8 (Daten vorhanden) |
| Spielstatistik | `ModernSession::read_statistics`: Sieger nach Jahren, Spielerstatistik je Wettbewerb (Tore, Vorlagen, Gelb, Gelb-Rot, Rot, Einsätze) ([Spielstatistik](statistik.md)) | – | M8 |
Alles, was hier noch fehlt (Transfers, Finanzen, Stadion, Umfeld und weitere
Menüs), folgt nach demselben Muster. Jedes neue Menü der UI bekommt in diesem
+4
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
#include "modern/content/statistics.hpp"
#include "modern/content/world_expand.hpp"
// The engine side of the UI's career handoff (src/ui/flow.hpp, ENGINE_BINDING.md).
//
@@ -813,6 +814,9 @@ public:
const std::filesystem::path &save_path, bool importing_legacy = false);
const ModernState& state() const { return g_; }
// The game statistics menu (docs/new_engine/statistik.md): winners by season, player
// statistics per competition. Read-only; answers {ok, ...} or {ok: false, error}.
cli::Json read_statistics(const cli::Json& request) const { return query_statistics(g_, request); }
ModernState& state() { return g_; }
const TurnResultSnapshot& last_turn_results() const { return turn_driver_.last_results; }
// Owned presentation for the event completed by the last accepted kickoff.
+271
View File
@@ -0,0 +1,271 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/content/statistics.hpp"
#include <algorithm>
#include <cstdio>
#include <map>
#include <string>
#include <variant>
#include <vector>
#include "formats/executable_layout.hpp"
#include "game/messages.hpp"
#include "modern/game/almanac.hpp"
namespace bmh::modern {
namespace {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
J error(const char* code) { return O{{"ok", false}, {"error", code}}; }
std::string season_label(int start_year) {
const int next = (start_year + 1) % 100;
return std::to_string(start_year) + "/" + (next < 10 ? "0" : "") + std::to_string(next);
}
std::string iso_date(uint32_t counter, int display_start_year) {
const AlmanacDate d = almanac_date(counter, display_start_year);
char out[16];
std::snprintf(out, sizeof out, "%04d-%02d-%02d", d.year, d.month, d.day);
return out;
}
// Every season of the career: the finished ones decoded, then the running one.
std::vector<AlmanacSeason> seasons_of(const ModernState& g) {
std::vector<AlmanacSeason> out;
for (const auto& [name, bytes] : g.almanac.finished) out.push_back(decode_almanac_season(bytes));
if (g.almanac.current.season >= 0) out.push_back(g.almanac.current);
return out;
}
// A competition as the statistics name it: leagues by the world's league id, cups by
// their cup id, the indoor Masters apart from the single tournaments.
struct Competition {
std::string id, name, type;
int order = 0; // leagues first (by index), then cups (by cup id)
};
std::string cup_name(const ModernState& g, int cup) {
// The indoor tournament's text names the venue of the next tournament (with a
// placeholder); the statistics list all tournaments under one name.
if (cup == 0xb) return "Hallenturnier";
std::string name;
try {
if (g.texts) name = almanac_utf8(message_text(g, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(cup + 1) * 4));
} catch (const std::exception&) {
name.clear();
}
return name.empty() ? "Pokal " + std::to_string(cup) : name;
}
Competition league_competition(const AlmanacSeason& s, int league) {
Competition c;
c.type = "league";
c.order = league;
for (const auto& l : s.leagues)
if (l.index == league) c.id = l.id, c.name = l.name;
if (c.id.empty()) c.id = "league:" + std::to_string(league);
if (c.name.empty()) c.name = "Liga " + std::to_string(league + 1);
return c;
}
Competition cup_competition(const ModernState& g, int cup, bool masters) {
Competition c;
c.type = "cup";
c.order = 100 + cup * 2 + (masters ? 1 : 0);
c.id = "cup:" + std::to_string(cup) + (masters ? ":masters" : "");
c.name = masters ? "Hallen-Masters" : cup_name(g, cup);
return c;
}
Competition competition_of(const ModernState& g, const AlmanacSeason& s, const AlmanacMatch& m) {
return m.type == 0 ? league_competition(s, m.league) : cup_competition(g, m.type - 1, false);
}
Competition competition_of(const ModernState& g, const AlmanacSeason& s, const AlmanacWinner& w) {
return w.type == 0 ? league_competition(s, w.league) : cup_competition(g, w.type - 1, w.detail == 1);
}
J club_json(const AlmanacSeason& s, uint16_t club) {
if (club >= s.clubs.size()) return nullptr;
return O{{"id", s.clubs[club].id}, {"name", s.clubs[club].name}};
}
std::string player_name(const AlmanacPlayer& p) { return p.first.empty() ? p.last : p.first + " " + p.last; }
const J* field(const J& request, const char* key) {
const auto* o = request.object();
if (!o) return nullptr;
const auto it = o->find(key);
return it == o->end() ? nullptr : &it->second;
}
J competitions(const ModernState& g, const std::vector<AlmanacSeason>& seasons) {
std::map<std::string, std::pair<Competition, std::vector<std::string>>> found; // id -> seasons
auto note = [&](const Competition& c, const std::string& season) {
auto& entry = found[c.id];
entry.first = c;
if (entry.second.empty() || entry.second.back() != season) entry.second.push_back(season);
};
for (const auto& s : seasons) {
const std::string label = season_label(s.start_year);
for (const auto& m : s.matches) note(competition_of(g, s, m), label);
for (const auto& w : s.winners) note(competition_of(g, s, w), label);
}
std::vector<std::pair<Competition, std::vector<std::string>>> list;
for (auto& [id, entry] : found) list.push_back(std::move(entry));
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.first.order < b.first.order; });
A out;
for (const auto& [c, labels] : list) {
A season_list;
for (const auto& l : labels) season_list.push_back(l);
out.push_back(O{{"id", c.id}, {"name", c.name}, {"type", c.type}, {"seasons", std::move(season_list)}});
}
return O{{"ok", true}, {"competitions", std::move(out)}};
}
J winners(const ModernState& g, const std::vector<AlmanacSeason>& seasons, const std::string& only) {
std::map<std::string, std::pair<Competition, A>> found;
for (const auto& s : seasons) {
std::map<std::string, int> edition; // several indoor tournaments in a season
for (const auto& w : s.winners) {
const Competition c = competition_of(g, s, w);
if (!only.empty() && c.id != only) continue;
auto& entry = found[c.id];
entry.first = c;
entry.second.push_back(O{{"season", season_label(s.start_year)}, {"year", s.start_year},
{"edition", ++edition[c.id]}, {"date", iso_date(w.date, s.display_start_year)},
{"winner", club_json(s, w.winner)},
{"runner_up", w.runner_up == 0xffff ? J(nullptr) : club_json(s, w.runner_up)}});
}
}
std::vector<std::pair<Competition, A>> list;
for (auto& [id, entry] : found) list.push_back(std::move(entry));
std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.first.order < b.first.order; });
A out;
for (auto& [c, rows] : list)
out.push_back(O{{"id", c.id}, {"name", c.name}, {"type", c.type}, {"winners", std::move(rows)}});
return O{{"ok", true}, {"competitions", std::move(out)}};
}
struct PlayerRow {
std::string id, name, club_id, club_name;
int appearances = 0, goals = 0, assists = 0, yellow = 0, second_yellow = 0, red = 0;
uint64_t last = 0; // order of the player's last match (his club is the club of that match)
};
J player_stats(const ModernState& g, const std::vector<AlmanacSeason>& seasons, const std::string& competition,
const std::string& season, const std::string& sort, size_t limit) {
std::map<std::string, PlayerRow> rows;
uint64_t order = 0;
for (const auto& s : seasons) {
if (!season.empty() && season_label(s.start_year) != season) continue;
for (const auto& m : s.matches) {
++order;
if (competition_of(g, s, m).id != competition) continue;
auto row = [&](uint16_t player, int side) -> PlayerRow* {
if (player >= s.players.size()) return nullptr;
const AlmanacPlayer& p = s.players[player];
PlayerRow& r = rows[p.id];
r.id = p.id, r.name = player_name(p);
if (order >= r.last) {
const uint16_t club = side ? m.away : m.home;
r.club_id = s.clubs.at(club).id, r.club_name = s.clubs.at(club).name, r.last = order;
}
return &r;
};
for (int side = 0; side < 2; ++side) {
const auto& lineup = m.lineup[size_t(side)];
for (size_t k = 0; k < std::min<size_t>(11, lineup.size()); ++k)
if (PlayerRow* r = row(lineup[k], side)) ++r->appearances;
}
for (const auto& e : m.events) {
switch (e.kind) {
case AlmanacEventKind::Goal:
if (PlayerRow* r = row(e.player, e.side)) ++r->goals;
if (PlayerRow* r = row(e.other, e.side)) ++r->assists;
break;
case AlmanacEventKind::YellowCard:
if (PlayerRow* r = row(e.player, e.side)) ++r->yellow;
break;
case AlmanacEventKind::SecondYellow:
if (PlayerRow* r = row(e.player, e.side)) ++r->second_yellow;
break;
case AlmanacEventKind::RedCard:
if (PlayerRow* r = row(e.player, e.side)) ++r->red;
break;
case AlmanacEventKind::Substitution:
if (PlayerRow* r = row(e.player, e.side)) ++r->appearances;
break;
default:
break;
}
}
}
}
auto key = [&](const PlayerRow& r) {
if (sort == "assists") return r.assists;
if (sort == "yellow") return r.yellow;
if (sort == "red") return r.red + r.second_yellow;
return r.goals;
};
std::vector<PlayerRow> list;
for (auto& [id, r] : rows)
if (key(r) > 0) list.push_back(std::move(r));
std::sort(list.begin(), list.end(), [&](const PlayerRow& a, const PlayerRow& b) {
if (key(a) != key(b)) return key(a) > key(b);
if (a.appearances != b.appearances) return a.appearances < b.appearances; // fewer games ranks first
return a.name < b.name;
});
A out;
int rank = 0, previous = -1;
for (size_t i = 0; i < list.size() && (limit == 0 || i < limit); ++i) {
const PlayerRow& r = list[i];
if (key(r) != previous) rank = int(i) + 1, previous = key(r);
out.push_back(O{{"rank", rank}, {"player", O{{"id", r.id}, {"name", r.name}}},
{"club", O{{"id", r.club_id}, {"name", r.club_name}}}, {"appearances", r.appearances},
{"goals", r.goals}, {"assists", r.assists}, {"yellow", r.yellow},
{"second_yellow", r.second_yellow}, {"red", r.red}});
}
return O{{"ok", true}, {"competition", competition}, {"season", season.empty() ? J(nullptr) : J(season)},
{"sort", sort}, {"players", std::move(out)}};
}
} // namespace
cli::Json query_statistics(const ModernState& g, const cli::Json& request) {
const J* kind = field(request, "kind");
if (!kind || !kind->string()) return error("invalid_statistics_request");
try {
const auto seasons = seasons_of(g);
if (*kind->string() == "competitions") return competitions(g, seasons);
if (*kind->string() == "winners") {
const J* only = field(request, "competition");
if (only && !only->string()) return error("invalid_statistics_request");
return winners(g, seasons, only ? *only->string() : std::string());
}
if (*kind->string() == "player_stats") {
const J* competition = field(request, "competition");
const J* season = field(request, "season");
const J* sort = field(request, "sort");
const J* limit = field(request, "limit");
if (!competition || !competition->string() || (season && !season->string() && !std::holds_alternative<std::nullptr_t>(season->value)) ||
(sort && !sort->string()) || (limit && (!limit->integer() || *limit->integer() < 0)))
return error("invalid_statistics_request");
const std::string order = sort ? *sort->string() : "goals";
if (order != "goals" && order != "assists" && order != "yellow" && order != "red")
return error("invalid_statistics_request");
return player_stats(g, seasons, *competition->string(), season && season->string() ? *season->string() : "",
order, limit ? size_t(*limit->integer()) : 50);
}
return error("invalid_statistics_request");
} catch (const std::exception&) {
return error("statistics_unavailable");
}
}
} // namespace bmh::modern
+22
View File
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Read-only queries for the game statistics menu of the Modern UI ("Spielstatistik";
// docs/new_engine/statistik.md). They evaluate the football almanac (docs/new_engine/
// almanach.md) of the running career and never change the game.
//
// A request is a JSON object with a `kind`; the answer is {ok: true, ...} or
// {ok: false, error}:
// {kind: "competitions"} leagues and cups with recorded results, per season
// {kind: "winners", competition?} the winners of every competition by season
// {kind: "player_stats", competition, season?, sort?, limit?}
// goals, assists, cards per player in one competition,
// of one season ("2026/27") or all seasons
#include "cli/json.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
cli::Json query_statistics(const ModernState& g, const cli::Json& request);
} // namespace bmh::modern
+25 -2
View File
@@ -23,20 +23,29 @@ constexpr size_t kManagerRecord = 0xB0C;
// Version 2 adds the final tables and the winners; version 1 seasons are still read.
constexpr uint32_t kVersion = 2;
// Original single-byte text (ISO 646-DE) to UTF-8, as the interfaces show it.
std::string utf8(std::string_view original) {
std::string utf8(std::string_view original) { return almanac_utf8(original); }
} // namespace
std::string almanac_utf8(std::string_view original) {
static constexpr std::string_view german[] = {"Ä", "Ö", "Ü", "ä", "ö", "ü", "ß"};
static constexpr std::string_view codes = "[\\]{|}~";
// Some engine texts carry the umlauts of code page 437 instead.
static constexpr unsigned char cp437[] = {0x8e, 0x99, 0x9a, 0x84, 0x94, 0x81, 0xe1};
std::string out;
for (char c : original) {
const size_t i = codes.find(c);
const auto* high = std::find(std::begin(cp437), std::end(cp437), static_cast<unsigned char>(c));
if (i != std::string_view::npos) out += german[i];
else if (high != std::end(cp437)) out += german[high - std::begin(cp437)];
else if (static_cast<unsigned char>(c) < 128) out += c;
else out += '?';
}
return out;
}
namespace {
const std::string& entry(const std::vector<std::string>& names, size_t i) {
static const std::string none;
return i < names.size() ? names[i] : none;
@@ -399,6 +408,20 @@ AlmanacRecorder::AlmanacRecorder(ModernState& g, const std::vector<MatchGroup>&
if (rec.type == 0) {
rec.league = uint8_t(id);
if (id < g.league_rounds.size()) rec.round = uint8_t(g.league_rounds[id] + 1);
} else if (rec.type == 10) {
// Competition 9 holds today's replays of postponed league matches, in the order
// of their entries in the postponement table (PrepareReplays): the almanac keeps
// them as matches of their league and original matchday.
int k = 0;
for (uint32_t n = 0; n < 0x28; ++n) {
const uint32_t at = ::bmh::layout::Postponed + n * 6;
if (!g.memory.has(at + 4) || g.memory.u16(at) != uint16_t(g.season_day())) continue;
if (k++ != m) continue;
rec.type = 0;
rec.league = g.memory.u8(at + 3);
rec.round = uint8_t(g.memory.u8(at + 2) + 1);
break;
}
} else if (id >= kCupTable && id < kCupTable + kCupEntries * kCupEntrySize && (id - kCupTable) % kCupEntrySize == 0) {
rec.stage = uint8_t(modern::cup_entry_index(id));
rec.round = uint8_t(modern::cup_round(g.memory, rec.stage) + 1);
+4
View File
@@ -18,6 +18,7 @@
#include <array>
#include <cstdint>
#include <map>
#include <string_view>
#include <string>
#include <utility>
#include <vector>
@@ -170,6 +171,9 @@ struct AlmanacDate { int year = 0, month = 0, day = 0; };
// The calendar date of a day counter (day 0 = 1 July of display_start_year), as the desk shows it.
AlmanacDate almanac_date(uint32_t counter, int display_start_year);
// Original single-byte text (ISO 646-DE) as UTF-8, the form the almanac keeps names in.
std::string almanac_utf8(std::string_view original);
// Binary form of a season (format version 1, little-endian; docs/new_engine/almanach.md).
std::string encode_almanac_season(const AlmanacSeason& season);
// Throws FormatError when the bytes are not an almanac season of a known version.
+14
View File
@@ -474,6 +474,20 @@ int main(int argc, char** argv) {
}
print_first_league_results(g, "run end");
if (modern::current_world()) print_almanac(g);
// MODERN_STATS=1: the queries of the game statistics menu (docs/new_engine/statistik.md)
if (std::getenv("MODERN_STATS")) {
const auto ask = [&](const cli::Json::Object& request) {
std::printf("statistics %s\n -> %s\n", cli::dump_json(request).c_str(),
cli::dump_json(session.read_statistics(request)).c_str());
};
ask({{"kind", "competitions"}});
ask({{"kind", "winners"}, {"competition", "cup:0"}});
ask({{"kind", "player_stats"}, {"competition", g.world_league_id.empty() ? "league:0" : g.world_league_id[0]},
{"season", "2026/27"}, {"limit", 3}});
ask({{"kind", "player_stats"}, {"competition", g.world_league_id.empty() ? "league:0" : g.world_league_id[0]},
{"sort", "yellow"}, {"limit", 3}});
ask({{"kind", "player_stats"}, {"competition", "x"}, {"sort", "dribbles"}});
}
if (std::getenv("SIM_ADVERTISING")) std::printf("%d advertising contracts accepted (SIM_ADVERTISING=1)\n", ad_contracts);
if (std::getenv("SIM_INTERVENE")) std::printf("%d interventions (substitution at minute 30, re-rated)\n", interventions);
if (sim_contracts_env && std::string(sim_contracts_env) == "1")