From f71f0727748d814e7e43510efd09bc5615d73fe5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:15:04 +0100 Subject: [PATCH 1/8] Modern UI contract: running-out contracts during session.advance The original asks for a running-out contract in the middle of the calendar. session.advance takes the answers in contractExpiry (renew with years and salary, or release); a contract without an answer rolls the run back and decision_pending names the player, the interface asks and sends the advance again. The test plays two seasons of kickoffs answering every request. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 2 +- src/modern/app/modern_session.cpp | 52 ++++++++++++++++++++++++++++++ tests/modern_ui_contract_tests.cpp | 21 ++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 7337b0d..5bbc13f 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -55,7 +55,7 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt | Command | payload | Wirkung | |---|---|---| | `camp.book` | `campId`, optional `focus {condition, technique, play}` (0–15; Erholung folgt) | setzt die Schwerpunkte und bucht das Lager wie der Schreibtisch; Fehler `unknown_camp`, `invalid_focus`, `booked_this_week`, `visit_limit`, `insufficient_funds` | -| `session.advance` | `{}` | der Anstoß am Schreibtisch: der Kalender läuft bis zum nächsten Schreibtisch eines Menschen, zum Saisonende oder zum Karriereende (Spiele noch ohne Live-Ansicht); `outcome` `career_ended` am Ende; Fehler `decision_pending` (eine Entscheidung am Schreibtisch fehlt, z. B. ein auslaufender Vertrag), `advance_failed` | +| `session.advance` | optional `contractExpiry {playerId: {action: "renew", years, monthlySalary} | {action: "release"}}` | der Anstoß am Schreibtisch: der Kalender läuft bis zum nächsten Schreibtisch eines Menschen, zum Saisonende oder zum Karriereende (Spiele noch ohne Live-Ansicht); `outcome` `career_ended` am Ende. Läuft unterwegs ein Vertrag aus (das Original fragt in dem Moment), gilt die mitgeschickte Antwort; fehlt sie, wird der Lauf zurückgerollt und `decision_pending` nennt in `message.args` `{decision: "contract_expiry", playerId}` - die UI fragt und schickt den Anstoß mit der Antwort erneut. Sonst `advance_failed` | | `quote.request` | `kind: contract`, `playerId` | fragt die Forderungen des Spielers ab (zieht Zufall wie am Schreibtisch); `outcome: offer_pending`, die Forderungen stehen danach im `contracts`-Read | | `contract.offer` | `quoteId`, `years` 1–4, `monthlySalary` (`Money`) | das Angebot gegen die Forderung; `outcome` `applied` (verlängert) oder `offer_rejected`; das Angebot ist danach verbraucht (`stale_quote`). Versicherung und Prämien folgen | | `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:`, `fund:`) und `count` | wie die Bank am Schreibtisch; Fehler `invalid_amount`, `amount_unavailable`, `invalid_share_count`, `insufficient_funds`, `investment_limit`, `invalid_fund_count` u. a. | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 20b2c7d..7cca294 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -9141,13 +9141,65 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision } else if (kind == "session.advance") { // payload {}: the kickoff of the desk - the calendar runs (matches without live view) to the // next desk of a human manager, the season end desk or the end of the career + // contractExpiry {playerId: {action: "renew", years 1-4, monthlySalary: Money} | {action: "release"}}: + // the answers to contracts running out on the way (the original asks at that moment). A + // contract without an answer stops the run: it is rolled back and decision_pending names + // the player, the interface asks and sends the advance again with the answer. + struct Expiry { bool renew = false; int term = 0; uint32_t salary = 0; }; + std::map answers; + if (const cli::Json* e = ui_field(*payload, "contractExpiry"); e && e->object()) + for (const auto& [id, value] : *e->object()) { + Expiry x; + const std::string action = ui_text(value, "action"); + if (action == "renew") { + const cli::Json* years = ui_field(value, "years"); + const cli::Json* salary = ui_field(value, "monthlySalary"); + int64_t cents = -1; + try { cents = salary ? std::stoll(ui_text(*salary, "minor")) : -1; } catch (const std::exception&) { cents = -1; } + if (!years || !years->integer() || *years->integer() < 1 || *years->integer() > 4 || cents < 0 || cents % 100) + return refuse("invalid_payload", "contractExpiry: renew braucht years 1-4 und monthlySalary."); + x.renew = true, x.term = int(*years->integer() - 1), x.salary = uint32_t(cents / 100); + } else if (action != "release") { + return refuse("invalid_payload", "contractExpiry: action ist renew oder release."); + } + answers[id] = x; + } + std::string pending_player; + auto previous_hook = g_.contract_screen; + const bool previous_installed = contract_expiry_presenter_installed_; + set_contract_expiry_presenter([&](modern::ModernState& state, WatcomRandom& random, int m, int row) -> int { + const int team = m >= 0 && size_t(m) < state.manager_teams.size() ? state.manager_teams[size_t(m)] : -1; + const SquadRange range = squad_range(team); + const int p = size_t(row) < range.count ? state.squad_slots[range.first + size_t(row)] & 0x0fff : 0x0fff; + const std::string id = p == 0x0fff ? std::string{} : modern::ui_player_id(state, p); + const auto it = answers.find(id); + if (it == answers.end()) { pending_player = id; return -2; } // ask the interface + if (!it->second.renew) return 0; // released + try { + const auto demands = modern::contract_demands(state, m, row, false, random); + const uint32_t demand = demands[size_t(it->second.term)]; + if (demand == 0 || demand == UINT32_MAX) return 0; + return modern::contract_offer(state, m, row, it->second.term, it->second.salary, demand, false, true, random, nullptr) ? 1 : 0; + } catch (const std::exception&) { + return -2; + } + }); ui::DeskRequest kickoff; kickoff.kind = ui::DeskRequestKind::advance_turn; kickoff.manager_slot = manager; kickoff.revision = revision; const TurnAdvanceResult r = dispatch_kickoff(kickoff, revision, error); + g_.contract_screen = previous_hook; // the session's own presenter again + contract_expiry_presenter_installed_ = previous_installed; if (r.kind == TurnDeskKind::Failed || r.kind == TurnDeskKind::WaitingAtDesk) { restore(); + g_.contract_screen = previous_hook; + if (!pending_player.empty()) { + cli::Json pending = refuse("decision_pending", "Ein Vertrag läuft aus: Verlängern oder freigeben?"); + auto& message = std::get(std::get(pending.value)["message"].value); + message["args"] = cli::Json::Object{{"decision", "contract_expiry"}, {"playerId", pending_player}}; + return pending; + } const std::string reason = r.reason.empty() ? error : r.reason; return refuse(r.kind == TurnDeskKind::WaitingAtDesk ? "decision_pending" : "advance_failed", "Weiter nicht möglich: " + reason); diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 9dab75b..47b22b3 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -273,6 +273,27 @@ int main(int argc, char** argv) { const std::string date_after = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")); check(date_after > date_before, "the date moved on"); } + // a season of kickoffs: running-out contracts stop the run with decision_pending and the + // player; the advance is sent again with the answer (here: release) + { + O expiry; + int decisions = 0, advances = 0; + for (int k = 0; k < 200 && advances < 120; ++k) { + const uint64_t before = rev; + const J done = session.ui_command(cmd("request:s" + std::to_string(k), "session.advance", O{{"contractExpiry", expiry}}), rev); + if (s(at(done, "messageType")) == "command_result") { ++advances; continue; } + const std::string code = s(at(done, "code")); + const std::string player = s(at(at(at(done, "message"), "args"), "playerId")); + check(code == "decision_pending" && !player.empty() && rev == before, "a pending contract names the player, nothing changed"); + if (code != "decision_pending" || player.empty() || expiry.count(player)) break; + expiry[player] = O{{"action", "release"}}; + ++decisions; + } + check(advances == 120, "two seasons of kickoffs with answered contract decisions"); + check(decisions > 0, "running-out contracts were asked for"); + std::printf("(date now %s)\n", s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")).c_str()); + std::printf("(%d contract decisions answered)\n", decisions); + } // almanac view after the kickoffs: index, calendar, day, match { const J index = session.read_almanac(O{{"kind", "index"}}); From 4372e6b78a92e6de863332f7700ca0fadb796f05 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:16:51 +0100 Subject: [PATCH 2/8] Modern UI contract: advertising read, advertising.accept and budget.commit The advertising read lists boards, shirt and TV rights with their contract and open offers, the three budgets and the finance preview. advertising.accept takes an offer by id, budget.commit sets a budget, both through the desk's own checks. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 3 ++ src/modern/app/modern_session.cpp | 81 +++++++++++++++++++++++++++++- tests/modern_ui_contract_tests.cpp | 26 ++++++++++ 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 5bbc13f..9e8ef0f 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -32,6 +32,7 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `tactics` | die acht Einstellungen (`tactic:0` Grundausrichtung bis `tactic:7` Einsatz) mit Wert und Maximum aus der EXE; die Bedeutung der Diagramm-Einstellungen 1–3, 5, 6 ist nicht belegt, daher neutrale Namen | | `training` | Bälle je Spielertyp und Trainingsbereich (1–3) mit den Grenzen, je Spieler Intensität und Schwerpunkt, ob das Training eingerichtet ist, Automatik-Bits | | `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | +| `advertising` | 14 Banden (`ad:board/`), Trikot (`ad:shirt`), TV-Rechte (`ad:tv`) je mit Vertrag (Sponsor, Monatsbetrag, Restmonate, Verlängerung, Option) und den offenen Angeboten (`offer:ad--`, Sponsor, Betrag, Banden, Monate, `allowed`); die drei Budgets (Merchandising, Presse, Fanarbeit) mit Stand, Höchstbetrag, Lieferwochen; die Finanzvorschau des Originals | | `bank` | Konto, Festgeld, Kreditrahmen, Anlagen (alles `Money`), die 12 Aktien (Kurs, Vorkurs, Bestand, bezahlt, Höchstkauf, 30 Kurse Verlauf) und die angebotenen Fonds; Kredite noch `unavailable` (folgen), der Aktientipp zieht Zufall und kommt als `quote.request` | Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team`. @@ -58,6 +59,8 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt | `session.advance` | optional `contractExpiry {playerId: {action: "renew", years, monthlySalary} | {action: "release"}}` | der Anstoß am Schreibtisch: der Kalender läuft bis zum nächsten Schreibtisch eines Menschen, zum Saisonende oder zum Karriereende (Spiele noch ohne Live-Ansicht); `outcome` `career_ended` am Ende. Läuft unterwegs ein Vertrag aus (das Original fragt in dem Moment), gilt die mitgeschickte Antwort; fehlt sie, wird der Lauf zurückgerollt und `decision_pending` nennt in `message.args` `{decision: "contract_expiry", playerId}` - die UI fragt und schickt den Anstoß mit der Antwort erneut. Sonst `advance_failed` | | `quote.request` | `kind: contract`, `playerId` | fragt die Forderungen des Spielers ab (zieht Zufall wie am Schreibtisch); `outcome: offer_pending`, die Forderungen stehen danach im `contracts`-Read | | `contract.offer` | `quoteId`, `years` 1–4, `monthlySalary` (`Money`) | das Angebot gegen die Forderung; `outcome` `applied` (verlängert) oder `offer_rejected`; das Angebot ist danach verbraucht (`stale_quote`). Versicherung und Prämien folgen | +| `advertising.accept` | `offerId` | nimmt ein Angebot an wie am Schreibtisch; Fehler `unknown_offer`, `advertising_refused` | +| `budget.commit` | `budgetId` (`budget:merchandise`, `budget:press`, `budget:fans`), `amount` (`Money`) | setzt ein Budget; Fehler `unknown_budget`, `invalid_amount`, `advertising_refused` (z. B. Lieferung läuft, zu wenig Geld) | | `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:`, `fund:`) und `count` | wie die Bank am Schreibtisch; Fehler `invalid_amount`, `amount_unavailable`, `invalid_share_count`, `insufficient_funds`, `investment_limit`, `invalid_fund_count` u. a. | | `lineup.commit` | `order`: Spieler-IDs in der gewünschten Reihenfolge | öffnet die Aufstellung wie am Schreibtisch und tauscht die Zeilen; Fehler `unknown_player`, `lineup_refused` (z. B. Verletzte, Ausländerregel) | | `tactics.commit` | `values`: die acht Werte | jede geänderte Einstellung über die Prüfung der Taktiktafel (eine gesetzte Grundausrichtung beendet die Steuerung durch den Assistenten); Fehler `invalid_tactic` | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 7cca294..a17fcba 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8823,7 +8823,8 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co const std::string kind = ui_text(request, "kind"), request_id = ui_text(request, "requestId"); const int manager = context.manager; if (manager < 0 || size_t(manager) >= g_.manager_teams.size() || - (kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts")) + (kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts" && + kind != "advertising")) return modern::ui_read(g_, context, request); if (const std::string wanted = ui_text(request, "managerId"); !wanted.empty() && wanted != modern::ui_manager_id(g_, manager)) return modern::ui_error(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", revision, false); @@ -8853,6 +8854,45 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co {"rows", std::move(rows)}, {"positions", std::move(positions)}, {"depthMax", 19}, {"laneMax", 8}, {"manual", g_.manager_options.size() > size_t(manager) * 5 && g_.manager_options[size_t(manager) * 5] == 0}}); } + if (kind == "advertising") { + // the 14 boards, the shirt and the TV rights with their contract, the open offers per place, + // the three budgets and the original's finance preview + ui::AdvertisingState a; + try { a = ui::advertising_from_game(g_, manager, revision); } catch (const std::exception&) { + return modern::ui_error(request_id, "advertising_unavailable", "Die Werbung ist hier nicht verfügbar.", revision, false); + } + const auto contract = [&](const ui::AdvertisingContract& c, const std::string& id, int display) { + A offers; + if (display >= 0 && display < 16) + for (const auto& o : a.offers[size_t(display)].offers) { + if (!o.present) continue; + const auto& names = display == 15 ? a.television_sponsor_names : a.board_sponsor_names; + offers.push_back(O{{"id", "offer:ad-" + std::to_string(display) + "-" + std::to_string(o.raw_slot)}, + {"sponsor", o.sponsor_id < names.size() ? cli::Json(names[o.sponsor_id]) : cli::Json(nullptr)}, + {"monthly", modern::ui_money(o.monthly_amount)}, {"boards", int(o.bundle_units)}, + {"months", int(o.months)}, {"allowed", o.can_accept}}); + } + return cli::Json(O{{"id", id}, {"active", c.active}, + {"sponsor", c.active ? cli::Json(c.sponsor_name) : cli::Json(nullptr)}, + {"monthly", modern::ui_money(c.monthly_amount)}, {"monthsRemaining", int(c.months_remaining)}, + {"extensionMonths", int(c.extension_months)}, {"option", c.option_marker}, + {"offers", std::move(offers)}}); + }; + A boards; + for (size_t i = 0; i < a.boards.size(); ++i) boards.push_back(contract(a.boards[i], "ad:board/" + std::to_string(i), int(i))); + A budgets; + static constexpr const char* kBudgets[3] = {"budget:merchandise", "budget:press", "budget:fans"}; + for (size_t i = 0; i < 3; ++i) + budgets.push_back(O{{"id", kBudgets[i]}, {"label", a.spending_labels[i]}, {"current", modern::ui_money(a.spending[i].current_amount)}, + {"maximum", modern::ui_money(a.spending[i].maximum_amount)}, {"deliveryWeeks", int(a.spending[i].delivery_weeks)}, + {"available", a.spending[i].available}}); + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "advertising"}, {"teamId", modern::ui_team_id(g_, team)}, {"boards", std::move(boards)}, + {"shirt", contract(a.shirt, "ad:shirt", 14)}, {"television", contract(a.television, "ad:tv", 15)}, + {"budgets", std::move(budgets)}, + {"preview", O{{"income", modern::ui_money(a.finance_preview.income)}, {"expenses", modern::ui_money(a.finance_preview.expenses)}, + {"balance", modern::ui_money(a.finance_preview.balance)}}}}); + } if (kind == "contracts") { // per player: remaining months, monthly salary, insurance, the team bonuses; the open quote // (quote.request) with the monthly demand for one to four years @@ -8985,10 +9025,12 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision const int saved_entry_manager = lineup_entry_manager_, saved_entry_club = lineup_entry_club_; const auto saved_quote = contract_quote_; const uint64_t saved_quote_id = next_contract_quote_id_, saved_contract_request = last_contract_request_id_; + const uint64_t saved_advertising_request = last_advertising_request_id_; const auto restore = [&] { g_ = saved_state; rand_ = saved_rand; game_ = saved_game; revision = previous; lineup_entry_manager_ = saved_entry_manager, lineup_entry_club_ = saved_entry_club; // the board stays as it was contract_quote_ = saved_quote, next_contract_quote_id_ = saved_quote_id, last_contract_request_id_ = saved_contract_request; + last_advertising_request_id_ = saved_advertising_request; }; cli::Json answer; std::string error; @@ -9268,6 +9310,43 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision : result.feedback); if (!result.accepted) std::get(answer.value)["outcome"] = "offer_rejected"; } + } else if (kind == "advertising.accept" || kind == "budget.commit") { + // advertising.accept {offerId: "offer:ad--"}: an offer of the advertising read; + // budget.commit {budgetId: "budget:merchandise|press|fans", amount: Money} + const int team = g_.manager_teams[size_t(manager)]; + if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es keine Werbung."); + const ui::AdvertisingState a = ui::advertising_from_game(g_, manager, revision); + ui::AdvertisingRequest r; + r.request_id = last_advertising_request_id_ + 1; + r.manager_slot = manager, r.runtime_club = team, r.revision = revision; + if (kind == "advertising.accept") { + const std::string id = ui_text(*payload, "offerId"); + int display = -1, raw = -1; + if (std::sscanf(id.c_str(), "offer:ad-%d-%d", &display, &raw) != 2 || display < 0 || display >= 16) + return refuse("unknown_offer", "Unbekanntes Werbeangebot: " + id); + const auto& list = a.offers[size_t(display)]; + const auto offer = std::find_if(list.offers.begin(), list.offers.end(), [&](const auto& o) { return o.present && o.raw_slot == raw; }); + if (offer == list.offers.end() || !offer->can_accept) return refuse("unknown_offer", "Dieses Werbeangebot gibt es nicht (mehr)."); + r.kind = ui::AdvertisingActionKind::accept_offer; + r.offer.manager = manager, r.offer.display_slot = display, r.offer.contract_slot = list.contract_slot; + r.offer.expected_contract = list.contract_bytes, r.offer.raw_slot = raw, r.offer.expected_offer = offer->bytes; + } else { + const std::string id = ui_text(*payload, "budgetId"); + const int index = id == "budget:merchandise" ? 0 : id == "budget:press" ? 1 : id == "budget:fans" ? 2 : -1; + if (index < 0) return refuse("unknown_budget", "Unbekanntes Budget: " + id); + const cli::Json* amount = ui_field(*payload, "amount"); + int64_t cents = -1; + try { cents = amount ? std::stoll(ui_text(*amount, "minor")) : -1; } catch (const std::exception&) { cents = -1; } + if (cents < 0 || cents % 100 || cents / 100 > UINT32_MAX) return refuse("invalid_amount", "amount in ganzen Euro (Money)."); + const auto& view = a.spending[size_t(index)]; + r.kind = ui::AdvertisingActionKind::set_spending; + r.spending.manager = manager, r.spending.target_slot = view.target_slot, r.spending.amount = uint32_t(cents / 100); + r.spending.expected_amount = view.current_amount, r.spending.expected_delivery_weeks = view.delivery_weeks; + } + if (!dispatch_advertising(r, revision, error)) { restore(); return refuse("advertising_refused", error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"advertising", "desktop", "bank"}, + kind == "advertising.accept" ? "Werbevertrag abgeschlossen." : "Budget gesetzt."); } else if (kind == "bank.commit") { // payload {action: deposit|withdraw, amount: Money} or {action: buy|sell, assetId: stock:|fund:, count} const std::string action = ui_text(*payload, "action"); diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 47b22b3..ca23713 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -260,6 +260,32 @@ int main(int argc, char** argv) { "code")) == "stale_quote" && rev == before + 2, "a used quote is gone"); } } + // advertising: the first acceptable offer, a budget + { + const J ads = session.ui_read(O{{"kind", "advertising"}}, rev); + check(s(at(ads, "messageType")) == "snapshot" && at(at(ads, "data"), "boards").array() && + at(at(ads, "data"), "boards").array()->size() == 14, "advertising read"); + std::string offer; + const auto pick = [&](const J& place) { + if (const auto* list = at(place, "offers").array()) + for (const auto& o : *list) + if (offer.empty() && truth(at(o, "allowed"))) offer = s(at(o, "id")); + }; + pick(at(at(ads, "data"), "shirt")); + pick(at(at(ads, "data"), "television")); + if (const auto* boards = at(at(ads, "data"), "boards").array()) + for (const auto& b : *boards) pick(b); + const uint64_t before = rev; + if (!offer.empty()) { + const J done = session.ui_command(cmd("request:w1", "advertising.accept", O{{"offerId", offer}}), rev); + if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "advertising: %s\n", cli::dump_json(done).c_str()); + check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "advertising offer accepted"); + } + const auto kept = modern::save_stream(session.state()); + check(s(at(session.ui_command(cmd("request:w2", "advertising.accept", O{{"offerId", "offer:ad-3-99"}}), rev), "code")) == + "unknown_offer" && modern::save_stream(session.state()) == kept, "unknown offer refused"); + std::printf("(advertising offer %s)\n", offer.empty() ? "none" : offer.c_str()); + } // session.advance: three kickoffs, each one revision, the date moves on { const std::string date_before = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")); From 6386c891b55b17375b72d85d87e4aac622c59a8e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:19:52 +0100 Subject: [PATCH 3/8] Modern UI contract: stadium read and ticket.commit The stadium read lists the periphery (the traffic access with its stage), the eight facilities with their level, the eight stand blocks and the ticket price, with the original names. ticket.commit sets the admission price. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 2 ++ src/modern/app/modern_session.cpp | 56 +++++++++++++++++++++++++++++- tests/modern_season_sim.cpp | 2 +- tests/modern_ui_contract_tests.cpp | 19 ++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 9e8ef0f..771ed01 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -33,6 +33,7 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `training` | Bälle je Spielertyp und Trainingsbereich (1–3) mit den Grenzen, je Spieler Intensität und Schwerpunkt, ob das Training eingerichtet ist, Automatik-Bits | | `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | | `advertising` | 14 Banden (`ad:board/`), Trikot (`ad:shirt`), TV-Rechte (`ad:tv`) je mit Vertrag (Sponsor, Monatsbetrag, Restmonate, Verlängerung, Option) und den offenen Angeboten (`offer:ad--`, Sponsor, Betrag, Banden, Monate, `allowed`); die drei Budgets (Merchandising, Presse, Fanarbeit) mit Stand, Höchstbetrag, Lieferwochen; die Finanzvorschau des Originals | +| `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` 0–3, sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €). Baupreise folgen mit den Stadion-Angeboten | | `bank` | Konto, Festgeld, Kreditrahmen, Anlagen (alles `Money`), die 12 Aktien (Kurs, Vorkurs, Bestand, bezahlt, Höchstkauf, 30 Kurse Verlauf) und die angebotenen Fonds; Kredite noch `unavailable` (folgen), der Aktientipp zieht Zufall und kommt als `quote.request` | Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team`. @@ -61,6 +62,7 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt | `contract.offer` | `quoteId`, `years` 1–4, `monthlySalary` (`Money`) | das Angebot gegen die Forderung; `outcome` `applied` (verlängert) oder `offer_rejected`; das Angebot ist danach verbraucht (`stale_quote`). Versicherung und Prämien folgen | | `advertising.accept` | `offerId` | nimmt ein Angebot an wie am Schreibtisch; Fehler `unknown_offer`, `advertising_refused` | | `budget.commit` | `budgetId` (`budget:merchandise`, `budget:press`, `budget:fans`), `amount` (`Money`) | setzt ein Budget; Fehler `unknown_budget`, `invalid_amount`, `advertising_refused` (z. B. Lieferung läuft, zu wenig Geld) | +| `ticket.commit` | `price` (`Money`, 8–25 €) | der Eintrittspreis; Fehler `invalid_amount`, `ticket_refused` | | `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:`, `fund:`) und `count` | wie die Bank am Schreibtisch; Fehler `invalid_amount`, `amount_unavailable`, `invalid_share_count`, `insufficient_funds`, `investment_limit`, `invalid_fund_count` u. a. | | `lineup.commit` | `order`: Spieler-IDs in der gewünschten Reihenfolge | öffnet die Aufstellung wie am Schreibtisch und tauscht die Zeilen; Fehler `unknown_player`, `lineup_refused` (z. B. Verletzte, Ausländerregel) | | `tactics.commit` | `values`: die acht Werte | jede geänderte Einstellung über die Prüfung der Taktiktafel (eine gesetzte Grundausrichtung beendet die Steuerung durch den Assistenten); Fehler `invalid_tactic` | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index a17fcba..fab330a 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8824,7 +8824,7 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co const int manager = context.manager; if (manager < 0 || size_t(manager) >= g_.manager_teams.size() || (kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts" && - kind != "advertising")) + kind != "advertising" && kind != "stadium")) return modern::ui_read(g_, context, request); if (const std::string wanted = ui_text(request, "managerId"); !wanted.empty() && wanted != modern::ui_manager_id(g_, manager)) return modern::ui_error(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", revision, false); @@ -8854,6 +8854,47 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co {"rows", std::move(rows)}, {"positions", std::move(positions)}, {"depthMax", 19}, {"laneMax", 8}, {"manual", g_.manager_options.size() > size_t(manager) * 5 && g_.manager_options[size_t(manager) * 5] == 0}}); } + if (kind == "stadium") { + // the periphery (14 objects; the traffic access has three stages), the eight facilities with + // their level, the eight stand blocks (capacity in thousands, seats, roof) and the ticket price; + // building prices follow with the stadium quotes (they carry the day's construction percent) + ui::StadiumState st; + ui::StadiumDataProjection data; + try { + st = ui::stadium_from_game(g_, exe_, revision); + data = ui::stadium_data_from_game(g_, exe_, manager, 0x40); + } catch (const std::exception&) { + return modern::ui_error(request_id, "stadium_unavailable", "Das Stadion ist hier nicht verfügbar.", revision, false); + } + const auto text = [&](size_t id) { return g_.texts && id < g_.texts->strings.size() ? ui::original_to_utf8(g_.texts->strings[id]) : std::string{}; }; + A periphery, facilities, blocks; + for (size_t o = 0; o < 14; ++o) { + const int level = st.level[o]; + O row{{"id", "periphery:" + std::to_string(o)}, {"name", text(720 + o)}, {"constructionDays", int(st.days[o])}}; + if (o == 0) row["stage"] = level == 0 ? 0 : (level - 1) / 85 + 1, row["maxStage"] = 3; + else row["built"] = level != 0; + periphery.push_back(std::move(row)); + } + static constexpr const char* kFacilities[8] = {"floodlights", "scoreboard", "pitch_heating", "vip_lounge", "pitch", "comfort", "condition", "safety"}; + for (size_t i = 0; i < 8; ++i) { + const auto& f = st.investments[i]; + facilities.push_back(O{{"id", std::string("facility:") + kFacilities[i]}, {"name", text(734 + i)}, + {"level", int(f.current_level)}, {"maxLevel", i == 2 || i == 3 ? 2 : 4}, + {"constructionWeeks", int(f.construction_weeks)}, {"upgradeAvailable", f.available}}); + } + for (size_t b = 0; b < st.blocks.size(); ++b) { + const auto& k = st.blocks[b]; + blocks.push_back(O{{"id", "block:" + std::string(1, char('a' + b))}, {"name", text(742 + b)}, + {"places", int64_t(k.capacity_level) * 1000}, + {"maxPlaces", int64_t(exe_.u8(::bmh::layout::CareerSession_Invalid_RuntimeField + uint32_t(b))) * 1000}, + {"seats", (k.flags & 1) != 0}, {"roof", (k.flags & 2) != 0}, + {"constructionWeeks", int(k.construction_weeks)}, {"placesAfterConstruction", int64_t(k.capacity) * 1000}}); + } + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "stadium"}, {"teamId", modern::ui_team_id(g_, team)}, {"periphery", std::move(periphery)}, + {"facilities", std::move(facilities)}, {"blocks", std::move(blocks)}, + {"ticketPrice", modern::ui_money(data.ticket_price)}, {"ticketPriceRange", O{{"min", modern::ui_money(8)}, {"max", modern::ui_money(25)}}}}); + } if (kind == "advertising") { // the 14 boards, the shirt and the TV rights with their contract, the open offers per place, // the three budgets and the original's finance preview @@ -9347,6 +9388,19 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision revision = previous + 1; answer = modern::ui_command_result(request_id, previous, revision, {"advertising", "desktop", "bank"}, kind == "advertising.accept" ? "Werbevertrag abgeschlossen." : "Budget gesetzt."); + } else if (kind == "ticket.commit") { + // payload {price: Money}: the admission price, 8 to 25 euros + const cli::Json* price = ui_field(*payload, "price"); + int64_t cents = -1; + try { cents = price ? std::stoll(ui_text(*price, "minor")) : -1; } catch (const std::exception&) { cents = -1; } + if (cents < 800 || cents > 2500 || cents % 100) return refuse("invalid_amount", "Eintritt 8 bis 25 Euro in ganzen Euro."); + TicketPriceRequest r; + r.identity.manager_slot = manager, r.identity.runtime_club = g_.manager_teams[size_t(manager)], r.identity.revision = revision; + r.identity.stable_club_identity = int(g_.club_ids.at(size_t(r.identity.runtime_club))); + r.price = int(cents / 100); + if (!dispatch_ticket_price(r, revision, error)) { restore(); return refuse("ticket_refused", error); } + if (revision != previous) revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"stadium"}, "Eintrittspreis gesetzt."); } else if (kind == "bank.commit") { // payload {action: deposit|withdraw, amount: Money} or {action: buy|sell, assetId: stock:|fund:, count} const std::string action = ui_text(*payload, "action"); diff --git a/tests/modern_season_sim.cpp b/tests/modern_season_sim.cpp index dbee00c..aa78a45 100644 --- a/tests/modern_season_sim.cpp +++ b/tests/modern_season_sim.cpp @@ -743,7 +743,7 @@ int main(int argc, char** argv) { read({{"kind", "squad"}}); read({{"kind", "table"}, {"league", 42}}); // the interface contract (docs/new_engine/ui-anbindung.md) - for (const char* kind : {"session", "desktop", "squad", "camps", "nonsense"}) { + for (const char* kind : {"session", "desktop", "squad", "camps", "stadium", "nonsense"}) { const auto request = cli::Json::Object{{"kind", kind}, {"requestId", std::string("request:sim-") + kind}}; std::printf("ui_read %s\n -> %s\n", kind, cli::dump_json(session.ui_read(request, revision)).c_str()); } diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index ca23713..9ccfa3a 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -286,6 +286,25 @@ int main(int argc, char** argv) { "unknown_offer" && modern::save_stream(session.state()) == kept, "unknown offer refused"); std::printf("(advertising offer %s)\n", offer.empty() ? "none" : offer.c_str()); } + // stadium: periphery, facilities, blocks; the ticket price + { + const J stadium = session.ui_read(O{{"kind", "stadium"}}, rev); + const J& d = at(stadium, "data"); + if (s(at(stadium, "messageType")) != "snapshot") std::fprintf(stderr, "stadium: %s\n", cli::dump_json(stadium).c_str()); + check(at(d, "periphery").array() && at(d, "periphery").array()->size() == 14 && at(d, "blocks").array() && + at(d, "blocks").array()->size() == 8 && at(d, "facilities").array() && at(d, "facilities").array()->size() == 8, + "stadium read"); + if (const auto* p = at(d, "periphery").array(); p && !p->empty()) + check(!s(at((*p)[0], "name")).empty() && at((*p)[0], "stage").integer(), "traffic access with its stage"); + const uint64_t before = rev; + const J done = session.ui_command(cmd("request:e1", "ticket.commit", O{{"price", O{{"minor", "1200"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev); + if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "ticket: %s\n", cli::dump_json(done).c_str()); + const J after = session.ui_read(O{{"kind", "stadium"}}, rev); + check(s(at(done, "messageType")) == "command_result" && s(at(at(at(after, "data"), "ticketPrice"), "minor")) == "1200" && + rev <= before + 1, "ticket price set"); + check(s(at(session.ui_command(cmd("request:e2", "ticket.commit", O{{"price", O{{"minor", "3000"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev), + "code")) == "invalid_amount", "ticket price above 25 refused"); + } // session.advance: three kickoffs, each one revision, the date moves on { const std::string date_before = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")); From e6bc72d3a0c84981a78f92d25cf55e51c7a5769f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:23:06 +0100 Subject: [PATCH 4/8] Modern UI contract: building in the stadium (periphery and facilities) The original's stadium dialog in two commands: quote.request opens it and gets the building firm's offer (periphery) or selects a facility and levels; stadium.commit builds - facilities with or without the tip for faster building - or declines, and closes the dialog. The stadium read shows the open offer; a refused command also restores the dialog. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 4 +- src/modern/app/modern_session.cpp | 106 ++++++++++++++++++++++++++++- tests/modern_ui_contract_tests.cpp | 49 +++++++++++-- 3 files changed, 152 insertions(+), 7 deletions(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 771ed01..de77396 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -33,7 +33,7 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `training` | Bälle je Spielertyp und Trainingsbereich (1–3) mit den Grenzen, je Spieler Intensität und Schwerpunkt, ob das Training eingerichtet ist, Automatik-Bits | | `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | | `advertising` | 14 Banden (`ad:board/`), Trikot (`ad:shirt`), TV-Rechte (`ad:tv`) je mit Vertrag (Sponsor, Monatsbetrag, Restmonate, Verlängerung, Option) und den offenen Angeboten (`offer:ad--`, Sponsor, Betrag, Banden, Monate, `allowed`); die drei Budgets (Merchandising, Presse, Fanarbeit) mit Stand, Höchstbetrag, Lieferwochen; die Finanzvorschau des Originals | -| `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` 0–3, sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €). Baupreise folgen mit den Stadion-Angeboten | +| `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` 0–3, sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €); das offene Angebot des Stadion-Dialogs (`quote`: Umfeld mit Preis, oder Anlage mit Zielstufe, Preis, Bauwochen und dem Trinkgeld-Bereich 6–14 %) | | `bank` | Konto, Festgeld, Kreditrahmen, Anlagen (alles `Money`), die 12 Aktien (Kurs, Vorkurs, Bestand, bezahlt, Höchstkauf, 30 Kurse Verlauf) und die angebotenen Fonds; Kredite noch `unavailable` (folgen), der Aktientipp zieht Zufall und kommt als `quote.request` | Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team`. @@ -63,6 +63,8 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt | `advertising.accept` | `offerId` | nimmt ein Angebot an wie am Schreibtisch; Fehler `unknown_offer`, `advertising_refused` | | `budget.commit` | `budgetId` (`budget:merchandise`, `budget:press`, `budget:fans`), `amount` (`Money`) | setzt ein Budget; Fehler `unknown_budget`, `invalid_amount`, `advertising_refused` (z. B. Lieferung läuft, zu wenig Geld) | | `ticket.commit` | `price` (`Money`, 8–25 €) | der Eintrittspreis; Fehler `invalid_amount`, `ticket_refused` | +| `quote.request` (Stadion) | `kind: periphery`, `objectId` oder `kind: facility`, `facilityId`, `increment` 1–3 | öffnet den Stadion-Dialog und holt das Angebot der Baufirma bzw. wählt Anlage und Stufen; `offer_pending`. Der Dialog bleibt offen (andere Schreibtisch-Einstellungen sind bis dahin gesperrt, `quote_open` für ein zweites Angebot) | +| `stadium.commit` | `quoteId`, `accept`, bei Anlagen `tip` | baut (Anlagen mit oder ohne Trinkgeld für schnelleres Bauen, wie das Original fragt) oder lehnt ab und schließt den Dialog; Fehler `stale_quote`, `stadium_refused` | | `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:`, `fund:`) und `count` | wie die Bank am Schreibtisch; Fehler `invalid_amount`, `amount_unavailable`, `invalid_share_count`, `insufficient_funds`, `investment_limit`, `invalid_fund_count` u. a. | | `lineup.commit` | `order`: Spieler-IDs in der gewünschten Reihenfolge | öffnet die Aufstellung wie am Schreibtisch und tauscht die Zeilen; Fehler `unknown_player`, `lineup_refused` (z. B. Verletzte, Ausländerregel) | | `tactics.commit` | `values`: die acht Werte | jede geänderte Einstellung über die Prüfung der Taktiktafel (eine gesetzte Grundausrichtung beendet die Steuerung durch den Assistenten); Fehler `invalid_tactic` | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index fab330a..703a24c 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8890,8 +8890,20 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co {"seats", (k.flags & 1) != 0}, {"roof", (k.flags & 2) != 0}, {"constructionWeeks", int(k.construction_weeks)}, {"placesAfterConstruction", int64_t(k.capacity) * 1000}}); } + // the open offer of the stadium dialog (quote.request), answered by stadium.commit + cli::Json quote = nullptr; + if (stadium_.opened && stadium_.manager == manager) { + const std::string id = "quote:stadium-" + std::to_string(stadium_.scope); + if (stadium_.periphery_quote) + quote = O{{"id", id}, {"kind", "periphery"}, {"objectId", "periphery:" + std::to_string(stadium_.periphery_quote->first)}, + {"price", modern::ui_money(stadium_.periphery_quote->second)}}; + else if (stadium_.investment && stadium_.option) + quote = O{{"id", id}, {"kind", "facility"}, {"facilityId", std::string("facility:") + kFacilities[size_t(*stadium_.investment)]}, + {"toLevel", int(stadium_.option->target_level)}, {"price", modern::ui_money(stadium_.option->base_price)}, + {"weeks", int(stadium_.option->base_weeks)}, {"tipPercent", O{{"min", 6}, {"max", 14}}}}; + } return modern::ui_snapshot(g_, context, request_id, - O{{"kind", "stadium"}, {"teamId", modern::ui_team_id(g_, team)}, {"periphery", std::move(periphery)}, + O{{"kind", "stadium"}, {"teamId", modern::ui_team_id(g_, team)}, {"quote", std::move(quote)}, {"periphery", std::move(periphery)}, {"facilities", std::move(facilities)}, {"blocks", std::move(blocks)}, {"ticketPrice", modern::ui_money(data.ticket_price)}, {"ticketPriceRange", O{{"min", modern::ui_money(8)}, {"max", modern::ui_money(25)}}}}); } @@ -9067,11 +9079,14 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision const auto saved_quote = contract_quote_; const uint64_t saved_quote_id = next_contract_quote_id_, saved_contract_request = last_contract_request_id_; const uint64_t saved_advertising_request = last_advertising_request_id_; + const StadiumRuntime saved_stadium = stadium_; + const uint64_t saved_stadium_scope = next_stadium_scope_; const auto restore = [&] { g_ = saved_state; rand_ = saved_rand; game_ = saved_game; revision = previous; lineup_entry_manager_ = saved_entry_manager, lineup_entry_club_ = saved_entry_club; // the board stays as it was contract_quote_ = saved_quote, next_contract_quote_id_ = saved_quote_id, last_contract_request_id_ = saved_contract_request; last_advertising_request_id_ = saved_advertising_request; + stadium_ = saved_stadium, next_stadium_scope_ = saved_stadium_scope; }; cli::Json answer; std::string error; @@ -9296,6 +9311,95 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision "statistics", "almanac"}, what); if (r.kind == TurnDeskKind::CareerComplete) std::get(answer.value)["outcome"] = "career_ended"; + } else if ((kind == "quote.request" && (ui_text(*payload, "kind") == "periphery" || ui_text(*payload, "kind") == "facility")) || + kind == "stadium.commit") { + // The stadium dialog of the original in two commands; it stays open in between: + // quote.request {kind: periphery, objectId} - opens the stadium, the building firm's offer + // quote.request {kind: facility, facilityId, increment 1-3} - a facility and how many levels + // stadium.commit {quoteId, accept, tip?} - builds (facilities: with or without the tip for + // faster building, as the original asks) or declines, and closes the stadium + const int team = g_.manager_teams[size_t(manager)]; + if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es kein Stadion."); + bool ok = true; + const auto step = [&](ui::StadiumRequestKind k, int object = -1, int option = -1, int32_t price = 0, bool tip = false) { + if (!ok) return; + ui::StadiumRequest r; + r.kind = k, r.manager_slot = manager, r.runtime_club = team, r.revision = revision; + r.stable_club_identity = int(g_.club_ids.at(size_t(team))); + if (k != ui::StadiumRequestKind::open) r.scope = stadium_.scope, r.sequence = stadium_.sequence; + r.object = object, r.option = option, r.price = price, r.accept_tip = tip; + ok = dispatch_stadium(r, revision, error); + }; + static constexpr const char* kFacilities[8] = {"floodlights", "scoreboard", "pitch_heating", "vip_lounge", "pitch", "comfort", "condition", "safety"}; + if (kind == "quote.request") { + if (stadium_.opened && (stadium_.periphery_quote || stadium_.investment)) + return refuse("quote_open", "Ein Stadionangebot ist noch offen (stadium.commit)."); + if (!stadium_.opened) step(ui::StadiumRequestKind::open); + if (ui_text(*payload, "kind") == "periphery") { + int object = -1; + if (std::sscanf(ui_text(*payload, "objectId").c_str(), "periphery:%d", &object) != 1 || object < 0 || object >= 14) { + restore(); return refuse("unknown_object", "Unbekanntes Umfeldobjekt."); + } + step(ui::StadiumRequestKind::quote_periphery, object); + } else { + const std::string id = ui_text(*payload, "facilityId"); + int facility = -1; + for (int i = 0; i < 8; ++i) if (id == std::string("facility:") + kFacilities[i]) facility = i; + const cli::Json* inc = ui_field(*payload, "increment"); + if (facility < 0 || !inc || !inc->integer() || *inc->integer() < 1 || *inc->integer() > 3) { + restore(); return refuse("invalid_payload", "facilityId und increment (1 bis 3) nötig."); + } + step(ui::StadiumRequestKind::select_investment, facility); + if (ok) { + StadiumInvestmentConstants constants; + for (unsigned i = 0; i < 8; ++i) { + constants.price[i] = exe_.u32(::bmh::layout::CareerSession_DispatchStadium_RuntimeField + i * 4); + constants.weeks[i] = exe_.u8(::bmh::layout::CareerSession_DispatchStadium_RuntimeField2 + (14 + i) * 5); + } + const auto options = modern::stadium_investment_options_source(g_, manager, static_cast(facility), + stadium_.price_percent, constants); + const size_t option = size_t(*inc->integer() - 1); + if (option >= options.size()) { restore(); return refuse("level_unavailable", "So viele Stufen sind nicht möglich."); } + step(ui::StadiumRequestKind::select_investment_option, facility, int(option), int32_t(options[option].base_price)); + } + } + if (!ok) { restore(); return refuse("stadium_refused", error); } + revision = previous + 1; + stadium_.revision = revision; // the open dialog continues at the command's one revision + answer = modern::ui_command_result(request_id, previous, revision, {"stadium"}, "Angebot liegt vor."); + std::get(answer.value)["outcome"] = "offer_pending"; + } else { + const std::string quote = ui_text(*payload, "quoteId"); + const cli::Json* accept = ui_field(*payload, "accept"); + const cli::Json* tip = ui_field(*payload, "tip"); + const bool yes = accept && std::holds_alternative(accept->value) && std::get(accept->value); + const bool with_tip = tip && std::holds_alternative(tip->value) && std::get(tip->value); + if (!stadium_.opened || quote != "quote:stadium-" + std::to_string(stadium_.scope)) + return refuse("stale_quote", "Dieses Stadionangebot gilt nicht mehr."); + if (stadium_.periphery_quote) { + const auto [object, price] = *stadium_.periphery_quote; + step(yes ? ui::StadiumRequestKind::build_periphery : ui::StadiumRequestKind::decline_periphery, object, -1, price); + } else if (stadium_.investment && stadium_.option) { + const int facility = int(*stadium_.investment), option = stadium_.option_index; + const int32_t base = int32_t(stadium_.option->base_price); + if (!yes) { + step(ui::StadiumRequestKind::cancel_investment, facility); + } else { + step(ui::StadiumRequestKind::confirm_investment, facility, option, base); + if (ok && stadium_.tip) + step(ui::StadiumRequestKind::answer_construction_tip, facility, option, + int32_t(with_tip ? stadium_.tip->offered_price : stadium_.tip->base_price), with_tip); + } + } else { + return refuse("stale_quote", "Es liegt kein Stadionangebot vor."); + } + const std::string feedback = stadium_.feedback; + step(ui::StadiumRequestKind::close); + if (!ok) { restore(); return refuse("stadium_refused", error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"stadium", "desktop", "bank"}, + !feedback.empty() ? feedback : yes ? "Der Bau beginnt." : "Abgelehnt."); + } } else if (kind == "quote.request" || kind == "contract.offer") { // quote.request {kind: "contract", playerId}: the player's demands for one to four years // (draws a random number, as at the desk); contract.offer {quoteId, years 1-4, diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 9ccfa3a..251dda0 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -304,6 +304,43 @@ int main(int argc, char** argv) { rev <= before + 1, "ticket price set"); check(s(at(session.ui_command(cmd("request:e2", "ticket.commit", O{{"price", O{{"minor", "3000"}, {"currency", "EUR"}, {"minorUnits", 2}}}}), rev), "code")) == "invalid_amount", "ticket price above 25 refused"); + // building: a periphery object not built yet, then a facility level without the tip + std::string object; + if (const auto* p = at(at(after, "data"), "periphery").array()) + for (const auto& o : *p) + if (object.empty() && at(o, "built").value.index() == 1 && !truth(at(o, "built")) && *at(o, "constructionDays").integer() == 0) + object = s(at(o, "id")); + const auto quote_of = [&]() { const J st = session.ui_read(O{{"kind", "stadium"}}, rev); return J(at(at(st, "data"), "quote")); }; + if (!object.empty()) { + const uint64_t b0 = rev; + const J q = session.ui_command(cmd("request:e3", "quote.request", O{{"kind", "periphery"}, {"objectId", object}}), rev); + if (s(at(q, "messageType")) != "command_result") std::fprintf(stderr, "periphery quote: %s\n", cli::dump_json(q).c_str()); + const J quote = quote_of(); + check(s(at(q, "outcome")) == "offer_pending" && s(at(quote, "objectId")) == object && rev == b0 + 1, "periphery quoted"); + const J built = session.ui_command(cmd("request:e4", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}}), rev); + if (s(at(built, "messageType")) != "command_result") std::fprintf(stderr, "periphery build: %s\n", cli::dump_json(built).c_str()); + check(s(at(built, "messageType")) == "command_result" && rev == b0 + 2 && std::holds_alternative(quote_of().value), + "periphery built, the stadium closed"); + } + { + const uint64_t b0 = rev; + const J q = session.ui_command(cmd("request:e5", "quote.request", O{{"kind", "facility"}, {"facilityId", "facility:safety"}, {"increment", 1}}), rev); + const J quote = quote_of(); + if (s(at(q, "messageType")) == "command_result") { + check(s(at(quote, "kind")) == "facility" && at(quote, "price").object(), "facility quoted"); + const J done = session.ui_command(cmd("request:e6", "stadium.commit", O{{"quoteId", at(quote, "id")}, {"accept", true}, {"tip", false}}), rev); + if (s(at(done, "messageType")) != "command_result") std::fprintf(stderr, "facility build: %s\n", cli::dump_json(done).c_str()); + check(s(at(done, "messageType")) == "command_result" && rev == b0 + 2, "facility ordered"); + } else { + std::printf("(facility quote: %s)\n", s(at(q, "code")).c_str()); + } + const J q2 = session.ui_command(cmd("request:e7", "quote.request", O{{"kind", "facility"}, {"facilityId", "facility:comfort"}, {"increment", 1}}), rev); + if (s(at(q2, "messageType")) == "command_result") { + const J declined = session.ui_command(cmd("request:e8", "stadium.commit", O{{"quoteId", at(quote_of(), "id")}, {"accept", false}}), rev); + check(s(at(declined, "messageType")) == "command_result" && std::holds_alternative(quote_of().value), + "facility offer declined, the stadium closed"); + } + } } // session.advance: three kickoffs, each one revision, the date moves on { @@ -361,15 +398,17 @@ int main(int argc, char** argv) { check(s(at(session.read_almanac(O{{"kind", "match"}, {"id", "match:0-0"}}), "error")) == "almanac_match_not_found", "unknown match"); // the statistics screen: real data (fictional false), unrecorded views say so + // (the club views need a club desk: on an international day the manager sits at the national one) const J minutes = session.read_statistics_screen(O{{"section", 8}}); - check(truth(at(minutes, "ok")) && !truth(at(minutes, "fictional")) && at(minutes, "rows").array() && - at(minutes, "rows").array()->size() == 4, "minute statistics"); - const J transfers = session.read_statistics_screen(O{{"section", 1}}); + const bool club_desk = !std::holds_alternative(at(minutes, "club").value); + check(truth(at(minutes, "ok")) && !truth(at(minutes, "fictional")) && + (!club_desk || (at(minutes, "rows").array() && at(minutes, "rows").array()->size() == 4)), "minute statistics"); + const J transfers = session.read_statistics_screen(O{{"section", 0}}); check(truth(at(transfers, "ok")) && !truth(at(transfers, "available")) && s(at(transfers, "reason")) == "not_recorded", - "transfer history not recorded"); + "title chances not recorded"); check(s(at(session.read_statistics_screen(O{{"section", 9}}), "error")) == "invalid_statistics_filter", "bad section"); const J curves = session.read_statistics_screen(O{{"section", 2}}); - check(at(curves, "series").array() && at(curves, "series").array()->size() == 6, "the six curves of the original"); + check(!club_desk || (at(curves, "series").array() && at(curves, "series").array()->size() == 6), "the six curves of the original"); } } catch (const std::exception& ex) { std::fprintf(stderr, "FAIL: %s\n", ex.what()); From 43317985e406035f6009d3a280721645ae49031c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:29:25 +0100 Subject: [PATCH 5/8] Modern UI contract: toto and exclusive sponsor reads and commands toto and sponsor reads in the envelope (amounts as Money), toto.submit with up to six columns and sponsor.answer for a camp's exclusive sponsor offer. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 4 ++++ src/modern/app/modern_session.cpp | 34 ++++++++++++++++++++++++++++++ src/modern/content/ui_contract.cpp | 20 ++++++++++++++++++ tests/modern_ui_contract_tests.cpp | 15 +++++++++++++ 4 files changed, 73 insertions(+) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index de77396..c660e24 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -34,6 +34,8 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | | `advertising` | 14 Banden (`ad:board/`), Trikot (`ad:shirt`), TV-Rechte (`ad:tv`) je mit Vertrag (Sponsor, Monatsbetrag, Restmonate, Verlängerung, Option) und den offenen Angeboten (`offer:ad--`, Sponsor, Betrag, Banden, Monate, `allowed`); die drei Budgets (Merchandising, Presse, Fanarbeit) mit Stand, Höchstbetrag, Lieferwochen; die Finanzvorschau des Originals | | `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` 0–3, sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €); das offene Angebot des Stadion-Dialogs (`quote`: Umfeld mit Preis, oder Anlage mit Zielstufe, Preis, Bauwochen und dem Trinkgeld-Bereich 6–14 %) | +| `toto` | der Tippschein ([Toto](toto.md)): `open` (elf Spiele), Spiele, Einsatz und Kosten (`Money`), Spalten, Regeln, letzte Abrechnung | +| `sponsor` | das Exklusiv-Sponsor-Angebot aus einem Trainingslager und ein vorgemerkter Vertrag (`monthly` als `Money`; `asset: null`, siehe [Trainingslager](trainingslager.md)) | | `bank` | Konto, Festgeld, Kreditrahmen, Anlagen (alles `Money`), die 12 Aktien (Kurs, Vorkurs, Bestand, bezahlt, Höchstkauf, 30 Kurse Verlauf) und die angebotenen Fonds; Kredite noch `unavailable` (folgen), der Aktientipp zieht Zufall und kommt als `quote.request` | Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`, `unknown_team`. @@ -63,6 +65,8 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt | `advertising.accept` | `offerId` | nimmt ein Angebot an wie am Schreibtisch; Fehler `unknown_offer`, `advertising_refused` | | `budget.commit` | `budgetId` (`budget:merchandise`, `budget:press`, `budget:fans`), `amount` (`Money`) | setzt ein Budget; Fehler `unknown_budget`, `invalid_amount`, `advertising_refused` (z. B. Lieferung läuft, zu wenig Geld) | | `ticket.commit` | `price` (`Money`, 8–25 €) | der Eintrittspreis; Fehler `invalid_amount`, `ticket_refused` | +| `toto.submit` | `stake` (`Money` je Spalte), `columns` (bis 6 Spalten mit 11 Tipps: 1 Heim, 0 Unentschieden, 2 Auswärts) | gibt den Tippschein ab; Fehler `toto_refused` (z. B. kein offener Schein, Einsatzgrenzen, doppelte Spalte) | +| `sponsor.answer` | `accept` | Antwort auf das Exklusiv-Sponsor-Angebot: beginnt sofort, wird vorgemerkt oder abgelehnt | | `quote.request` (Stadion) | `kind: periphery`, `objectId` oder `kind: facility`, `facilityId`, `increment` 1–3 | öffnet den Stadion-Dialog und holt das Angebot der Baufirma bzw. wählt Anlage und Stufen; `offer_pending`. Der Dialog bleibt offen (andere Schreibtisch-Einstellungen sind bis dahin gesperrt, `quote_open` für ein zweites Angebot) | | `stadium.commit` | `quoteId`, `accept`, bei Anlagen `tip` | baut (Anlagen mit oder ohne Trinkgeld für schnelleres Bauen, wie das Original fragt) oder lehnt ab und schließt den Dialog; Fehler `stale_quote`, `stadium_refused` | | `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:`, `fund:`) und `count` | wie die Bank am Schreibtisch; Fehler `invalid_amount`, `amount_unavailable`, `invalid_share_count`, `insufficient_funds`, `investment_limit`, `invalid_fund_count` u. a. | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 703a24c..ff50d18 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -9492,6 +9492,40 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision revision = previous + 1; answer = modern::ui_command_result(request_id, previous, revision, {"advertising", "desktop", "bank"}, kind == "advertising.accept" ? "Werbevertrag abgeschlossen." : "Budget gesetzt."); + } else if (kind == "toto.submit") { + // payload {stake: Money per column, columns: [[11 tips: 1 home, 0 draw, 2 away], ... up to 6]} + const cli::Json* stake = ui_field(*payload, "stake"); + const cli::Json* columns = ui_field(*payload, "columns"); + int64_t cents = -1; + try { cents = stake ? std::stoll(ui_text(*stake, "minor")) : -1; } catch (const std::exception&) { cents = -1; } + if (cents <= 0 || cents % 100 || !columns || !columns->array()) return refuse("invalid_payload", "stake (Money) und columns nötig."); + std::vector> tips; + for (const auto& column : *columns->array()) { + const auto* c = column.array(); + if (!c || c->size() != 11) return refuse("invalid_payload", "Jede Spalte hat elf Tipps."); + std::array t{}; + for (size_t i = 0; i < 11; ++i) { + if (!(*c)[i].integer() || *(*c)[i].integer() < 0 || *(*c)[i].integer() > 2) return refuse("invalid_payload", "Tipps sind 0, 1 oder 2."); + t[i] = uint8_t(*(*c)[i].integer()); + } + tips.push_back(t); + } + if (!dispatch_pools_columns(manager, uint32_t(cents / 100), tips, revision, error)) { restore(); return refuse("toto_refused", error); } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"toto", "desktop"}, "Tippschein abgegeben."); + } else if (kind == "sponsor.answer") { + // payload {accept: bool}: the answer to the exclusive sponsor offer from a camp stay + const cli::Json* accept = ui_field(*payload, "accept"); + if (!accept || !std::holds_alternative(accept->value)) return refuse("invalid_payload", "accept (true/false) nötig."); + std::string result; + if (!dispatch_exclusive_sponsor(manager, std::get(accept->value), revision, result, error)) { + restore(); return refuse(error.empty() ? "sponsor_refused" : error, "Kein Sponsorangebot offen."); + } + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"sponsor", "advertising", "desktop"}, + result == "started" ? "Der Exklusiv-Sponsor beginnt sofort." : + result == "queued" ? "Der Exklusiv-Sponsor beginnt, sobald die Fläche frei ist." : + "Angebot abgelehnt."); } else if (kind == "ticket.commit") { // payload {price: Money}: the admission price, 8 to 25 euros const cli::Json* price = ui_field(*payload, "price"); diff --git a/src/modern/content/ui_contract.cpp b/src/modern/content/ui_contract.cpp index 1ecefd5..1af346b 100644 --- a/src/modern/content/ui_contract.cpp +++ b/src/modern/content/ui_contract.cpp @@ -10,6 +10,7 @@ #include "formats/executable_layout.hpp" #include "game/state.hpp" #include "game/table.hpp" +#include "modern/content/projections.hpp" #include "modern/content/world_package.hpp" #include "modern/game/almanac.hpp" #include "modern/game/desk_actions.hpp" @@ -367,6 +368,25 @@ cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& req if (kind == "session") return snapshot(request_id, std::move(m), session_data(g, c)); if (kind == "desktop") return snapshot(request_id, std::move(m), desktop_data(g, c, today)); if (kind == "camps") return snapshot(request_id, std::move(m), camps_data(g, c, std::to_string(c.state_revision))); + if (kind == "toto" || kind == "sponsor") { + // the existing projections (ui-abfragen.md), amounts as Money + J p = query_projection(g, c.manager, O{{"kind", kind}}); + auto* o = std::get_if(&p.value); + if (!o || !(*o)["ok"].value.index() || !std::get((*o)["ok"].value)) + return failure(request_id, "unavailable", "Nicht verfügbar.", c.state_revision); + o->erase("ok"); + const auto money = [](J& v) { if (v.integer()) v = ui_money(*v.integer()); }; + if (kind == "toto") { + money((*o)["stake"]), money((*o)["cost"]); + auto& last = std::get((*o)["last"].value); + money(last["paid"]), money(last["won"]); + } else { + for (const char* key : {"offer", "queued"}) + if (auto* row = std::get_if(&(*o)[key].value)) money((*row)["monthly"]); + } + (*o)["kind"] = kind; + return snapshot(request_id, std::move(m), std::move(p)); + } if (kind == "squad") { const int team = requested_team(g, c, request); if (team < 0 || !fields_players(g, team)) diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 251dda0..587ba3b 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -342,6 +342,21 @@ int main(int argc, char** argv) { } } } + // toto and the exclusive sponsor + { + const J toto = session.ui_read(O{{"kind", "toto"}}, rev); + check(s(at(toto, "messageType")) == "snapshot" && at(at(at(toto, "data"), "stake"), "minor").string(), "toto read with Money"); + const J::Array column{J(1), J(0), J(2), J(1), J(1), J(0), J(2), J(1), J(1), J(0), J(2)}; + const uint64_t before = rev; + const J done = session.ui_command(cmd("request:o1", "toto.submit", + O{{"stake", O{{"minor", "5000000"}, {"currency", "EUR"}, {"minorUnits", 2}}}, {"columns", J::Array{J(column), J(column)}}}), rev); + if (truth(at(at(toto, "data"), "open"))) + check(s(at(done, "messageType")) == "command_result" && rev == before + 1, "two toto columns submitted"); + else + check(s(at(done, "code")) == "toto_refused" && rev == before, "toto closed: refused without change"); + check(s(at(session.ui_command(cmd("request:o2", "sponsor.answer", O{{"accept", true}}), rev), "messageType")) == "error", + "no sponsor offer to answer"); + } // session.advance: three kickoffs, each one revision, the date moves on { const std::string date_before = s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")); From 140084838761094dd77f21d8b23ba99e03081474 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:32:44 +0100 Subject: [PATCH 6/8] Modern UI contract: transfer read and transfer.submit The transfer read lists the transfer list with asking fee, salary reference, offers and the own bid, and the own squad. transfer.submit lists an own player (or offers him for loan) or bids through the original's offer editor (open, set fee, salary and years, submit); the outcome tells accepted, pending or rejected. The open editor is part of the rollback. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 2 + src/modern/app/modern_session.cpp | 145 ++++++++++++++++++++++++++++- tests/modern_ui_contract_tests.cpp | 33 +++++++ 3 files changed, 179 insertions(+), 1 deletion(-) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index c660e24..53a3b25 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -34,6 +34,7 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | | `advertising` | 14 Banden (`ad:board/`), Trikot (`ad:shirt`), TV-Rechte (`ad:tv`) je mit Vertrag (Sponsor, Monatsbetrag, Restmonate, Verlängerung, Option) und den offenen Angeboten (`offer:ad--`, Sponsor, Betrag, Banden, Monate, `allowed`); die drei Budgets (Merchandising, Presse, Fanarbeit) mit Stand, Höchstbetrag, Lieferwochen; die Finanzvorschau des Originals | | `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` 0–3, sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €); das offene Angebot des Stadion-Dialogs (`quote`: Umfeld mit Preis, oder Anlage mit Zielstufe, Preis, Bauwochen und dem Trinkgeld-Bereich 6–14 %) | +| `transfer` | die Transferliste (`listing:`: Spieler, Alter, Position, Stärke, Verkäufer, Ablöseforderung, Gehaltsreferenz pro Jahr, Gehaltsforderung in %, Zahl der Angebote, eigene Listung, eigenes Gebot), der eigene Kader (gelistet oder nicht), Kontostand, Kreditrahmen | | `toto` | der Tippschein ([Toto](toto.md)): `open` (elf Spiele), Spiele, Einsatz und Kosten (`Money`), Spalten, Regeln, letzte Abrechnung | | `sponsor` | das Exklusiv-Sponsor-Angebot aus einem Trainingslager und ein vorgemerkter Vertrag (`monthly` als `Money`; `asset: null`, siehe [Trainingslager](trainingslager.md)) | | `bank` | Konto, Festgeld, Kreditrahmen, Anlagen (alles `Money`), die 12 Aktien (Kurs, Vorkurs, Bestand, bezahlt, Höchstkauf, 30 Kurse Verlauf) und die angebotenen Fonds; Kredite noch `unavailable` (folgen), der Aktientipp zieht Zufall und kommt als `quote.request` | @@ -65,6 +66,7 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt | `advertising.accept` | `offerId` | nimmt ein Angebot an wie am Schreibtisch; Fehler `unknown_offer`, `advertising_refused` | | `budget.commit` | `budgetId` (`budget:merchandise`, `budget:press`, `budget:fans`), `amount` (`Money`) | setzt ein Budget; Fehler `unknown_budget`, `invalid_amount`, `advertising_refused` (z. B. Lieferung läuft, zu wenig Geld) | | `ticket.commit` | `price` (`Money`, 8–25 €) | der Eintrittspreis; Fehler `invalid_amount`, `ticket_refused` | +| `transfer.submit` | `action: list`, `playerId`, optional `loan`; oder `action: bid`, `listingId`, `fee`, `monthlySalary` (`Money`), `years` 1–4, optional `loan` | setzt einen eigenen Spieler auf die Liste (bzw. bietet ihn zum Verleih an) oder gibt über den Angebotseditor des Originals ein Gebot ab (öffnen, Felder setzen, abschicken). `outcome`: `applied` (sofort angenommen), `offer_pending` (Antwort mit der nächsten Woche), `offer_rejected` (zu niedrig/abgelehnt). Fragt die Engine einen menschlichen Verkäufer (Abwerben), wird zurückgerollt: `decision_pending` (noch nicht unterstützt). Fehler `unknown_player`, `already_listed`, `unknown_listing`, `own_player`, `no_bid_slot`, `transfer_refused` | | `toto.submit` | `stake` (`Money` je Spalte), `columns` (bis 6 Spalten mit 11 Tipps: 1 Heim, 0 Unentschieden, 2 Auswärts) | gibt den Tippschein ab; Fehler `toto_refused` (z. B. kein offener Schein, Einsatzgrenzen, doppelte Spalte) | | `sponsor.answer` | `accept` | Antwort auf das Exklusiv-Sponsor-Angebot: beginnt sofort, wird vorgemerkt oder abgelehnt | | `quote.request` (Stadion) | `kind: periphery`, `objectId` oder `kind: facility`, `facilityId`, `increment` 1–3 | öffnet den Stadion-Dialog und holt das Angebot der Baufirma bzw. wählt Anlage und Stufen; `offer_pending`. Der Dialog bleibt offen (andere Schreibtisch-Einstellungen sind bis dahin gesperrt, `quote_open` für ein zweites Angebot) | diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index ff50d18..51c718f 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8824,7 +8824,7 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co const int manager = context.manager; if (manager < 0 || size_t(manager) >= g_.manager_teams.size() || (kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts" && - kind != "advertising" && kind != "stadium")) + kind != "advertising" && kind != "stadium" && kind != "transfer")) return modern::ui_read(g_, context, request); if (const std::string wanted = ui_text(request, "managerId"); !wanted.empty() && wanted != modern::ui_manager_id(g_, manager)) return modern::ui_error(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", revision, false); @@ -8854,6 +8854,36 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co {"rows", std::move(rows)}, {"positions", std::move(positions)}, {"depthMax", 19}, {"laneMax", 8}, {"manual", g_.manager_options.size() > size_t(manager) * 5 && g_.manager_options[size_t(manager) * 5] == 0}}); } + if (kind == "transfer") { + // the transfer list (listed players with seller, asking fee, salary reference, offers, the own + // bid), the own squad (listed or not), account and credit line + ui::TransferMarketState mk; + try { mk = ui::transfer_market_from_game(g_, revision); } catch (const std::exception&) { + return modern::ui_error(request_id, "transfer_unavailable", "Der Transfermarkt ist hier nicht verfügbar.", revision, false); + } + static constexpr const char* kPositions[4] = {"gk", "def", "mid", "fwd"}; + A listings, squad; + for (const auto& it : mk.items) { + cli::Json bid = nullptr; + if (it.own_bid) + bid = O{{"fee", modern::ui_money(it.own_bid->fee)}, {"annualSalary", modern::ui_money(it.own_bid->annual_salary)}, + {"years", int(it.own_bid->contract_years)}}; + listings.push_back(O{{"id", "listing:" + std::to_string(it.list_entry)}, {"playerId", modern::ui_player_id(g_, it.player)}, + {"name", ui::original_to_utf8(it.name)}, {"age", it.age}, {"position", kPositions[it.position & 3]}, + {"strength", it.strength}, + {"sellerId", it.seller >= 0 ? cli::Json(modern::ui_team_id(g_, it.seller)) : cli::Json(nullptr)}, + {"seller", ui::original_to_utf8(it.seller_name)}, {"askingFee", modern::ui_money(it.asking_fee)}, + {"salaryReference", modern::ui_money(it.salary_reference)}, + {"salaryDemandPercent", int(it.salary_demand_percent)}, {"offers", it.offers}, + {"ownListing", it.own_listing}, {"ownBidPending", it.own_bid_pending}, {"ownBid", std::move(bid)}}); + } + for (const auto& s : mk.squad) + squad.push_back(O{{"playerId", modern::ui_player_id(g_, s.player)}, {"name", ui::original_to_utf8(s.name)}, {"age", s.age}, + {"position", kPositions[s.position & 3]}, {"strength", s.strength}, {"listed", s.already_listed}}); + return modern::ui_snapshot(g_, context, request_id, + O{{"kind", "transfer"}, {"teamId", modern::ui_team_id(g_, team)}, {"listings", std::move(listings)}, {"squad", std::move(squad)}, + {"cash", modern::ui_money(mk.balance)}, {"creditLine", modern::ui_money(mk.credit_line)}}); + } if (kind == "stadium") { // the periphery (14 objects; the traffic access has three stages), the eight facilities with // their level, the eight stand blocks (capacity in thousands, seats, roof) and the ticket price; @@ -9081,12 +9111,15 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision const uint64_t saved_advertising_request = last_advertising_request_id_; const StadiumRuntime saved_stadium = stadium_; const uint64_t saved_stadium_scope = next_stadium_scope_; + const auto saved_offer_editor = transfer_offer_editor_; + const uint64_t saved_offer_revision = transfer_offer_revision_; const auto restore = [&] { g_ = saved_state; rand_ = saved_rand; game_ = saved_game; revision = previous; lineup_entry_manager_ = saved_entry_manager, lineup_entry_club_ = saved_entry_club; // the board stays as it was contract_quote_ = saved_quote, next_contract_quote_id_ = saved_quote_id, last_contract_request_id_ = saved_contract_request; last_advertising_request_id_ = saved_advertising_request; stadium_ = saved_stadium, next_stadium_scope_ = saved_stadium_scope; + transfer_offer_editor_ = saved_offer_editor, transfer_offer_revision_ = saved_offer_revision; }; cli::Json answer; std::string error; @@ -9492,6 +9525,116 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision revision = previous + 1; answer = modern::ui_command_result(request_id, previous, revision, {"advertising", "desktop", "bank"}, kind == "advertising.accept" ? "Werbevertrag abgeschlossen." : "Budget gesetzt."); + } else if (kind == "transfer.submit") { + // {action: "list", playerId, loan?}: an own player on the transfer list (or offered for loan) + // {action: "bid", listingId, fee, monthlySalary, years 1-4, loan?}: an offer on a listed player + // through the original's offer editor (open, set the fields, submit). A question to a human + // seller (poaching) is not supported yet and rolls back with decision_pending. + const int team = g_.manager_teams[size_t(manager)]; + if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es keine Transfers."); + const std::string action = ui_text(*payload, "action"); + const cli::Json* loan_field = ui_field(*payload, "loan"); + const bool loan = loan_field && std::holds_alternative(loan_field->value) && std::get(loan_field->value); + std::vector notices; + bool question = false; + HumanBuyerSaleHooks hooks; + hooks.notice = [&](const GameState&, const HumanBuyerSaleNotice& n) { notices.push_back(ui::original_to_utf8(n.original_message)); }; + hooks.confirm = [&](const GameState&, int, const std::string&) -> bool { question = true; throw std::runtime_error("question"); }; + const ui::TransferMarketState m = ui::transfer_market_from_game(g_, revision); + std::string feedback; + bool bid_pending = false; + try { + if (action == "list") { + const std::string id = ui_text(*payload, "playerId"); + const auto item = std::find_if(m.squad.begin(), m.squad.end(), [&](const auto& s) { return modern::ui_player_id(g_, s.player) == id; }); + if (item == m.squad.end()) return refuse("unknown_player", "Spieler nicht im Kader: " + id); + if (item->already_listed) return refuse("already_listed", "Der Spieler steht schon auf der Liste."); + ui::TransferMarketRequest r; + r.kind = ui::TransferMarketRequestKind::list_player; + r.offer_is_loan = loan; + r.manager_slot = m.manager_slot, r.runtime_club = m.runtime_club, r.revision = m.revision; + r.squad_row = item->row, r.expected_player = item->player; + r.selected_players.push_back({-1, m.roster.squad_start_offset + item->row, item->player, m.runtime_club, item->row}); + if (!dispatch_transfer_market(r, hooks, revision, error)) { restore(); return refuse("transfer_refused", error); } + feedback = loan ? "Der Spieler wird zum Verleih angeboten." : "Der Spieler steht auf der Transferliste."; + } else if (action == "bid") { + int entry = -1; + if (std::sscanf(ui_text(*payload, "listingId").c_str(), "listing:%d", &entry) != 1) return refuse("unknown_listing", "listingId fehlt."); + const auto item = std::find_if(m.items.begin(), m.items.end(), [&](const auto& it) { return it.list_entry == entry; }); + if (item == m.items.end()) return refuse("unknown_listing", "Dieser Listenplatz ist nicht (mehr) belegt."); + if (item->own_listing) return refuse("own_player", "Das ist ein eigener Spieler."); + const auto money_of = [&](const char* key) -> int64_t { + const cli::Json* v = ui_field(*payload, key); + try { return v ? std::stoll(ui_text(*v, "minor")) : -1; } catch (const std::exception&) { return -1; } + }; + const int64_t fee = money_of("fee"), salary = money_of("monthlySalary"); + const cli::Json* years = ui_field(*payload, "years"); + if (fee < 0 || fee % 100 || salary < 0 || salary % 100 || !years || !years->integer() || *years->integer() < 1 || *years->integer() > 4) + return refuse("invalid_payload", "fee, monthlySalary (Money, ganze Euro) und years 1-4 nötig."); + ui::TransferMarketRequest open; + open.kind = ui::TransferMarketRequestKind::open_offer; + open.offer_is_loan = loan; + open.manager_slot = m.manager_slot, open.runtime_club = m.runtime_club, open.revision = m.revision; + if (item->own_bid) open.bid = *item->own_bid; + open.bid.manager = m.manager_slot, open.bid.list_entry = item->list_entry, open.bid.player = item->player; + open.bid.source_slot = item->source_slot; + open.selected_players.push_back({item->list_entry, item->source_slot, item->player, item->seller, -1}); + auto opened = open_transfer_offer(open, revision, error); + if (!opened) { restore(); return refuse("transfer_refused", error); } + ui::OutgoingTransferEditorState e = opened->editor; + if (!e.editable) { restore(); return refuse("no_bid_slot", "Für diesen Spieler ist kein Angebot möglich."); } + const auto edit = [&](ui::OutgoingTransferRequestKind k, ui::OutgoingTransferField field, uint32_t value) + -> std::optional { + ui::OutgoingTransferRequest r; + r.kind = k; + r.identity = {e.manager_slot, e.runtime_club, e.revision, e.list_entry, e.source_slot, e.player, e.seller, e.bid_slot}; + r.field = field, r.value = value, r.quote_loan = e.quote_loan; + r.fee = e.fee, r.monthly_salary = e.monthly_salary, r.duration_years = e.duration_years, r.bonuses = e.bonuses; + r.quoted_fee = e.panel.quoted_fee, r.quoted_monthly_salary = e.panel.quoted_monthly_salary, r.quoted_years = e.panel.quoted_years; + auto d = dispatch_transfer_offer(r, hooks, revision, error); + if (d) e = d->editor; + return d; + }; + // the screen stores the edited value and asks for a fresh quote, one field at a time + bool ok = true; + if (ok && e.fee != uint32_t(fee / 100)) { e.fee = uint32_t(fee / 100); ok = bool(edit(ui::OutgoingTransferRequestKind::quote_change, ui::OutgoingTransferField::fee, e.fee)); } + if (ok && e.monthly_salary != uint32_t(salary / 100)) { + e.monthly_salary = uint32_t(salary / 100); + ok = bool(edit(ui::OutgoingTransferRequestKind::quote_change, ui::OutgoingTransferField::monthly_salary, e.monthly_salary)); + } + if (ok && e.duration_years != uint8_t(*years->integer())) { + e.duration_years = uint8_t(*years->integer()); + ok = bool(edit(ui::OutgoingTransferRequestKind::quote_change, ui::OutgoingTransferField::duration_years, e.duration_years)); + } + std::optional sent; + if (ok) sent = edit(ui::OutgoingTransferRequestKind::submit, ui::OutgoingTransferField::fee, e.fee); + if (!sent) { restore(); return refuse("transfer_refused", error); } + const TransferActionStatus status = sent->action.status; + bid_pending = status == TransferActionStatus::pending; + if (!e.closed) edit(ui::OutgoingTransferRequestKind::cancel, ui::OutgoingTransferField::fee, e.fee); // a low offer keeps it open + feedback = status == TransferActionStatus::accepted ? "Angenommen: Der Spieler wechselt zu Ihrem Verein." + : status == TransferActionStatus::pending ? "Angebot abgegeben; die Antwort kommt mit der nächsten Woche." + : status == TransferActionStatus::offer_too_low ? "Das Angebot ist zu niedrig." + : "Das Angebot wurde abgelehnt."; + if (status != TransferActionStatus::accepted && status != TransferActionStatus::pending) { + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"transfer"}, feedback); + std::get(answer.value)["outcome"] = "offer_rejected"; + } + } else { + return refuse("invalid_payload", "action ist list oder bid."); + } + } catch (const std::exception& ex) { + restore(); + if (question) return refuse("decision_pending", "Ein menschlicher Verkäufer müsste gefragt werden (noch nicht unterstützt)."); + return refuse("transfer_refused", ex.what()); + } + for (const auto& n : notices) feedback += (feedback.empty() ? "" : " ") + n; + if (std::holds_alternative(answer.value)) { + revision = previous + 1; + answer = modern::ui_command_result(request_id, previous, revision, {"transfer", "squad", "desktop"}, feedback); + if (bid_pending) std::get(answer.value)["outcome"] = "offer_pending"; + } } else if (kind == "toto.submit") { // payload {stake: Money per column, columns: [[11 tips: 1 home, 0 draw, 2 away], ... up to 6]} const cli::Json* stake = ui_field(*payload, "stake"); diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 587ba3b..34aa7fd 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -342,6 +342,39 @@ int main(int argc, char** argv) { } } } + // transfers: list an own player, bid on a listed one (asking fee and salary reference) + { + const J market = session.ui_read(O{{"kind", "transfer"}}, rev); + const auto* listings = at(at(market, "data"), "listings").array(); + const auto* squad = at(at(market, "data"), "squad").array(); + check(s(at(market, "messageType")) == "snapshot" && listings && squad && !squad->empty(), "transfer read"); + const uint64_t before = rev; + if (squad && squad->size() > 15) { + const std::string seller = s(at(squad->back(), "playerId")); + const J listed = session.ui_command(cmd("request:t9", "transfer.submit", O{{"action", "list"}, {"playerId", seller}}), rev); + if (s(at(listed, "messageType")) != "command_result") std::fprintf(stderr, "list: %s\n", cli::dump_json(listed).c_str()); + check(s(at(listed, "messageType")) == "command_result" && rev == before + 1, "own player listed"); + } + std::string listing; + J fee, salary; + if (listings) + for (const auto& l : *listings) + if (listing.empty() && !truth(at(l, "ownListing")) && !truth(at(l, "ownBidPending"))) + listing = s(at(l, "id")), fee = at(l, "askingFee"), salary = at(l, "salaryReference"); + if (!listing.empty()) { + // the salary reference is annual in the market row; the offer takes a monthly salary + const int64_t monthly = std::stoll(s(at(salary, "minor"))) / 12 / 100 * 100; + const uint64_t b2 = rev; + const J bid = session.ui_command(cmd("request:t10", "transfer.submit", + O{{"action", "bid"}, {"listingId", listing}, {"fee", fee}, + {"monthlySalary", O{{"minor", std::to_string(monthly)}, {"currency", "EUR"}, {"minorUnits", 2}}}, {"years", 2}}), rev); + std::printf("(bid on %s: %s)\n", listing.c_str(), cli::dump_json(bid).substr(0, 260).c_str()); + check((s(at(bid, "messageType")) == "command_result" && rev == b2 + 1) || + (s(at(bid, "messageType")) == "error" && rev == b2), "bid answered or refused cleanly"); + } + check(s(at(session.ui_command(cmd("request:t11", "transfer.submit", O{{"action", "bid"}, {"listingId", "listing:999"}}), rev), "code")) == + "unknown_listing", "unknown listing refused"); + } // toto and the exclusive sponsor { const J toto = session.ui_read(O{{"kind", "toto"}}, rev); From fda4b72967f8ed178629d4c103fe5bc9f9ed26e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:37:37 +0100 Subject: [PATCH 7/8] Modern UI: the live ticker replays the last kickoff's matches ModernSession::read_live answers the ticker's fixture and frame queries with the engine's recording of the last session.advance: the matches of human managers with their owners, frames in minute order (kickoff, every event, half time, the end) with score, chances, cards and players on the pitch, the event lines, and the day's other matches as the conference. Co-Authored-By: Claude Opus 5.5 --- docs/new_engine/ui-anbindung.md | 10 +++ src/modern/app/modern_session.cpp | 25 ++++++ src/modern/app/modern_session.hpp | 6 ++ src/modern/content/statistics.cpp | 140 +++++++++++++++++++++++++++++ src/modern/content/statistics.hpp | 7 ++ tests/modern_ui_contract_tests.cpp | 25 ++++++ 6 files changed, 213 insertions(+) diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 53a3b25..79ce43a 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -49,6 +49,16 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt - `ModernSession::read_statistics_screen`: der Statistikbildschirm mit den Filtern seiner Demo (`section` 0–8, `category`, `country`, `winner_country`, `absolute`, `curves`), `fictional: false`. Aus dem Almanach: 3 Ewige Tabelle (je Land die erste Liga, 5 die eigene), 4 WM-Statistiken (Sieger mit Finale, Torschützen, Länder-Historie), 6 Serien und Rekorde (eigene Liga), 7 Sieger (national, Europapokale, Hallen-Masters), 8 Minuten-Statistik (eigener Verein). Aus den Aufzeichnungen des Originals: 1 Transferhistorie (Käufe, Verkäufe, Leihen des Managers mit Ablöse) und 2 Analytics: die sechs Kurven des Originals mit ihren Namen, `values` je erfasster Woche und `absoluteMin`/`absoluteMax`; **die UI skaliert selbst** (`points` bleibt leer, die Demo lieferte Bildschirmkoordinaten). Noch ohne Aufzeichnung (`available: false`, `reason: not_recorded`): 0 Möglichkeiten, 5 Saisonfinanzen (das Original speichert nur die laufende Saison), bei 4 Gruppen und Finalrunde. - `ModernSession::read_statistics`: `competitions`, `winners`, `player_stats` ([Statistik](statistik.md)) für eine eigene Spieler- und Siegerstatistik. +## Live-Ticker (ohne Umschlag) + +`ModernSession::read_live` (für `DataSource::read_live`, Abfragen wie die Demo: `{kind: "fixture"}`, `{kind: "frame", sequence}`, optional `revision`, `fixture_id`). Die Engine rechnet einen Spieltag beim Anstoß im Ganzen; der Ticker spielt die **Aufzeichnung** der Spiele des letzten `session.advance` ab (`source: "engine-recording"`, Format `openbmh-live-fixture@1` der Demo): + +- `matches`: die Spiele mit menschlichem Manager (höchstens vier), `owners`: die Manager mit Team und `match_id` (`view` ist `null`; die Aufstellung kommt aus dem `lineup`-Read). +- `frames` in Minutenfolge: Anpfiff, jedes Ereignis (Tor, Chance, Karten, Verletzung, Wechsel, Elfmeter), Halbzeit, Wiederanpfiff, Abpfiff; je Spiel Stand, Chancen, Gelb, Rot, Elfmeter, Spieler auf dem Feld. `events` (fortlaufend) mit Überschrift und Satz, Spieler, Seite, Stand. +- `conference`: die übrigen Spiele des Tages im Almanach-Format. +- Noch leer: `standings` (Live-Tabelle). Fehler: `live_unavailable` (noch kein Anstoß), `live_no_human_match`, `stale_live_revision`, `stale_live_fixture`, `invalid_live_sequence`. +- Eingriffe während des Spiels (Wechsel, Taktik) brauchen einen schrittweisen Anstoß und folgen mit Lieferung E. + ## Commands `ModernSession::ui_command(request, revision)`. Ein Command (`messageType: command`) braucht `requestId`, `expectedRevision` (gleich der aktuellen Revision), `owner.managerId` (der Manager am Schreibtisch), `kind` und `payload`; `careerId` wird geprüft, wenn angegeben. Antwort: `command_result` mit `previousRevision`, `newRevision` (ein Schritt je Command), `outcome`, `changedReadKinds`, oder `error`. diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 51c718f..63894e9 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -8752,6 +8752,29 @@ std::string ui_text(const cli::Json& j, const char* key) { } // namespace +cli::Json ModernSession::read_live(const cli::Json& request) const { + using O = cli::Json::Object; + const auto fail = [](const char* e) { return cli::Json(O{{"ok", false}, {"error", e}}); }; + if (!request.object()) return fail("invalid_live_query"); + for (const auto& [key, value] : *request.object()) + if (key != "kind" && key != "revision" && key != "sequence" && key != "fixture_id") return fail("invalid_live_query"); + if (!ui_last_advance_) return fail("live_unavailable"); + if (const cli::Json* r = ui_field(request, "revision"); r && (!r->integer() || uint64_t(*r->integer()) != ui_last_advance_revision_)) + return fail("stale_live_revision"); + cli::Json fixture = modern::live_fixture(g_, ui_last_advance_->first, ui_last_advance_->second, ui_last_advance_revision_); + const auto* f = std::get_if(&fixture.value); + if (!f || !std::holds_alternative(f->at("ok").value) || !std::get(f->at("ok").value)) return fixture; + if (const cli::Json* id = ui_field(request, "fixture_id"); id && (!id->string() || *id->string() != *f->at("fixture_id").string())) + return fail("stale_live_fixture"); + const std::string kind = ui_text(request, "kind").empty() ? "fixture" : ui_text(request, "kind"); + if (kind == "fixture") return ui_field(request, "sequence") ? fail("invalid_live_query") : fixture; + if (kind != "frame") return fail("invalid_live_query"); + const cli::Json* seq = ui_field(request, "sequence"); + const auto& frames = *f->at("frames").array(); + if (!seq || !seq->integer() || *seq->integer() < 0 || size_t(*seq->integer()) >= frames.size()) return fail("invalid_live_sequence"); + return O{{"ok", true}, {"fixture_id", f->at("fixture_id")}, {"frame", frames[size_t(*seq->integer())]}}; +} + cli::Json ModernSession::read_statistics_screen(const cli::Json& request) const { using O = cli::Json::Object; using A = cli::Json::Array; @@ -9337,6 +9360,8 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision } modern::ensure_ui_identities(g_); revision = previous + 1; + ui_last_advance_ = std::make_pair(saved_state.date, g_.date); // what read_live replays + ui_last_advance_revision_ = revision; const char* what = r.kind == TurnDeskKind::SeasonEndDesk ? "Saisonende." : r.kind == TurnDeskKind::CareerComplete ? "Die Karriere ist zu Ende." : "Weiter zum nächsten Termin."; answer = modern::ui_command_result(request_id, previous, revision, diff --git a/src/modern/app/modern_session.hpp b/src/modern/app/modern_session.hpp index c645b18..f59d774 100644 --- a/src/modern/app/modern_session.hpp +++ b/src/modern/app/modern_session.hpp @@ -834,6 +834,9 @@ public: // The almanac screen (index, calendar, day, match; docs/new_engine/ui-anbindung.md). Read-only. cli::Json read_almanac(const cli::Json& request) const { return query_almanac(g_, request); } // The statistics screen for the manager at the desk (docs/new_engine/ui-anbindung.md). Read-only. + // The live ticker (DataSource::read_live): {kind: "fixture"} the recorded matches of the last + // session.advance, {kind: "frame", sequence} one of its frames; revision/fixture_id as in the demo. + cli::Json read_live(const cli::Json& request) const; // Sections 1 (transfer history) and 2 (the six curves) come from the original's own records. cli::Json read_statistics_screen(const cli::Json& request) const; // The read queries of the new interface (docs/new_engine/ui-abfragen.md): status, leagues, @@ -1001,6 +1004,9 @@ private: // ui_command: answers by requestId (the command as JSON, the answer) for repeated commands, // the last 64 in this process; after a restart expectedRevision prevents a second booking. std::map> ui_answers_; + // the day counters around the last session.advance and the revision after it (read_live) + std::optional> ui_last_advance_; + uint64_t ui_last_advance_revision_ = 0; std::vector ui_answer_order_; std::filesystem::path data_directory_; diff --git a/src/modern/content/statistics.cpp b/src/modern/content/statistics.cpp index d0ca9f4..5f3f335 100644 --- a/src/modern/content/statistics.cpp +++ b/src/modern/content/statistics.cpp @@ -747,4 +747,144 @@ cli::Json query_statistics_screen(const ModernState& g, int manager, const cli:: } } + +// --- the live ticker of the Modern UI: the recorded matches of the last kickoff --------------- + +namespace { + +// The ticker's lines for an event of the almanac (German, as the interface's demo). +std::pair ticker_text(const AlmanacSeason& s, const AlmanacMatch& m, const AlmanacEvent& e, + int home, int away) { + const std::string team = s.clubs[e.side ? m.away : m.home].name; + const std::string who = e.player != kAlmanacNone && e.player < s.players.size() ? player_name(s.players[e.player]) : team; + const std::string other = e.other != kAlmanacNone && e.other < s.players.size() ? player_name(s.players[e.other]) : std::string{}; + const std::string score = std::to_string(home) + ":" + std::to_string(away); + switch (e.kind) { + case AlmanacEventKind::Goal: + return {"Tor für " + team, who + " trifft zum " + score + "." + (other.empty() ? "" : " Vorlage: " + other + ".")}; + case AlmanacEventKind::Miss: return {"Chance für " + team, who + " vergibt."}; + case AlmanacEventKind::YellowCard: return {"Gelbe Karte", who + " (" + team + ") sieht Gelb."}; + case AlmanacEventKind::SecondYellow: return {"Gelb-Rot", who + " (" + team + ") muss vom Platz."}; + case AlmanacEventKind::RedCard: return {"Rote Karte", who + " (" + team + ") fliegt vom Platz."}; + case AlmanacEventKind::Injury: return {"Verletzung", who + " (" + team + ") ist verletzt."}; + case AlmanacEventKind::Substitution: + return {"Wechsel bei " + team, who + (other.empty() ? " kommt ins Spiel." : " kommt für " + other + ".")}; + case AlmanacEventKind::ShootoutKick: + return {"Elfmeterschießen", who + (e.detail ? " verwandelt." : " verschießt.")}; + } + return {"", ""}; +} + +const char* event_kind(AlmanacEventKind k) { + static constexpr const char* kKinds[8] = {"goal", "yellow", "red", "second_yellow", "injury", "substitution", "shootout", "miss"}; + return kKinds[size_t(k) & 7]; +} + +} // namespace + +cli::Json live_fixture(const ModernState& g, uint32_t after_date, uint32_t until_date, uint64_t revision) { + // the matches of the last kickoff (dates after_date <= d < until_date) from the almanac: the + // ones with a human manager are the ticker's matches (at most four), all others the conference + struct Ref { const AlmanacSeason* season; size_t index; }; + const auto seasons = seasons_of(g); + std::vector human, others; + for (const auto& s : seasons) + for (size_t i = 0; i < s.matches.size(); ++i) { + const AlmanacMatch& m = s.matches[i]; + if (m.date < after_date || m.date >= until_date) continue; // played from the desk day on, before the next desk + ((m.home_manager >= 0 || m.away_manager >= 0) && human.size() < 4 ? human : others).push_back({&s, i}); + } + if (human.empty()) return O{{"ok", false}, {"error", "live_no_human_match"}}; + A owners, matches, conference; + std::map owner_match; + for (const Ref& r : human) { + const AlmanacSeason& s = *r.season; + const AlmanacMatch& m = s.matches[r.index]; + const std::string id = match_id(s, r.index); + A match_owners; + for (int side = 0; side < 2; ++side) { + const int8_t mi = side ? m.away_manager : m.home_manager; + if (mi < 0 || size_t(mi) >= s.managers.size()) continue; + const AlmanacManager& a = s.managers[size_t(mi)]; + std::string mid = a.index >= 0 && size_t(a.index) < g.manager_ids.size() ? g.manager_ids[size_t(a.index)] : std::string{}; + if (mid.empty()) mid = "manager:slot-" + std::to_string(a.index); + if (owner_match.count(mid)) continue; + owner_match[mid] = id; + match_owners.push_back(mid); + const AlmanacClub& c = s.clubs[side ? m.away : m.home]; + const size_t rec = size_t(std::max(0, a.index)) * 0xb0c + 0x221; + owners.push_back(O{{"id", mid}, {"portrait", rec < g.manager_records.size() ? int(g.manager_records[rec]) : 0}, + {"name", a.name}, {"team", O{{"id", c.id}, {"name", c.name}, {"role", c.id.starts_with("nt:") ? "national" : "club"}}}, + {"match_id", id}, {"view", nullptr}}); + } + const Competition c = competition_of(g, s, m); + matches.push_back(O{{"id", id}, {"home", O{{"id", s.clubs[m.home].id}, {"name", s.clubs[m.home].name}}}, + {"away", O{{"id", s.clubs[m.away].id}, {"name", s.clubs[m.away].name}}}, + {"owners", std::move(match_owners)}, {"competition", c.name}}); + } + for (const Ref& r : others) conference.push_back(almanac_match(g, *r.season, r.index)); + + // the frames: kickoff, every event of a ticker match in minute order, half time, the end + struct Moment { int minute; int order; const Ref* ref; const AlmanacEvent* event; const char* phase; }; + std::vector moments; + bool extra = false, shootout = false; + for (const Ref& r : human) { + const AlmanacMatch& m = r.season->matches[r.index]; + extra |= m.decided >= 1, shootout |= m.decided == 2; + for (const auto& e : m.events) moments.push_back({e.minute, 1, &r, &e, nullptr}); + } + moments.push_back({0, 0, nullptr, nullptr, "kickoff"}); + moments.push_back({45, 2, nullptr, nullptr, "interval"}); + moments.push_back({46, 0, nullptr, nullptr, "restart"}); + moments.push_back({extra ? 120 : 90, 3, nullptr, nullptr, shootout ? "shootout_end" : "fulltime"}); + std::stable_sort(moments.begin(), moments.end(), [](const Moment& a, const Moment& b) { + return a.minute != b.minute ? a.minute < b.minute : a.order < b.order; + }); + struct Tally { int score[2] = {0, 0}, chances[2] = {0, 0}, yellow[2] = {0, 0}, red[2] = {0, 0}, shootout[2] = {0, 0}; }; + std::vector tally(human.size()); + A frames, events; + for (const Moment& mo : moments) { + if (mo.event) { + const size_t k = size_t(mo.ref - human.data()); + const AlmanacSeason& s = *mo.ref->season; + const AlmanacMatch& m = s.matches[mo.ref->index]; + const AlmanacEvent& e = *mo.event; + Tally& t = tally[k]; + const size_t side = e.side ? 1 : 0; + if (e.kind == AlmanacEventKind::Goal) ++t.score[side], ++t.chances[side]; + if (e.kind == AlmanacEventKind::Miss) ++t.chances[side]; + if (e.kind == AlmanacEventKind::YellowCard) ++t.yellow[side]; + if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++t.red[side]; + if (e.kind == AlmanacEventKind::ShootoutKick && e.detail) ++t.shootout[side]; + const auto [headline, body] = ticker_text(s, m, e, t.score[0], t.score[1]); + const std::string mid = match_id(s, mo.ref->index); + events.push_back(O{{"id", mid + ":event:" + std::to_string(events.size())}, {"sequence", int64_t(frames.size())}, + {"match_id", mid}, {"minute", mo.minute}, {"kind", event_kind(e.kind)}, {"headline", headline}, + {"body", body}, {"score", A{J(t.score[0]), J(t.score[1])}}, {"side", side ? "away" : "home"}, + {"player", almanac_person(s, e.player)}, {"other", almanac_person(s, e.other)}}); + } + A scores; + for (size_t k = 0; k < human.size(); ++k) { + const Tally& t = tally[k]; + scores.push_back(O{{"match_id", match_id(*human[k].season, human[k].index)}, + {"score", A{J(t.score[0]), J(t.score[1])}}, {"chances", A{J(t.chances[0]), J(t.chances[1])}}, + {"yellow", A{J(t.yellow[0]), J(t.yellow[1])}}, {"red", A{J(t.red[0]), J(t.red[1])}}, + {"shootout", A{J(t.shootout[0]), J(t.shootout[1])}}, + {"players", A{J(11 - t.red[0]), J(11 - t.red[1])}}, {"standings", A{}}}); + } + const char* phase = mo.phase ? mo.phase : mo.minute <= 45 ? "first_half" : mo.minute <= 90 ? "second_half" + : mo.minute <= 120 ? "extra_time" : "shootout"; + frames.push_back(O{{"sequence", int64_t(frames.size())}, {"minute", mo.minute}, {"phase", phase}, + {"matches", std::move(scores)}, {"events", events}}); + } + const AlmanacSeason& first = *human.front().season; + return O{{"ok", true}, {"schema", "openbmh-live-fixture@1"}, {"source", "engine-recording"}, + {"fixture_id", "live:" + std::to_string(first.start_year) + "-" + std::to_string(human.front().index)}, + {"source_revision", int64_t(revision)}, {"date", iso_date(first.matches[human.front().index].date, first.display_start_year)}, + {"role", owners.empty() ? "club" : std::get(std::get(owners.front().value).at("team").value).at("role")}, + {"surface", "outdoor"}, {"duration", extra ? 120 : 90}, {"field_count", 11}, {"owners", std::move(owners)}, + {"matches", std::move(matches)}, {"frames", std::move(frames)}, {"conference", std::move(conference)}, + {"notice", "Aufzeichnung der Engine: die Spiele des letzten Anstoßes"}}; +} + } // namespace bmh::modern diff --git a/src/modern/content/statistics.hpp b/src/modern/content/statistics.hpp index 5485fda..bcc6aeb 100644 --- a/src/modern/content/statistics.hpp +++ b/src/modern/content/statistics.hpp @@ -35,4 +35,11 @@ cli::Json query_almanac(const ModernState& g, const cli::Json& request); // not_recorded (title chances, transfers, weekly curves, season finances). cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::Json& request); +// The live ticker (DataSource::read_live): the matches recorded between two day counters (the last +// kickoff) in the fixture form of the interface: the matches of human managers (at most four) +// with their owners, frames in minute order (kickoff, every event, half time, the end) with +// score, chances, cards and players per match, the event lines, and the other matches of the +// day as the conference. source: "engine-recording". +cli::Json live_fixture(const ModernState& g, uint32_t after_date, uint32_t until_date, uint64_t revision); + } // namespace bmh::modern diff --git a/tests/modern_ui_contract_tests.cpp b/tests/modern_ui_contract_tests.cpp index 34aa7fd..a2a86d0 100644 --- a/tests/modern_ui_contract_tests.cpp +++ b/tests/modern_ui_contract_tests.cpp @@ -424,6 +424,31 @@ int main(int argc, char** argv) { std::printf("(date now %s)\n", s(at(at(session.ui_read(O{{"kind", "desktop"}}, rev), "meta"), "date")).c_str()); std::printf("(%d contract decisions answered)\n", decisions); } + // the live ticker: advance until a kickoff played a match of the human manager, then its recording + { + J fixture; + for (int k = 0; k < 12; ++k) { + fixture = session.read_live(O{{"kind", "fixture"}}); + if (truth(at(fixture, "ok"))) break; + check(s(at(fixture, "error")) == "live_no_human_match", "no human match: said so"); + session.ui_command(cmd("request:lv" + std::to_string(k), "session.advance", O{}), rev); + } + const auto* frames = at(fixture, "frames").array(); + const auto* matches = at(fixture, "matches").array(); + check(truth(at(fixture, "ok")) && s(at(fixture, "source")) == "engine-recording" && frames && frames->size() >= 4 && + matches && !matches->empty() && at(fixture, "owners").array() && !at(fixture, "owners").array()->empty(), + "live fixture of the last kickoff"); + if (frames && frames->size() >= 4) { + const J& last = frames->back(); + const J one = session.read_live(O{{"kind", "frame"}, {"sequence", int64_t(frames->size() - 1)}}); + check(truth(at(one, "ok")) && cli::dump_json(at(one, "frame")) == cli::dump_json(last), "one frame by sequence"); + // the last frame's score is the recorded result of the match + const J m = at(at(last, "matches").array()->front(), "score"); + std::printf("(live: %zu frames, %zu matches, conference %zu, final %s)\n", frames->size(), matches->size(), + at(fixture, "conference").array() ? at(fixture, "conference").array()->size() : 0, cli::dump_json(m).c_str()); + } + check(s(at(session.read_live(O{{"kind", "frame"}, {"sequence", 99999}}), "error")) == "invalid_live_sequence", "bad sequence"); + } // almanac view after the kickoffs: index, calendar, day, match { const J index = session.read_almanac(O{{"kind", "index"}}); From 0046ab90d069070e5eb497293abe0cb9d1c9dde2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 27 Oct 2026 09:53:31 +0100 Subject: [PATCH 8/8] Modern: the traffic access has four stages The Modern interface shows four stages for the traffic access, the original has three. A Modern world (WorldLayout::traffic_stages = 4) keeps the condition byte in steps of 64 (64, 128, 192, 255) and offers a build up to stage 3; every stage weighs as one original stage. New careers convert the original start table, older Modern saves are converted on load (traffic_scale). Classic data keeps three stages; the Classic equivalence is unchanged. Also: the live ticker takes the matches from the desk day on. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/modern-engine.yml | 4 +-- CMakeLists.txt | 3 ++ docs/new_engine/balance.md | 9 +++++ docs/new_engine/ui-anbindung.md | 2 +- src/cli/console/windows_money.cpp | 6 +++- src/game/world_layout.hpp | 3 ++ src/modern/app/modern_session.cpp | 14 ++++++-- src/modern/app/modern_session.hpp | 1 + src/modern/content/world_expand.cpp | 1 + src/modern/content/world_save.cpp | 4 ++- src/modern/game/balance_plan.cpp | 3 +- src/modern/game/career.cpp | 3 +- src/modern/game/matchday_setup.cpp | 5 +-- src/modern/game/modern_state.hpp | 3 ++ src/modern/game/month.cpp | 3 +- src/modern/game/traffic.hpp | 51 +++++++++++++++++++++++++++++ src/modern/game/weekly.cpp | 7 ++-- tests/modern_traffic_tests.cpp | 48 +++++++++++++++++++++++++++ 18 files changed, 154 insertions(+), 16 deletions(-) create mode 100644 src/modern/game/traffic.hpp create mode 100644 tests/modern_traffic_tests.cpp diff --git a/.github/workflows/modern-engine.yml b/.github/workflows/modern-engine.yml index 39d0ef0..04a2915 100644 --- a/.github/workflows/modern-engine.yml +++ b/.github/workflows/modern-engine.yml @@ -54,9 +54,9 @@ jobs: - name: Configure without game data run: cmake -S . -B build-engine -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=OFF -DBMH_DATA= - name: Compile the Modern console, simulator and engine tests - run: cmake --build build-engine --target openbmh_modern_cli modern_season_sim modern_world_info modern_camp_tests modern_almanac_tests modern_toto_tests modern_calendar_tests --parallel 2 + run: cmake --build build-engine --target openbmh_modern_cli modern_season_sim modern_world_info modern_camp_tests modern_almanac_tests modern_toto_tests modern_calendar_tests modern_traffic_tests --parallel 2 - name: Run the data-free Modern engine tests - run: ctest --test-dir build-engine -R "^modern_(camp|almanac|toto|calendar)_tests$" --output-on-failure --output-junit modern-engine-results.xml + run: ctest --test-dir build-engine -R "^modern_(camp|almanac|toto|calendar|traffic)_tests$" --output-on-failure --output-junit modern-engine-results.xml - name: Upload test report if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/CMakeLists.txt b/CMakeLists.txt index 067f254..760dccd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1220,6 +1220,9 @@ add_executable(modern_toto_tests tests/modern_toto_tests.cpp) target_link_libraries(modern_toto_tests PRIVATE bmh_season_modern) add_test(NAME modern_toto_tests COMMAND modern_toto_tests) +add_executable(modern_traffic_tests tests/modern_traffic_tests.cpp) +target_link_libraries(modern_traffic_tests PRIVATE bmh_season_modern) +add_test(NAME modern_traffic_tests COMMAND modern_traffic_tests) add_executable(modern_calendar_tests tests/modern_calendar_tests.cpp) target_link_libraries(modern_calendar_tests PRIVATE bmh_season_modern) add_test(NAME modern_calendar_tests COMMAND modern_calendar_tests) diff --git a/docs/new_engine/balance.md b/docs/new_engine/balance.md index a1bba42..67f4561 100644 --- a/docs/new_engine/balance.md +++ b/docs/new_engine/balance.md @@ -115,6 +115,15 @@ Ergebnis: keine Prüfverletzung, keine Fehler bei Verträgen, Werbung und Lagern Keine Regeländerung nötig. +## Stadion: Verkehrsanbindung mit vier Stufen + +Die Modern-Oberfläche zeigt für die Verkehrsanbindung vier Ausbaustufen, das Original hat drei (Zustandsbyte in Schritten von 0x55: 85, 170, 255; Angebot unter 171). In einer Modern-Welt (`WorldLayout::traffic_stages = 4`) gilt deshalb (`src/modern/game/traffic.hpp`, 27.10.2026): + +- Schritte von 64: Stufe 1–4 bei 64, 128, 192, 255; ein Ausbau wird bis Stufe 3 angeboten. Jeder Ausbau kostet wie im Original (Grundpreis 2,5 Mio. €, 45 Tage). +- Jede Stufe wirkt wie eine Original-Stufe (Einnahmen je Zuschauer, Monatseinnahmen, Zuschauerstufe von 25.000); die vierte Stufe ist ein zusätzlicher Schritt. +- Neue Karrieren starten mit der Stufe der Original-Starttabelle; ältere Modern-Spielstände werden beim Laden in die neue Skala umgerechnet (`traffic_scale` in `state/modern.json`). +- Mit Classic-Daten bleibt es bei drei Stufen (Gleichheitstest unverändert). Test: `modern_traffic_tests`. + ## Offen - Langläufe mit einem aktiven Manager (Transfers, Aufstellung), sobald die Konsole oder die UI das automatisiert erlaubt. - Spieler in den Pools (vereinslos) aus dem Datensatz behalten ihre Rohwerte; der Datensatz 1.3 hat keine. diff --git a/docs/new_engine/ui-anbindung.md b/docs/new_engine/ui-anbindung.md index 79ce43a..5cb1371 100644 --- a/docs/new_engine/ui-anbindung.md +++ b/docs/new_engine/ui-anbindung.md @@ -33,7 +33,7 @@ Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nicht | `training` | Bälle je Spielertyp und Trainingsbereich (1–3) mit den Grenzen, je Spieler Intensität und Schwerpunkt, ob das Training eingerichtet ist, Automatik-Bits | | `contracts` | je Spieler Restlaufzeit, Monatsgehalt, Versicherung, Prämien; das offene Angebot (`quote`: ID, Spieler, Monatsforderung für 1–4 Jahre, Höchstgehalt 200.000 €) | | `advertising` | 14 Banden (`ad:board/`), Trikot (`ad:shirt`), TV-Rechte (`ad:tv`) je mit Vertrag (Sponsor, Monatsbetrag, Restmonate, Verlängerung, Option) und den offenen Angeboten (`offer:ad--`, Sponsor, Betrag, Banden, Monate, `allowed`); die drei Budgets (Merchandising, Presse, Fanarbeit) mit Stand, Höchstbetrag, Lieferwochen; die Finanzvorschau des Originals | -| `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` 0–3, sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €); das offene Angebot des Stadion-Dialogs (`quote`: Umfeld mit Preis, oder Anlage mit Zielstufe, Preis, Bauwochen und dem Trinkgeld-Bereich 6–14 %) | +| `stadium` | Umfeld (14 Objekte mit Namen und Bautagen; Verkehrsanbindung mit `stage` und `maxStage`: Classic 3, Modern-Welt 4; sonst `built`), die acht Anlagen (Stufe, Höchststufe, Bauwochen, ob ausbaubar), die acht Tribünenblöcke (Plätze, Höchstplätze, Sitzplätze, Dach, Bauwochen, Plätze nach dem Bau), Eintrittspreis (8–25 €); das offene Angebot des Stadion-Dialogs (`quote`: Umfeld mit Preis, oder Anlage mit Zielstufe, Preis, Bauwochen und dem Trinkgeld-Bereich 6–14 %) | | `transfer` | die Transferliste (`listing:`: Spieler, Alter, Position, Stärke, Verkäufer, Ablöseforderung, Gehaltsreferenz pro Jahr, Gehaltsforderung in %, Zahl der Angebote, eigene Listung, eigenes Gebot), der eigene Kader (gelistet oder nicht), Kontostand, Kreditrahmen | | `toto` | der Tippschein ([Toto](toto.md)): `open` (elf Spiele), Spiele, Einsatz und Kosten (`Money`), Spalten, Regeln, letzte Abrechnung | | `sponsor` | das Exklusiv-Sponsor-Angebot aus einem Trainingslager und ein vorgemerkter Vertrag (`monthly` als `Money`; `asset: null`, siehe [Trainingslager](trainingslager.md)) | diff --git a/src/cli/console/windows_money.cpp b/src/cli/console/windows_money.cpp index 8bf71dd..bbad7e0 100644 --- a/src/cli/console/windows_money.cpp +++ b/src/cli/console/windows_money.cpp @@ -12,6 +12,7 @@ #include #include "app/window_actions.hpp" +#include "game/world_layout.hpp" #include "cli/console/console.hpp" #include "cli/console/detail.hpp" #include "game/bank_credit.hpp" @@ -324,7 +325,10 @@ void Console::register_money_commands() { // condition byte to the next multiple of 85 (85, 170, 255; ageing lowers it), and an // offer exists below 171. The other objects are built once. std::string state = s.level[o] != 0 ? "built" : "-"; - if (o == 0 && s.level[0] != 0) state = "stage " + std::to_string((s.level[0] - 1) / 85 + 1) + " of 3"; + if (o == 0 && s.level[0] != 0) { // three stages in steps of 85; a Modern world: four in steps of 64 + const int stages = bmh::world_layout().traffic_stages, step = stages == 4 ? 64 : 85; + state = "stage " + std::to_string((s.level[0] - 1) / step + 1) + " of " + std::to_string(stages); + } rows.push_back({std::to_string(o), text(kPeripheryNames + int(o)), building ? "building" : state, std::to_string(s.days[o])}); } diff --git a/src/game/world_layout.hpp b/src/game/world_layout.hpp index 4abb43f..e973599 100644 --- a/src/game/world_layout.hpp +++ b/src/game/world_layout.hpp @@ -42,6 +42,9 @@ struct WorldLayout { // national_start: team no_team() + n at national_start + (n - 1) * national_slots). Classic: none, // the national teams play without players. uint32_t national_start = 0, national_slots = 0; + // Stages of the traffic access (periphery object 0): Classic 3 (condition byte in steps of + // 0x55), a Modern world 4 (steps of 64; the Modern interface shows four). + int traffic_stages = 3; int first_amateur() const { return league_teams; } int first_foreign_cup() const { return league_teams + amateur_teams; } diff --git a/src/modern/app/modern_session.cpp b/src/modern/app/modern_session.cpp index 63894e9..4ece9fc 100644 --- a/src/modern/app/modern_session.cpp +++ b/src/modern/app/modern_session.cpp @@ -654,6 +654,13 @@ ModernSession::ModernSession(const std::filesystem::path &data, uint32_t watcom_ // saves from before the national squads end at the reserve: the national squads // start empty (those teams play with their drawn rating until the next nomination) if (g_.squad_slots.size() < world_layout().total_slots) g_.squad_slots.resize(world_layout().total_slots, 0x0fff); + // saves from before the four traffic stages keep the original's scale: convert each + // manager record's traffic access byte to its stage in the new scale + if (modern::four_traffic_stages() && g_.traffic_scale != 64) { + for (size_t rec = 0; rec + 0xb0c <= g_.manager_records.size(); rec += 0xb0c) + g_.manager_records[rec] = modern::traffic_from_original(g_.manager_records[rec]); + g_.traffic_scale = 64; + } rand_ = saved.random; game_ = saved.game; native.emplace(); @@ -4320,6 +4327,7 @@ bool ModernSession::finish(ui::CareerInitializationResult& result, std::string& // Both UI projections must reflect the freshly initialized driver cursor. // Reuse its prepared groups; these projections do not prepare an event or draw RNG. modern::ensure_ui_identities(g_); // career and manager ids of the interface contract + if (modern::four_traffic_stages()) g_.traffic_scale = 64; // the start built the traffic access in that scale result.desktop = desktop_projection(1); result.preparation = preparation_projection(1); for (size_t m = 0; m < managers_.size(); ++m) @@ -8387,7 +8395,7 @@ bool ModernSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, request.object >= 14 || !plain(request.object)) return invalid("invalid_periphery_offer"); const size_t object = size_t(request.object); const uint8_t level = g_.manager_records[record + object]; - if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0)) + if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? !modern::traffic_buildable(level) : level != 0)) return invalid("periphery_unavailable"); const int32_t price = modern::periphery_offer(g_, request.object, game_); if (price <= 0) return invalid("invalid_periphery_price"); @@ -8403,7 +8411,7 @@ bool ModernSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, if (request.kind == ui::StadiumRequestKind::build_periphery) { const size_t object = size_t(request.object); const uint8_t level = g_.manager_records[record + object]; - if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0)) + if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? !modern::traffic_buildable(level) : level != 0)) return invalid("periphery_unavailable"); // ConstructionPricePercent consumes this genuine JA even when PayConstruction's // payment fails. The Source presenter runs before the quote @@ -8924,7 +8932,7 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co for (size_t o = 0; o < 14; ++o) { const int level = st.level[o]; O row{{"id", "periphery:" + std::to_string(o)}, {"name", text(720 + o)}, {"constructionDays", int(st.days[o])}}; - if (o == 0) row["stage"] = level == 0 ? 0 : (level - 1) / 85 + 1, row["maxStage"] = 3; + if (o == 0) row["stage"] = modern::traffic_stage(level), row["maxStage"] = world_layout().traffic_stages; else row["built"] = level != 0; periphery.push_back(std::move(row)); } diff --git a/src/modern/app/modern_session.hpp b/src/modern/app/modern_session.hpp index f59d774..3677ecd 100644 --- a/src/modern/app/modern_session.hpp +++ b/src/modern/app/modern_session.hpp @@ -4,6 +4,7 @@ #include "modern/content/projections.hpp" #include "modern/content/statistics.hpp" #include "modern/content/ui_contract.hpp" +#include "modern/game/traffic.hpp" #include "modern/content/world_expand.hpp" // The engine side of the UI's career handoff (src/ui/flow.hpp, ENGINE_BINDING.md). // diff --git a/src/modern/content/world_expand.cpp b/src/modern/content/world_expand.cpp index e4cf542..6966bc2 100644 --- a/src/modern/content/world_expand.cpp +++ b/src/modern/content/world_expand.cpp @@ -142,6 +142,7 @@ WorldLayout modern_layout(int league_clubs, int german_clubs) { // no_team, filled on the international days from the players of its nationality w.national_start = w.pool_end + w.no_team_slots + 54; w.national_slots = kSquadSlots; + w.traffic_stages = 4; // the four stages of the Modern interface (modern/game/traffic.hpp) w.total_slots = w.national_start + uint32_t(w.national_teams - 1) * w.national_slots; return w; } diff --git a/src/modern/content/world_save.cpp b/src/modern/content/world_save.cpp index 780c576..082a84e 100644 --- a/src/modern/content/world_save.cpp +++ b/src/modern/content/world_save.cpp @@ -138,7 +138,8 @@ void save_world_career(const std::filesystem::path& path, const World& world, co {"exclusive_sponsors", sponsors_json(state.exclusive_sponsors)}, {"career_id", state.career_id}, {"manager_ids", strings(state.manager_ids)}, - {"manager_serial", int64_t(state.manager_serial)}}); + {"manager_serial", int64_t(state.manager_serial)}, + {"traffic_scale", int64_t(state.traffic_scale)}}); // The almanac: finished seasons unchanged, the running one encoded now. for (const auto& [name, bytes] : state.almanac.finished) docs[name] = bytes; if (state.almanac.current.season >= 0) docs["history/current.bin"] = encode_almanac_season(state.almanac.current); @@ -193,6 +194,7 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl out.state.career_id = str(get(modern, "career_id")); out.state.manager_ids = strings(get(modern, "manager_ids")); out.state.manager_serial = uint32_t(num(get(modern, "manager_serial"))); + if (o->count("traffic_scale")) out.state.traffic_scale = uint8_t(num(get(modern, "traffic_scale"))); } for (const auto& [name, bytes] : docs) { if (!name.starts_with("history/season-")) continue; diff --git a/src/modern/game/balance_plan.cpp b/src/modern/game/balance_plan.cpp index b206492..21f7cab 100644 --- a/src/modern/game/balance_plan.cpp +++ b/src/modern/game/balance_plan.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "modern/game/traffic.hpp" #include "modern/game/modern_state.hpp" #include "modern/game/environment.hpp" #include "modern/game/balance_plan.hpp" @@ -50,7 +51,7 @@ int32_t wrap(int64_t v) { return int32_t(uint32_t(uint64_t(v))); } // Add32: the level of a facility (facility 0: its size step) uint32_t facility_level(const ModernState& g, int m, int k) { const uint8_t v = rec8(g, m, size_t(k)); - return k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xff : 1; + return k == 0 ? uint32_t(traffic_stage(v)) & 0xff : 1; // the traffic access by its stage (traffic.hpp) } // DailyInterest2(0): the interest of one day without booking it - negative is income diff --git a/src/modern/game/career.cpp b/src/modern/game/career.cpp index d58bfed..0f1cae3 100644 --- a/src/modern/game/career.cpp +++ b/src/modern/game/career.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "modern/game/traffic.hpp" #include "modern/game/modern_state.hpp" #include "modern/game/career.hpp" @@ -446,7 +447,7 @@ void build_stadium(ModernState& g, const LeImage& exe, int m, int league, int mo const uint8_t level = mode == 1 ? 3 : exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(i + league * 0x17)); if (i == 0x10 || i == 0x11 || level == 0) continue; if (i == 0) { - rec[0] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(league * 0x17)) + (mode == 1 ? 0x55 : 0)); + rec[0] = traffic_from_original(uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(league * 0x17)) + (mode == 1 ? 0x55 : 0))); } else { rec[i] = uint8_t(rand.range(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField2 + uint32_t(i * 5)), exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField3 + uint32_t(i * 5))) << 2); } diff --git a/src/modern/game/matchday_setup.cpp b/src/modern/game/matchday_setup.cpp index fdc0c32..c62c7c3 100644 --- a/src/modern/game/matchday_setup.cpp +++ b/src/modern/game/matchday_setup.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "modern/game/traffic.hpp" #include "modern/game/modern_state.hpp" #include "modern/game/matchday_setup.hpp" #include "game/trace.hpp" @@ -108,7 +109,7 @@ int32_t catering_income(const ModernState& g, int manager, int32_t spectators, W for (int k = 0; k < 14; k++) { const uint8_t v = g.manager_records.at(rec + size_t(k)); if (v == 0) continue; - const uint32_t level = k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32 + const uint32_t level = k == 0 ? uint32_t(traffic_stage(v)) & 0xFF : 1; // Add32 (traffic.hpp) sum += kPerVisitor[k] * uint32_t(spectators) * level / 100; } if (sum != 0) sum = uint32_t(rand.range(0x55, 0x73)) * sum / 100; @@ -724,7 +725,7 @@ int attendance(ModernState& g, int home, int away, int bits, int temperature, in for (int k = 0; k < 10; k++) { const int v = r8(size_t(k)); // MatchdaySetupRuntimeField6[0] is overwritten with the step of the stadium size - const int32_t step = k == 0 ? int32_t(v / 0x55 * 25000) : kStadiumSteps[k]; + const int32_t step = k == 0 ? int32_t(traffic_full_stages(v) * 25000) : kStadiumSteps[k]; if (step < n && (v == 0 || k == 0)) n -= n / rand.range(10, 20); } const int wet = int(uint32_t(100 - covered) * uint32_t(uint8_t(rain)) * 8) / 100; diff --git a/src/modern/game/modern_state.hpp b/src/modern/game/modern_state.hpp index 1f0141d..0fab9d6 100644 --- a/src/modern/game/modern_state.hpp +++ b/src/modern/game/modern_state.hpp @@ -82,6 +82,9 @@ struct ModernState : GameState { std::string career_id; std::vector manager_ids; uint32_t manager_serial = 0; + // The scale of the traffic access bytes (traffic.hpp): 0 the original's (steps of 0x55), 64 the + // four stages of a Modern world. Older Modern saves are converted when loaded. + uint8_t traffic_scale = 0; // Players whose age the data set gives (birth date); the others carry a placeholder the // career start replaces as in the original. Needed only while a career starts (not saved). std::vector world_age_known; diff --git a/src/modern/game/month.cpp b/src/modern/game/month.cpp index 4481ec3..37a76c4 100644 --- a/src/modern/game/month.cpp +++ b/src/modern/game/month.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "modern/game/traffic.hpp" #include "modern/game/modern_state.hpp" #include "modern/game/environment.hpp" #include "modern/game/month.hpp" @@ -531,7 +532,7 @@ int32_t monthly_income(ModernState& g, int m) { for (int k = 0; k < 6; k++) { const uint8_t v = r.at(rec + size_t(k)); if (v == 0) continue; - const int level = k == 0 ? ((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32 + const int level = k == 0 ? traffic_stage(v) & 0xFF : 1; // Add32 (traffic.hpp) sum += level * kFacilityIncome[k]; } add32(r, rec + 0x86c, sum); diff --git a/src/modern/game/traffic.hpp b/src/modern/game/traffic.hpp new file mode 100644 index 0000000..704c1e4 --- /dev/null +++ b/src/modern/game/traffic.hpp @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The traffic access (Verkehrsanbindung, stadium periphery object 0, manager record +0x00): +// the only periphery object with stages. Its condition byte grows by one stage per finished +// build and sinks with the stadium's ageing; a stage counts while the byte is above the stage +// below it. +// +// The original has three stages in steps of 0x55 (85, 170, 255; a new build is offered below +// 0xab). A Modern world has four, as the Modern interface shows them: steps of 64 (64, 128, +// 192, 255; a build is offered below 193). Every stage weighs as much as one original stage +// (income per visitor, monthly income, the attendance step). Classic data in the Modern core +// keeps the original three (WorldLayout::traffic_stages). + +#include +#include + +#include "game/world_layout.hpp" + +namespace bmh::modern { + +inline bool four_traffic_stages() { return world_layout().traffic_stages == 4; } +inline int traffic_step() { return four_traffic_stages() ? 64 : 0x55; } + +// The stage of a condition byte, 0 = none (the original's Add32 level). +inline int traffic_stage(int v) { return v <= 0 ? 0 : (v - 1) / traffic_step() + 1; } + +// The completed stages (MatchdaySetup's size step: the original's v / 0x55; 255 is stage 4). +inline int traffic_full_stages(int v) { + if (!four_traffic_stages()) return v / 0x55; + return v >= 255 ? 4 : v / 64; +} + +// Whether the building firm offers another stage. +inline bool traffic_buildable(int v) { return v < (four_traffic_stages() ? 3 * 64 + 1 : 0xab); } + +// The condition byte after a finished build: the next full stage. +inline uint8_t traffic_after_build(int v) { + const int step = traffic_step(); + return uint8_t(std::min(255, (v == 0 ? 1 : (v - 1) / step + 2) * step)); +} + +// The original's value of a stage boundary (the ageing message at each boundary). +inline bool traffic_stage_boundary(int v) { return v % traffic_step() == 0; } + +// A condition byte of the original's scale (start tables, older Modern saves) in this world's scale. +inline uint8_t traffic_from_original(int v) { + if (!four_traffic_stages() || v == 0) return uint8_t(v); + return uint8_t(std::min(255, ((v - 1) / 0x55 + 1) * 64)); +} + +} // namespace bmh::modern diff --git a/src/modern/game/weekly.cpp b/src/modern/game/weekly.cpp index d49f0ee..875e81e 100644 --- a/src/modern/game/weekly.cpp +++ b/src/modern/game/weekly.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-only #include "formats/executable_layout.hpp" +#include "modern/game/traffic.hpp" #include "modern/game/modern_state.hpp" #include "modern/game/weekly.hpp" #include "modern/game/club_player_detail.hpp" @@ -171,7 +172,7 @@ int facility_rating(ModernState& g, int manager, int* second, WatcomRandom* rand const uint8_t v = rec.b(size_t(i)); if (v == 0) continue; int level; - if (i < 0xe || i == 0x10 || i == 0x11) level = i == 0 ? (v - 1) / 0x55 + 1 : 1; + if (i < 0xe || i == 0x10 || i == 0x11) level = i == 0 ? traffic_stage(v) : 1; else level = rec.b(size_t(i) + 0x2e) & 7; sum += (level & 0xFF) * kFacility[i * 5]; } @@ -365,7 +366,7 @@ void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom if (weeks == 0 && rec.b(size_t(i)) != 0 && rec.b(0x1e + size_t(i)) == 0) { uint8_t& v = rec.b(size_t(i)); v--; - if ((i == 0 && v % 0x55 == 0) || rec.b(0x1e + size_t(i)) + v == 0) { + if ((i == 0 && traffic_stage_boundary(v)) || rec.b(0x1e + size_t(i)) + v == 0) { if (i < 0xe) { message = true; } else if (i < 0x16) { @@ -388,7 +389,7 @@ void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom uint8_t& build = rec.b(0x1e + size_t(i)); if (build != 0 && --build == 0) { uint8_t& v = rec.b(size_t(i)); - if (i == 0) v = uint8_t((v == 0 ? 1 : (v - 1) / 0x55 + 2) * 0x55); + if (i == 0) v = traffic_after_build(v); else v = uint8_t(rand.range(kFacility[i * 5 + 2], kFacility[i * 5 + 3]) << 2); if (i > 0xd) { rec.b(0x2e + size_t(i)) = uint8_t((rec.b(0x2e + size_t(i)) >> 4) & 7); diff --git a/tests/modern_traffic_tests.cpp b/tests/modern_traffic_tests.cpp new file mode 100644 index 0000000..0e1f437 --- /dev/null +++ b/tests/modern_traffic_tests.cpp @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The traffic access stages (modern/game/traffic.hpp): the original's three in steps of 0x55, +// a Modern world's four in steps of 64, and the conversion of the original's scale. +#include + +#include "game/world_layout.hpp" +#include "modern/game/traffic.hpp" + +using namespace bmh; +using namespace bmh::modern; + +namespace { +int failures = 0; +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } +} +} // namespace + +int main() { + // Classic: 0 -> 85 -> 170 -> 255, a build is offered below 0xab + set_world_layout(classic_world_layout()); + check(traffic_after_build(0) == 85 && traffic_after_build(85) == 170 && traffic_after_build(170) == 255, "classic builds"); + check(traffic_buildable(170) && !traffic_buildable(255), "classic offer limit"); + check(traffic_stage(85) == 1 && traffic_stage(170) == 2 && traffic_stage(255) == 3 && traffic_stage(84) == 1, "classic stages"); + check(traffic_full_stages(255) == 3 && traffic_full_stages(169) == 1, "classic size steps"); + check(traffic_from_original(170) == 170, "classic keeps its scale"); + + // a Modern world: 0 -> 64 -> 128 -> 192 -> 255, a build is offered below 193 + WorldLayout modern = classic_world_layout(); + modern.traffic_stages = 4; + set_world_layout(modern); + check(traffic_after_build(0) == 64 && traffic_after_build(64) == 128 && traffic_after_build(128) == 192 && + traffic_after_build(192) == 255, "four builds"); + check(traffic_buildable(192) && !traffic_buildable(255), "fourth stage offered, then no more"); + check(traffic_stage(64) == 1 && traffic_stage(128) == 2 && traffic_stage(192) == 3 && traffic_stage(255) == 4, "four stages"); + check(traffic_stage(63) == 1 && traffic_stage(191) == 3, "aged values keep their stage"); + check(traffic_full_stages(255) == 4 && traffic_full_stages(192) == 3 && traffic_full_stages(191) == 2, "size steps"); + check(traffic_stage_boundary(128) && !traffic_stage_boundary(127), "ageing message at a stage boundary"); + check(traffic_from_original(85) == 64 && traffic_from_original(170) == 128 && traffic_from_original(255) == 192 && + traffic_from_original(0) == 0 && traffic_from_original(150) == 128, "the original's stages in the new scale"); + + set_world_layout(classic_world_layout()); + if (failures == 0) std::printf("modern traffic tests passed\n"); + return failures == 0 ? 0 : 1; +}