Modern UI contract: live matchdays with interventions
session.advance {live: true} runs the kickoff on its own thread and stops at
the minutes of a live match of a human manager (not at a voided one).
live.step plays on, live.substitute and live.tactics act as the original's
pitch and tactics screens during a match (open, change, close) on the
kickoff thread, live.finish plays the day to its end. Other commands answer
live_running meanwhile, read_live reports the minute and the live scores.
A missing contract decision rolls the whole live day back. Also: the
recording takes matches up to the day the kickoff ends.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
10a8f0b881
commit
822331f045
6 files changed
+386
-4
No files matched your search
+2
-1
@@ -356,7 +356,8 @@ add_executable(modern_world_info tests/modern_world_info.cpp)
|
||||
target_link_libraries(modern_world_info PRIVATE bmh_modern_content)
|
||||
|
||||
add_library(bmh_modern_session STATIC src/modern/app/modern_session.cpp)
|
||||
target_link_libraries(bmh_modern_session PUBLIC bmh_season_modern bmh_modern_content bmhui)
|
||||
find_package(Threads REQUIRED)
|
||||
target_link_libraries(bmh_modern_session PUBLIC bmh_season_modern bmh_modern_content bmhui Threads::Threads)
|
||||
if(MSVC)
|
||||
target_compile_options(bmh_modern_session PRIVATE /W4 /utf-8 /bigobj)
|
||||
else()
|
||||
|
||||
@@ -58,7 +58,7 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt
|
||||
- `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.
|
||||
- **Live mit Eingriffen:** `session.advance {live: true}` startet den Anstoß in einem eigenen Ablauf, der nach der ersten Minute eines laufenden Live-Spiels eines Menschen anhält (eine gewertete Partie, z. B. ein Forfeit, läuft ohne Halt durch). Solange er steht, liefert `read_live` `{live: true, status: "paused", minute, matches}` (Stand je Live-Spiel, Manager je Seite); die vollständige Aufzeichnung folgt nach dem Abpfiff. Alle anderen Befehle antworten `live_running`, bis der Spieltag vorbei ist.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -82,6 +82,11 @@ Die UI ruft diese über `DataSource::read_almanac` und `read_statistics` direkt
|
||||
| `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` |
|
||||
| `session.advance` mit `live: true` | wie oben, dazu `contractExpiry` | Live-Spieltag: hält in der ersten Minute eines Live-Spiels an (`changedReadKinds: ["live"]`); läuft kein Live-Spiel, endet er sofort wie ein normaler Anstoß |
|
||||
| `live.step` | `minutes` (1–150, sonst 1) | spielt so viele Spielminuten des Live-Spiels und hält wieder an; ist der Spieltag vorbei, kommt die Antwort des Anstoßes |
|
||||
| `live.substitute` | `outPlayerId`, `inPlayerId` | Wechsel wie im Spielfeld-Bildschirm des Originals (öffnen, tauschen, schließen; ab Minute 3); Fehler `substitution_refused` |
|
||||
| `live.tactics` | `values` (8) | Taktik wie im Taktik-Bildschirm während des Spiels; Fehler `invalid_tactic` |
|
||||
| `live.finish` | `{}` | spielt den Spieltag ohne weiteren Halt zu Ende; Antwort wie `session.advance` (bei fehlender Vertragsentscheidung wird der ganze Live-Spieltag zurückgerollt: `decision_pending`) |
|
||||
| `bank.commit` | `action` `deposit`/`withdraw` mit `amount` (`Money`, ganze Euro) oder `buy`/`sell` mit `assetId` (`stock:<n>`, `fund:<n>`) 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` |
|
||||
|
||||
@@ -8766,6 +8766,29 @@ cli::Json ModernSession::read_live(const cli::Json& request) const {
|
||||
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 (live_) {
|
||||
// a live kickoff standing still: the minute and the live matches' scores so far (the
|
||||
// full recording with every event follows after the final whistle, kind "fixture")
|
||||
if (!live_->paused || !live_->groups) return fail("live_running");
|
||||
cli::Json::Array matches;
|
||||
for (const MatchGroup& grp : *live_->groups)
|
||||
for (int m = 0; m < grp.matches(); ++m) {
|
||||
const int home = grp.fixtures.at(size_t(m) * 2), away = grp.fixtures.at(size_t(m) * 2 + 1);
|
||||
if (std::find(g_.live_matches.begin(), g_.live_matches.end(), home) == g_.live_matches.end()) continue;
|
||||
int h = 0, a = 0;
|
||||
if (!grp.results.empty()) h = grp.results.at(size_t(m)) >> 4, a = grp.results.at(size_t(m)) & 0xf;
|
||||
else if (grp.cup_results.size() == size_t(grp.matches()))
|
||||
h = grp.cup_results[size_t(m)] >> 5 & 0x1f, a = grp.cup_results[size_t(m)] & 0x1f;
|
||||
if (h >= 0xc || a >= 0xc) h = a = 0; // not under way yet
|
||||
const int hm = g_.manager_of(home), am = g_.manager_of(away);
|
||||
matches.push_back(O{{"home", O{{"id", modern::ui_team_id(g_, home)}, {"name", ui::original_to_utf8(g_.club_name(home))}}},
|
||||
{"away", O{{"id", modern::ui_team_id(g_, away)}, {"name", ui::original_to_utf8(g_.club_name(away))}}},
|
||||
{"homeManagerId", hm >= 0 ? cli::Json(modern::ui_manager_id(g_, hm)) : cli::Json(nullptr)},
|
||||
{"awayManagerId", am >= 0 ? cli::Json(modern::ui_manager_id(g_, am)) : cli::Json(nullptr)},
|
||||
{"score", cli::Json::Array{cli::Json(h), cli::Json(a)}}});
|
||||
}
|
||||
return O{{"ok", true}, {"live", true}, {"status", "paused"}, {"minute", live_->minute}, {"matches", std::move(matches)}};
|
||||
}
|
||||
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");
|
||||
@@ -9141,6 +9164,53 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co
|
||||
{"initialized", !t.needs_initialization()}, {"automation", int(t.automation)}});
|
||||
}
|
||||
|
||||
void ModernSession::wait_live() {
|
||||
std::unique_lock<std::mutex> lock(live_->mutex);
|
||||
live_->changed.wait(lock, [this] { return live_->paused || live_->done; });
|
||||
}
|
||||
|
||||
cli::Json ModernSession::finish_live(const std::string& request_id, uint64_t previous, uint64_t& revision) {
|
||||
LiveRun& run = *live_;
|
||||
if (run.worker.joinable()) run.worker.join();
|
||||
// the session's own hooks again
|
||||
turn_driver_.live_minute = run.previous_live_minute;
|
||||
turn_driver_.sportschau = run.previous_sportschau;
|
||||
const TurnAdvanceResult result = run.result;
|
||||
const std::string error = run.error.empty() ? result.reason : run.error;
|
||||
const std::string pending = run.pending_player;
|
||||
if (result.kind == TurnDeskKind::Failed || result.kind == TurnDeskKind::WaitingAtDesk) {
|
||||
// the whole live kickoff goes back, as an ordinary advance does
|
||||
g_ = std::move(run.saved_state);
|
||||
rand_ = run.saved_rand, game_ = run.saved_game;
|
||||
g_.contract_screen = run.previous_contract_hook;
|
||||
contract_expiry_presenter_installed_ = run.previous_contract_installed;
|
||||
revision = run.base_revision;
|
||||
live_.reset();
|
||||
cli::Json refused = modern::ui_error(request_id, pending.empty() ? (result.kind == TurnDeskKind::WaitingAtDesk ? "decision_pending" : "advance_failed")
|
||||
: "decision_pending",
|
||||
pending.empty() ? "Weiter nicht möglich: " + error : "Ein Vertrag läuft aus: Verlängern oder freigeben?",
|
||||
revision, false);
|
||||
if (!pending.empty())
|
||||
std::get<cli::Json::Object>(std::get<cli::Json::Object>(refused.value)["message"].value)["args"] =
|
||||
cli::Json::Object{{"decision", "contract_expiry"}, {"playerId", pending}};
|
||||
return refused;
|
||||
}
|
||||
g_.contract_screen = run.previous_contract_hook;
|
||||
contract_expiry_presenter_installed_ = run.previous_contract_installed;
|
||||
modern::ensure_ui_identities(g_);
|
||||
ui_last_advance_ = std::make_pair(run.from_date, g_.date);
|
||||
ui_last_awards_ = std::move(run.awards);
|
||||
revision = previous + 1;
|
||||
ui_last_advance_revision_ = revision;
|
||||
live_.reset();
|
||||
cli::Json answer = modern::ui_command_result(request_id, previous, revision,
|
||||
{"session", "desktop", "squad", "lineup", "tactics", "training", "camps", "bank", "statistics", "almanac", "live", "postmatch"},
|
||||
result.kind == TurnDeskKind::SeasonEndDesk ? "Saisonende." : result.kind == TurnDeskKind::CareerComplete
|
||||
? "Die Karriere ist zu Ende." : "Abpfiff. Weiter zum nächsten Termin.");
|
||||
if (result.kind == TurnDeskKind::CareerComplete) std::get<cli::Json::Object>(answer.value)["outcome"] = "career_ended";
|
||||
return answer;
|
||||
}
|
||||
|
||||
cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision) {
|
||||
const std::string request_id = ui_text(request, "requestId");
|
||||
const std::string kind = ui_text(request, "kind");
|
||||
@@ -9166,6 +9236,118 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision
|
||||
return refuse("manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.");
|
||||
const cli::Json* payload = ui_field(request, "payload");
|
||||
if (!payload || !payload->object()) return refuse("invalid_payload", "Der Befehl braucht ein payload-Objekt.");
|
||||
// a live kickoff stands still: only its own commands until it is finished
|
||||
if (live_ && !kind.starts_with("live.")) return refuse("live_running", "Ein Spieltag läuft live; erst live.step oder live.finish.");
|
||||
if (!live_ && kind.starts_with("live.")) return refuse("live_not_running", "Es läuft kein Live-Spieltag.");
|
||||
if (live_) {
|
||||
const uint64_t previous = revision;
|
||||
LiveRun& run = *live_;
|
||||
cli::Json answer;
|
||||
if (kind == "live.step" || kind == "live.finish") {
|
||||
const cli::Json* minutes = ui_field(*payload, "minutes");
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(run.mutex);
|
||||
if (kind == "live.finish") run.finish = true;
|
||||
else run.remaining = minutes && minutes->integer() && *minutes->integer() >= 1 && *minutes->integer() <= 150
|
||||
? int(*minutes->integer()) : 1;
|
||||
run.paused = false;
|
||||
}
|
||||
run.changed.notify_all();
|
||||
wait_live();
|
||||
if (run.done) return finish_live(request_id, previous, revision);
|
||||
revision = previous + 1;
|
||||
answer = modern::ui_command_result(request_id, previous, revision, {"live"}, "Minute " + std::to_string(run.minute));
|
||||
} else if (kind == "live.substitute" || kind == "live.tactics") {
|
||||
// live.substitute {outPlayerId, inPlayerId}: a player on the pitch for one on the bench;
|
||||
// live.tactics {values: [8]}: the tactics board. Both as the original's pitch and tactics
|
||||
// screens during a match (open, change, close), on the kickoff thread.
|
||||
if (!run.paused || !run.engine) return refuse("live_not_paused", "Der Spieltag steht nicht still.");
|
||||
const int team = g_.manager_teams[size_t(manager)];
|
||||
std::string task_error;
|
||||
bool task_ok = false;
|
||||
std::function<void()> task;
|
||||
if (kind == "live.substitute") {
|
||||
const std::string out_id = ui_text(*payload, "outPlayerId"), in_id = ui_text(*payload, "inPlayerId");
|
||||
task = [&, team, out_id, in_id] {
|
||||
const int minute = run.minute;
|
||||
MatchEngine& engine = *run.engine;
|
||||
if (!begin_live_intervention(minute, 2, manager, team, engine, run.engine_revision, task_error)) return;
|
||||
const SquadRange range = squad_range(team);
|
||||
int out_row = -1, in_row = -1;
|
||||
for (size_t row = 0; row < range.count; ++row) {
|
||||
const int p = g_.squad_slots[range.first + row] & 0x0fff;
|
||||
if (p == 0x0fff) continue;
|
||||
if (modern::ui_player_id(g_, p) == out_id) out_row = int(row);
|
||||
if (modern::ui_player_id(g_, p) == in_id) in_row = int(row);
|
||||
}
|
||||
if (out_row < 0 || in_row < 0) {
|
||||
task_error = "unknown_player";
|
||||
abort_live_intervention(minute, 2, manager, team, engine, run.engine_revision);
|
||||
return;
|
||||
}
|
||||
ui::LineupRequest r;
|
||||
r.kind = ui::LineupRequestKind::swap_players;
|
||||
r.manager_slot = manager, r.runtime_club = team, r.revision = run.engine_revision;
|
||||
r.first_row = out_row, r.second_row = in_row;
|
||||
r.first_slot = g_.squad_slots[range.first + size_t(out_row)], r.second_slot = g_.squad_slots[range.first + size_t(in_row)];
|
||||
r.first_player = r.first_slot & 0x0fff, r.second_player = r.second_slot & 0x0fff;
|
||||
const LiveSubstitutionResult result = dispatch_live_substitution_result(r, minute, 2, engine, run.engine_revision);
|
||||
if (result.status != LiveSubstitutionStatus::applied) {
|
||||
task_error = result.error.empty() ? "substitution_refused" : result.error;
|
||||
abort_live_intervention(minute, 2, manager, team, engine, run.engine_revision);
|
||||
return;
|
||||
}
|
||||
task_ok = finish_live_intervention(minute, 2, manager, team, engine, run.engine_revision, task_error);
|
||||
};
|
||||
} else {
|
||||
const cli::Json* values = ui_field(*payload, "values");
|
||||
const auto* list = values ? values->array() : nullptr;
|
||||
if (!list || list->size() != 8) return refuse("invalid_payload", "values braucht acht Taktikwerte.");
|
||||
std::array<int, 8> want{};
|
||||
for (size_t i = 0; i < 8; ++i) {
|
||||
if (!(*list)[i].integer()) return refuse("invalid_payload", "Taktikwerte sind ganze Zahlen.");
|
||||
want[i] = int(*(*list)[i].integer());
|
||||
}
|
||||
task = [&, team, want] {
|
||||
const int minute = run.minute;
|
||||
MatchEngine& engine = *run.engine;
|
||||
if (!begin_live_intervention(minute, 8, manager, team, engine, run.engine_revision, task_error)) return;
|
||||
const size_t rec = size_t(manager) * 0xb0c;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (int(g_.manager_records.at(rec + 0xd2 + size_t(i))) == want[size_t(i)]) continue;
|
||||
ui::TacticsRequest r;
|
||||
r.kind = ui::TacticsRequestKind::set_tactic;
|
||||
r.manager_slot = manager, r.runtime_club = team, r.revision = run.engine_revision;
|
||||
r.index = i, r.desired_value = want[size_t(i)];
|
||||
if (i == 0) r.desired_assistant_attitude = 0;
|
||||
if (!dispatch_live_tactic(r, minute, 8, engine, run.engine_revision, task_error)) {
|
||||
abort_live_intervention(minute, 8, manager, team, engine, run.engine_revision);
|
||||
return;
|
||||
}
|
||||
}
|
||||
task_ok = finish_live_intervention(minute, 8, manager, team, engine, run.engine_revision, task_error);
|
||||
};
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(run.mutex);
|
||||
run.task = std::move(task);
|
||||
}
|
||||
run.changed.notify_all();
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(run.mutex);
|
||||
run.changed.wait(lock, [&] { return !run.task; });
|
||||
}
|
||||
if (!task_ok) return refuse(kind == "live.substitute" ? "substitution_refused" : "invalid_tactic", task_error);
|
||||
revision = previous + 1;
|
||||
answer = modern::ui_command_result(request_id, previous, revision, {"live", "lineup", "tactics"},
|
||||
kind == "live.substitute" ? "Wechsel ausgeführt." : "Taktik geändert.");
|
||||
} else {
|
||||
return refuse("unknown_command", "Unbekannter Live-Befehl: " + kind);
|
||||
}
|
||||
ui_answers_[request_id] = {body, answer};
|
||||
ui_answer_order_.push_back(request_id);
|
||||
return answer;
|
||||
}
|
||||
|
||||
// a refused engine action leaves the state and both generators as they were
|
||||
const ModernState saved_state = g_;
|
||||
@@ -9336,6 +9518,104 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision
|
||||
if (!ok) { restore(); return refuse(error.empty() ? "invalid_training" : error, "Training nicht übernommen: " + error); }
|
||||
if (revision != previous) revision = previous + 1;
|
||||
answer = modern::ui_command_result(request_id, previous, revision, {"training"}, "Training übernommen.");
|
||||
} else if (kind == "session.advance" && ui_field(*payload, "live") && std::holds_alternative<bool>(ui_field(*payload, "live")->value) &&
|
||||
std::get<bool>(ui_field(*payload, "live")->value)) {
|
||||
// the kickoff on its own thread, stopping after the first match minute of a human match
|
||||
auto run = std::make_shared<LiveRun>();
|
||||
if (const cli::Json* e = ui_field(*payload, "contractExpiry"); e && e->object())
|
||||
for (const auto& [id, value] : *e->object()) {
|
||||
ContractExpiryAnswer x;
|
||||
if (ui_text(value, "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);
|
||||
}
|
||||
run->answers[id] = x;
|
||||
}
|
||||
run->saved_state = saved_state, run->saved_rand = saved_rand, run->saved_game = saved_game;
|
||||
run->base_revision = previous, run->from_date = g_.date, run->engine_revision = revision;
|
||||
run->previous_contract_hook = g_.contract_screen;
|
||||
run->previous_contract_installed = contract_expiry_presenter_installed_;
|
||||
run->previous_sportschau = turn_driver_.sportschau;
|
||||
run->previous_live_minute = turn_driver_.live_minute;
|
||||
LiveRun* r = run.get();
|
||||
set_contract_expiry_presenter([r](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 = r->answers.find(id);
|
||||
if (it == r->answers.end()) { r->pending_player = id; return -2; }
|
||||
if (!it->second.renew) return 0;
|
||||
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; }
|
||||
});
|
||||
turn_driver_.sportschau.awards = [r, inner = run->previous_sportschau.awards](const GameState& state, const SportschauAwardsView& v) {
|
||||
const auto& ms = static_cast<const modern::ModernState&>(state);
|
||||
cli::Json::Array players;
|
||||
for (const auto& p : v.players) {
|
||||
if (p.player_id == 0x0fff) continue;
|
||||
const std::string club = p.team_id >= 0 ? modern::ui_team_id(ms, p.team_id) : std::string{};
|
||||
players.push_back(cli::Json::Object{{"playerId", modern::ui_player_id(ms, p.player_id)}, {"name", ui::original_to_utf8(p.player_name)},
|
||||
{"teamId", club.empty() ? cli::Json(nullptr) : cli::Json(club)},
|
||||
{"club", ui::original_to_utf8(p.club_name)}, {"score", int(p.score)}});
|
||||
}
|
||||
r->awards.push_back(cli::Json::Object{{"competition", ui::original_to_utf8(v.competition_title)}, {"players", std::move(players)}});
|
||||
if (inner) inner(state, v);
|
||||
};
|
||||
turn_driver_.live_minute = [r, inner = run->previous_live_minute](int minute, MatchEngine& engine, std::vector<MatchGroup>& groups, GameState& gs) {
|
||||
if (inner) inner(minute, engine, groups, gs);
|
||||
// only the minutes of a live match that is played (not one voided, e.g. a forfeit)
|
||||
bool live_match = false;
|
||||
for (const MatchGroup& grp : engine.groups)
|
||||
for (int m = 0; m < grp.matches() && !live_match; ++m) {
|
||||
const uint32_t bit = uint32_t(1) << m;
|
||||
if ((grp.kickoff_void_mask & bit) || (grp.void_mask() & bit)) continue;
|
||||
const int home = grp.fixtures.at(size_t(m) * 2);
|
||||
live_match = std::find(gs.live_matches.begin(), gs.live_matches.end(), home) != gs.live_matches.end();
|
||||
}
|
||||
if (!live_match) return;
|
||||
std::unique_lock<std::mutex> lock(r->mutex);
|
||||
if (r->finish || --r->remaining > 0) return;
|
||||
r->paused = true, r->minute = minute, r->engine = &engine, r->groups = &groups;
|
||||
r->changed.notify_all();
|
||||
for (;;) {
|
||||
r->changed.wait(lock, [r] { return r->finish || r->remaining > 0 || bool(r->task); });
|
||||
if (!r->task) break;
|
||||
auto task = std::move(r->task);
|
||||
lock.unlock();
|
||||
task();
|
||||
lock.lock();
|
||||
r->task = nullptr;
|
||||
r->changed.notify_all();
|
||||
}
|
||||
r->paused = false, r->engine = nullptr, r->groups = nullptr;
|
||||
};
|
||||
live_ = std::move(run);
|
||||
live_->worker = std::thread([this, r, manager] {
|
||||
ui::DeskRequest kickoff;
|
||||
kickoff.kind = ui::DeskRequestKind::advance_turn;
|
||||
kickoff.manager_slot = manager;
|
||||
kickoff.revision = r->engine_revision;
|
||||
std::string error;
|
||||
TurnAdvanceResult result;
|
||||
try { result = dispatch_kickoff(kickoff, r->engine_revision, error); } catch (const std::exception& e) { error = e.what(); }
|
||||
std::lock_guard<std::mutex> lock(r->mutex);
|
||||
r->result = result, r->error = error, r->done = true, r->paused = false;
|
||||
r->changed.notify_all();
|
||||
});
|
||||
wait_live();
|
||||
if (live_->done) return finish_live(request_id, previous, revision);
|
||||
revision = previous + 1;
|
||||
answer = modern::ui_command_result(request_id, previous, revision, {"live"}, "Live: Minute " + std::to_string(live_->minute));
|
||||
} 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
|
||||
|
||||
@@ -18,14 +18,17 @@
|
||||
// ModernSession owns the engine state of that sequence. It never draws numbers for
|
||||
// rendering; every random draw belongs to one of the steps above.
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <array>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
@@ -1140,6 +1143,52 @@ private:
|
||||
bool loan_return_presenter_installed_ = false;
|
||||
bool loan_return_offer_presenter_installed_ = false;
|
||||
bool options_applied_ = false;
|
||||
|
||||
// --- a live kickoff of the interface contract (session.advance {live: true}) ----------------
|
||||
// The kickoff runs on its own thread and stops at the match minutes the interface asks for
|
||||
// (TurnDriver::live_minute); live.step, live.substitute, live.tactics and live.finish act while
|
||||
// it stands still, the interface thread waits meanwhile. Reads therefore never meet a running
|
||||
// engine. Declared last: destroyed first, its destructor ends a running kickoff.
|
||||
struct ContractExpiryAnswer { bool renew = false; int term = 0; uint32_t salary = 0; };
|
||||
struct LiveRun {
|
||||
std::thread worker;
|
||||
std::mutex mutex;
|
||||
std::condition_variable changed;
|
||||
bool paused = false, done = false, finish = false;
|
||||
int remaining = 1; // minutes to play before the next stop
|
||||
int minute = 0; // the minute it stands at
|
||||
MatchEngine* engine = nullptr; // valid while paused
|
||||
std::vector<MatchGroup>* groups = nullptr;
|
||||
std::function<void()> task; // an intervention, run on the kickoff thread
|
||||
TurnAdvanceResult result;
|
||||
std::string error, pending_player;
|
||||
uint64_t engine_revision = 0; // the revision the kickoff and its interventions count
|
||||
// the advance it belongs to: rollback point, answers, the hooks it replaced
|
||||
ModernState saved_state;
|
||||
WatcomRandom saved_rand;
|
||||
GameRandom saved_game;
|
||||
uint64_t base_revision = 0;
|
||||
uint32_t from_date = 0;
|
||||
std::map<std::string, ContractExpiryAnswer> answers;
|
||||
cli::Json::Array awards;
|
||||
std::function<int(GameState&, int, int)> previous_contract_hook;
|
||||
bool previous_contract_installed = false;
|
||||
SportschauPresentationHooks previous_sportschau;
|
||||
decltype(TurnDriver::live_minute) previous_live_minute;
|
||||
~LiveRun() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
finish = true;
|
||||
}
|
||||
changed.notify_all();
|
||||
if (worker.joinable()) worker.join();
|
||||
}
|
||||
};
|
||||
std::shared_ptr<LiveRun> live_; // (shared: the session is copied for staged modal work, never while live)
|
||||
// waits until the live kickoff stands still or is done (interface thread)
|
||||
void wait_live();
|
||||
// ends a finished live kickoff: hooks back, rollback on failure; the answer for `request_id`
|
||||
cli::Json finish_live(const std::string& request_id, uint64_t previous, uint64_t& revision);
|
||||
};
|
||||
|
||||
} // namespace bmh::modern::app
|
||||
@@ -791,7 +791,7 @@ cli::Json live_fixture(const ModernState& g, uint32_t after_date, uint32_t until
|
||||
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
|
||||
if (m.date < after_date || m.date > until_date) continue; // played from the desk day on (only played matches are recorded)
|
||||
((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"}};
|
||||
@@ -891,7 +891,7 @@ cli::Json almanac_matches_between(const ModernState& g, uint32_t from_date, uint
|
||||
A out;
|
||||
for (const auto& s : seasons_of(g))
|
||||
for (size_t i = 0; i < s.matches.size(); ++i)
|
||||
if (s.matches[i].date >= from_date && s.matches[i].date < until_date) out.push_back(almanac_match(g, s, i));
|
||||
if (s.matches[i].date >= from_date && s.matches[i].date <= until_date) out.push_back(almanac_match(g, s, i));
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
@@ -403,6 +403,53 @@ 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 live kickoff: stops in a match of the human manager, steps, intervenes, finishes
|
||||
{
|
||||
bool stopped = false;
|
||||
for (int k = 0; k < 12 && !stopped; ++k) {
|
||||
const J started = session.ui_command(cmd("request:lr" + std::to_string(k), "session.advance", O{{"live", true}}), rev);
|
||||
const J state = session.read_live(O{{"kind", "fixture"}});
|
||||
stopped = truth(at(state, "live"));
|
||||
if (!stopped)
|
||||
check(s(at(started, "messageType")) == "command_result", "a live kickoff without a human match runs through");
|
||||
}
|
||||
check(stopped, "a live kickoff stood still in a match");
|
||||
if (stopped) {
|
||||
check(s(at(session.ui_command(cmd("request:lx", "bank.commit", O{{"action", "deposit"}}), rev), "code")) == "live_running",
|
||||
"other commands wait for the live kickoff");
|
||||
const J stepped = session.ui_command(cmd("request:ls", "live.step", O{{"minutes", 30}}), rev);
|
||||
const J state = session.read_live(O{{"kind", "fixture"}});
|
||||
check(s(at(stepped, "messageType")) == "command_result" && at(state, "minute").integer() &&
|
||||
*at(state, "minute").integer() >= 30, "thirty minutes on");
|
||||
std::printf("(live state: %s)\n", cli::dump_json(state).substr(0, 400).c_str());
|
||||
// a substitution: the last field row for the first bench row
|
||||
const J lineup = session.ui_read(O{{"kind", "lineup"}}, rev);
|
||||
const auto* order = at(at(lineup, "data"), "order").array();
|
||||
if (order && order->size() > 11) {
|
||||
const J sub = session.ui_command(cmd("request:lsub", "live.substitute",
|
||||
O{{"outPlayerId", (*order)[10]}, {"inPlayerId", (*order)[11]}}), rev);
|
||||
std::printf("(live substitution: %s)\n", cli::dump_json(sub).substr(0, 200).c_str());
|
||||
check(s(at(sub, "messageType")) == "command_result" || s(at(sub, "code")) == "substitution_refused",
|
||||
"live substitution answered");
|
||||
}
|
||||
const J tactics = session.ui_read(O{{"kind", "tactics"}}, rev);
|
||||
if (const auto* controls = at(at(tactics, "data"), "controls").array(); controls && controls->size() == 8) {
|
||||
J::Array values;
|
||||
for (const auto& c : *controls) values.push_back(at(c, "value"));
|
||||
values[7] = J(*values[7].integer() == 0 ? 1 : 0);
|
||||
const J changed = session.ui_command(cmd("request:ltac", "live.tactics", O{{"values", values}}), rev);
|
||||
std::printf("(live tactics: %s)\n", cli::dump_json(changed).substr(0, 800).c_str());
|
||||
check(s(at(changed, "messageType")) == "command_result", "live tactics changed");
|
||||
}
|
||||
const J done = session.ui_command(cmd("request:lf", "live.finish", O{}), rev);
|
||||
check(s(at(done, "messageType")) == "command_result", "live kickoff finished");
|
||||
const J fixture = session.read_live(O{{"kind", "fixture"}});
|
||||
if (!truth(at(fixture, "ok"))) std::printf("(fixture: %s)\n", cli::dump_json(fixture).substr(0, 200).c_str());
|
||||
check(truth(at(fixture, "ok")) && at(fixture, "frames").array() && at(fixture, "frames").array()->size() >= 4,
|
||||
"the live kickoff's recording");
|
||||
}
|
||||
check(s(at(session.ui_command(cmd("request:lz", "live.step", O{}), rev), "code")) == "live_not_running", "no live kickoff");
|
||||
}
|
||||
// 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)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user