Initial public OpenBMH 0.1 source (by Codex)

This commit is contained in:
Codex committed 2026-10-16 19:36:32 +02:00
commit 558fbf166b
613 files changed
+168029

No files matched your search

+737
View File
@@ -0,0 +1,737 @@
// SPDX-License-Identifier: GPL-3.0-only
// The console's core: registry, input blocks, argument binding, output and the global
// commands (docs/CLI_CONCEPT/01-grundlagen.md). The windows live in windows_*.cpp.
#include "cli/console/console.hpp"
#include <algorithm>
#include <stdexcept>
#include "cli/console/detail.hpp"
#include "ui/manager.hpp"
namespace bmh::cli::console {
using namespace detail;
// ---------------------------------------------------------------------------------------
// detail helpers
namespace detail {
Param integer(std::string name, long long min, long long max, bool optional) {
Param p;
p.name = std::move(name);
p.type = Param::Type::integer;
p.min = min, p.max = max, p.optional = optional;
return p;
}
Param boolean(std::string name, bool optional) {
Param p;
p.name = std::move(name);
p.type = Param::Type::boolean;
p.optional = optional;
return p;
}
Param text(std::string name, long long max_length, bool optional) {
Param p;
p.name = std::move(name);
p.type = Param::Type::text;
p.max = max_length, p.optional = optional;
return p;
}
Param choice(std::string name, std::vector<std::string> choices, bool optional) {
Param p;
p.name = std::move(name);
p.type = Param::Type::choice;
p.choices = std::move(choices);
p.optional = optional;
return p;
}
std::string on_off(bool v) { return v ? "on" : "off"; }
std::string lower(std::string s) {
for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));
return s;
}
std::string utf8(std::string_view text) {
for (char c : text)
if (static_cast<unsigned char>(c) >= 0x80) return std::string(text);
return ui::original_to_utf8(text);
}
std::string fold(std::string s) {
s = lower(std::move(s));
// UTF-8 Ä Ö Ü (C3 84, C3 96, C3 9C) -> ä ö ü (C3 A4, C3 B6, C3 BC)
for (size_t i = 0; i + 1 < s.size(); ++i)
if (static_cast<unsigned char>(s[i]) == 0xC3) {
unsigned char& c = reinterpret_cast<unsigned char&>(s[i + 1]);
if (c == 0x84 || c == 0x96 || c == 0x9C) c = static_cast<unsigned char>(c + 0x20);
}
return s;
}
// Dates as the concept's `date` type: YYYY-MM-DD (01-grundlagen 1.2).
std::string date_text(int day, int month, int year) {
char buffer[16];
std::snprintf(buffer, sizeof buffer, "%04d-%02d-%02d", year, month, day);
return buffer;
}
std::string money(long long value) { return std::to_string(value); }
size_t resolve_player(const std::string& reference, const std::vector<PlayerRef>& players) {
const std::string key = lower(reference);
auto number = [&](size_t prefix) {
Arg a;
a.text = reference.substr(prefix);
const auto n = to_int(a);
if (!n) fail("E_BAD_ARGUMENT", "\"" + reference + "\" is no player reference (id:<n>, row:<n> or a name)");
return int(*n);
};
if (key.rfind("id:", 0) == 0 || key.rfind("row:", 0) == 0) {
const bool by_id = key[0] == 'i';
const int n = number(by_id ? 3 : 4);
for (size_t i = 0; i < players.size(); ++i)
if ((by_id ? players[i].id : players[i].row) == n) return i;
fail("E_BAD_ARGUMENT", "no player " + reference + " in this list");
}
const std::string wanted = fold(reference);
std::vector<size_t> exact, partial;
for (size_t i = 0; i < players.size(); ++i) {
const std::string name = fold(players[i].name);
if (name == wanted) exact.push_back(i);
else if (name.find(wanted) != std::string::npos) partial.push_back(i);
}
const auto& found = exact.empty() ? partial : exact;
if (found.size() == 1) return found.front();
if (found.empty()) fail("E_BAD_ARGUMENT", "no player named \"" + reference + "\" in this list");
std::string candidates;
for (size_t i = 0; i < found.size() && i < 8; ++i)
candidates += (i ? ", " : "") + players[found[i]].name + " = id:" + std::to_string(players[found[i]].id);
fail("E_AMBIGUOUS", "\"" + reference + "\" fits several players: " + candidates);
}
} // namespace detail
namespace {
const char* class_name(char cls) {
switch (cls) {
case '#': return "status";
case '>': return "option";
case '|': return "table";
case '+': return "ok";
case '!': return "error";
case '?': return "question";
case 'i': return "info";
case '~': return "event";
case 'c': return "chat";
default: return "other";
}
}
// The type part of a parameter: "1..5", "bool", "string", "enum(a,b)".
std::string param_type(const Param& p) {
switch (p.type) {
case Param::Type::integer: return std::to_string(p.min) + ".." + std::to_string(p.max);
case Param::Type::boolean: return "bool";
case Param::Type::text: return p.max > 0 ? "string(max " + std::to_string(p.max) + ")" : "string";
case Param::Type::choice: {
std::string s = "enum(";
for (size_t i = 0; i < p.choices.size(); ++i) s += (i ? "," : "") + p.choices[i];
return s + ")";
}
}
return {};
}
// A parameter in a signature: "name:type", optional ones in [brackets].
std::string param_text(const Param& p) {
if (!p.display.empty()) return p.display;
const std::string s = p.name + ":" + (p.type == Param::Type::text ? "string" : param_type(p));
return p.optional ? "[" + s + "]" : s;
}
// The index of an enum argument: a name of the list (canonical comparison) or its number.
int choice_index(const Param& p, const Arg& a) {
for (size_t i = 0; i < p.choices.size(); ++i)
if (canonical(p.choices[i]) == canonical(a.text)) return int(i);
if (const auto n = to_int(a); n && *n >= 0 && size_t(*n) < p.choices.size()) return int(*n);
return -1;
}
size_t edit_distance(const std::string& a, const std::string& b) {
std::vector<size_t> row(b.size() + 1);
for (size_t j = 0; j <= b.size(); ++j) row[j] = j;
for (size_t i = 1; i <= a.size(); ++i) {
size_t diagonal = row[0];
row[0] = i;
for (size_t j = 1; j <= b.size(); ++j) {
const size_t up = row[j];
row[j] = std::min({row[j] + 1, row[j - 1] + 1, diagonal + (a[i - 1] == b[j - 1] ? 0 : 1)});
diagonal = up;
}
}
return row[b.size()];
}
} // namespace
long long Console::Values::integer(const std::string& name, long long fallback) const {
const auto it = args.find(canonical(name));
return it == args.end() ? fallback : *to_int(it->second);
}
bool Console::Values::boolean(const std::string& name, bool fallback) const {
const auto it = args.find(canonical(name));
return it == args.end() ? fallback : *to_bool(it->second);
}
std::string Console::Values::text(const std::string& name, std::string fallback) const {
const auto it = args.find(canonical(name));
return it == args.end() ? fallback : it->second.text;
}
int Console::Values::choice(const std::string& name) const {
const auto it = args.find(canonical(name));
if (it == args.end() || !spec) return -1;
for (const Param& p : spec->params)
if (canonical(p.name) == canonical(name)) return choice_index(p, it->second);
return -1;
}
// ---------------------------------------------------------------------------------------
Console::Console(Options options, std::function<void(const std::string&)> write)
: options_(std::move(options)), write_(std::move(write)) {
texts_ = load_textd(ui::asset_path(options_.data, "TEXTD.BLK"));
exe_ = load_le(ui::asset_path(options_.data, "BMH.exe"));
// The program start up to the options dialog (InitializeCareer) - as the SDL app does it.
session_ = std::make_unique<app::CareerSession>(options_.data, options_.seed);
install_hooks();
register_global_commands();
register_start_commands();
register_file_commands();
register_desk_commands();
register_table_commands();
register_club_commands();
register_money_commands();
register_office_commands();
register_squad_commands();
register_transfer_commands();
register_info_commands();
register_match_commands();
register_friendly_commands();
register_reschedule_commands();
register_balance_commands();
register_environment_commands();
register_state_commands();
register_advice_commands();
}
// ~Console is in windows_match.cpp, where the engine thread (EngineRun) is complete.
std::string Console::text(int index) const {
if (index < 0 || size_t(index) >= texts_.strings.size()) return {};
std::string s = utf8(texts_.strings[size_t(index)]);
// dialog markers at the start steer the original's dialog mode (09-texte 1.6)
while (!s.empty() && (s.rfind("\xC2\xA7", 0) == 0 || s.rfind("\xC2\xBA", 0) == 0)) s.erase(0, 2);
// padding for the screen layout is no content
while (!s.empty() && s.back() == ' ') s.pop_back();
while (!s.empty() && s.front() == ' ') s.erase(0, 1);
return s;
}
// ---------------------------------------------------------------------------------------
// registry
void Console::add(Spec spec, Handler handler) {
handlers_[spec.window + "/" + canonical(spec.name)] = std::move(handler);
specs_.push_back(std::move(spec));
}
const Spec* Console::find(std::string_view window, std::string_view key) const {
for (const Spec& s : specs_)
if (s.window == window && canonical(s.name) == key) return &s;
return nullptr;
}
void Console::register_global_commands() {
// --- global commands, valid in every window (01-grundlagen 9) ----------------------
Param list_param = detail::text("command", 0, true);
list_param.display = "[command:string|all]";
add({"*", "ListOptions", {list_param}, "commands possible here; ListOptions(all) also shows locked ones", false},
[this](const Values& v) {
const std::string which = v.text("command");
if (!which.empty() && canonical(which) != "all") {
const Spec* spec = find(window_, canonical(which));
if (!spec) spec = find("*", canonical(which));
if (!spec) fail("E_UNKNOWN_COMMAND", which + " is not a command of " + window_);
emit('>', option_line(*spec));
std::vector<std::vector<std::string>> rows;
for (const Param& p : spec->params) rows.push_back({p.name, param_type(p), p.optional ? "optional" : "required"});
if (!rows.empty()) emit_table({"Parameter", "Type", "Use"}, rows);
return;
}
const bool all = !which.empty();
for (const Spec* spec : window_specs(all)) {
std::string line = option_line(*spec);
if (canonical(spec->name) == "answer" && !question_) line += " [locked: no open question]";
emit('>', line);
// the desk's icons: one line per window Open() reaches (02-fenster 4 and 6)
if (window_ == "Desktop" && canonical(spec->name) == "open" && career_) {
ui::DeskState d = desk();
std::sort(d.items.begin(), d.items.end(), [](const auto& a, const auto& b) { return a.kind < b.kind; });
for (const auto& item : d.items) {
if (item.kind >= 30 || item.kind == 12) continue; // widgets; 12 = Kickoff
if (item.disabled && !all) continue;
std::string target = " Open(" + menu_window(item.kind) + ")";
if (target.size() < 48) target.resize(48, ' ');
target += " - menu " + std::to_string(item.kind);
if (item.disabled) target += " [locked: mode]";
emit('>', target);
}
}
}
});
add({"*", "GoBack", {}, "right mouse button: one level back, otherwise nothing", false},
[this](const Values& v) {
if (question_) {
// a question's right mouse button: its default answer (01-grundlagen 2.4) - only
// from the player it belongs to, and said aloud (it may decline a sale)
if (v.player && v.player != question_->player)
fail("E_NOT_YOUR_TURN", "the question belongs to player " + std::to_string(question_->player));
Question q = std::move(*question_);
question_.reset();
emit('+', "Q" + std::to_string(q.id) + " answered: " + q.default_option + " (GoBack = default answer)");
q.on_answer(q.default_option);
return;
}
if (window_ == "NewGame") new_game_continue(); // exception: right mouse = next (H1 S. 13)
else if (const auto it = closers_.find(window_); it != closers_.end()) it->second();
else if (!close_window()) emit('+', "nothing to go back to");
});
Param chat_to = integer("to", 0, 4, true);
add({"*", "Chat", {chat_to, detail::text("text", 200)}, "message to all, or to one player (0 = only the log)", false},
[this](const Values& v) {
const std::string message = v.text("text");
if (message.empty()) fail("E_BAD_ARGUMENT", "text must not be empty");
const int from = v.player ? v.player : (player_ ? player_ : 1);
const int to = v.has("to") ? int(v.integer("to")) : -1;
chat_.push_back({from, to, message});
const std::string target = to < 0 ? "All" : to == 0 ? "Log" : "P" + std::to_string(to);
emit('c', "[P" + std::to_string(from) + " -> " + target + "] " + message);
});
add({"*", "ChatLog", {integer("count", 1, 1000, true)}, "the last chat messages", false}, [this](const Values& v) {
const size_t count = size_t(v.integer("count", 20));
std::vector<std::vector<std::string>> rows;
const size_t first = chat_.size() > count ? chat_.size() - count : 0;
for (size_t i = first; i < chat_.size(); ++i) {
const ChatEntry& e = chat_[i];
rows.push_back({std::to_string(i + 1), "P" + std::to_string(e.from),
e.to < 0 ? "All" : e.to == 0 ? "Log" : "P" + std::to_string(e.to), e.text});
}
emit_table({"#", "From", "To", "Text"}, rows);
});
Param answer_option = detail::text("option");
answer_option.display = "option:enum";
Param answer_id = detail::text("id");
answer_id.display = "id:int"; // 2 or Q2, as the question line shows it
add({"*", "Answer", {answer_id, answer_option}, "answer the open question", false},
[this](const Values& v) {
if (!question_) fail("E_BAD_ARGUMENT", "there is no open question");
std::string id_text = v.text("id");
if (!id_text.empty() && (id_text[0] == 'Q' || id_text[0] == 'q')) id_text.erase(0, 1);
Arg id_arg;
id_arg.text = id_text;
const auto id = to_int(id_arg);
if (!id) fail("E_BAD_ARGUMENT", "id must be the question number, e.g. 2 or Q2");
if (*id != question_->id) fail("E_BAD_ARGUMENT", "the open question is Q" + std::to_string(question_->id));
if (v.player && v.player != question_->player)
fail("E_NOT_YOUR_TURN", "the question belongs to player " + std::to_string(question_->player));
Arg arg;
arg.text = v.text("option");
std::string chosen;
for (const std::string& o : question_->options)
if (canonical(o) == canonical(arg.text)) chosen = o;
if (chosen.empty() && question_->options == std::vector<std::string>{"Yes", "No"})
if (const auto b = to_bool(arg)) chosen = *b ? "Yes" : "No";
if (chosen.empty())
if (const auto n = to_int(arg); n && *n >= 1 && size_t(*n) <= question_->options.size())
chosen = question_->options[size_t(*n - 1)];
if (chosen.empty()) fail("E_BAD_ARGUMENT", "option must be one of the question's options");
Question q = std::move(*question_);
question_.reset();
emit('+', "Q" + std::to_string(q.id) + " answered: " + chosen); // (some answers print nothing else)
q.on_answer(chosen);
});
add({"*", "Status", {}, "window, player and a short overview", false}, [this](const Values& v) {
// a seat not on turn sees the desk of the manager on turn: say so, so it is not read
// as its own club
if (v.player && player_ && v.player != player_)
emit('+', "you are player " + std::to_string(v.player) + "; player " + std::to_string(player_) +
" is on turn - the overview below is his");
if (run_) {
emit('+', match_status());
return;
}
if (!career_) {
emit('+', "options: " + options_text());
} else {
const ui::DeskState d = desk();
emit('+', utf8(d.manager_name) + " | " + utf8(d.club_name) + " | " +
date_text(d.date.day, d.date.month, d.date.year) + " | balance " + money(d.balance));
}
if (question_) emit('+', "open question: Q" + std::to_string(question_->id));
});
add({"*", "Help", {detail::text("command", 0, true)}, "command reference (all windows)", false}, [this](const Values& v) {
const std::string which = v.text("command");
for (const Spec& spec : specs_) {
if (!which.empty() && canonical(spec.name) != canonical(which)) continue;
emit('>', "[" + spec.window + "] " + option_line(spec));
}
if (!which.empty() && std::none_of(specs_.begin(), specs_.end(),
[&](const Spec& s) { return canonical(s.name) == canonical(which); }))
fail("E_UNKNOWN_COMMAND", which + " is no command");
});
add({"*", "Quit", {boolean("force", true)}, "end the session (asks first during a game)", false},
[this](const Values& v) {
auto end = [this] {
if (run_) stop_matchday();
ended_ = true;
emit('+', "session ended");
};
if (question_ && !v.boolean("force"))
fail("E_PENDING_QUESTION", "answer Q" + std::to_string(question_->id) + " first (or Quit(force=true))");
if (!career_ || v.boolean("force")) {
end();
return;
}
// the plug on the desk asks first (H2 S. 24); the question is the console's own
// text: the original asks with a picture, not with a TEXTD text
ask("Quit the game? Unsaved progress is lost.", {"Yes", "No"}, "No", [this, end](const std::string& answer) {
if (answer == "Yes") end();
else emit('+', "quit cancelled");
});
});
}
// ---------------------------------------------------------------------------------------
// input
void Console::start() {
last_block_.clear();
last_output_.clear();
flush_status();
}
bool Console::feed(std::string_view line) {
if (ended_) return false;
switch (classify_line(line)) {
case LineKind::skip: break;
case LineKind::clear: pending_.clear(); break;
case LineKind::command: pending_.emplace_back(line); break;
case LineKind::go: execute_block(); break;
}
return !ended_;
}
void Console::execute_block() {
last_block_ = std::move(pending_);
pending_.clear();
last_output_.clear();
if (last_block_.empty()) {
emit('+', "nothing to do");
return;
}
for (size_t i = 0; i < last_block_.size() && !ended_; ++i) {
try {
Command cmd;
try {
cmd = parse_command(last_block_[i]);
} catch (const ParseError& e) {
fail("E_BAD_ARGUMENT", std::string("syntax: ") + e.what());
}
try {
execute(cmd);
} catch (const CliError&) {
throw;
} catch (const std::exception& e) {
// an engine exception is a defect of the program, never of the input
fail("E_INTERNAL", e.what());
}
} catch (const CliError& e) {
emit('!', e.code + ": " + e.message + (e.text_key.empty() ? "" : " [textKey: " + e.text_key + "]"));
const size_t skipped = last_block_.size() - i - 1;
if (skipped) emit('!', "E_BLOCK_ABORTED: " + std::to_string(skipped) + " command" + (skipped == 1 ? "" : "s") + " skipped");
break;
}
}
flush_status();
}
void Console::execute(const Command& cmd) {
const Spec* spec = find(window_, cmd.key);
if (!spec) spec = find("*", cmd.key);
if (!spec) {
// Run/Step outside a match: with several managers the match day starts only after the
// last one's Kickoff (each Kickoff passes the turn) - agents sent Run here again and
// again in the learning session, so the error says what to do instead
if ((cmd.key == "run" || cmd.key == "step") && window_ != "Match")
fail("E_NOT_IN_WINDOW", "no match is running - the match day starts after every manager's Kickoff; "
"WaitTurn (or Status) shows when the window is Match");
for (const Spec& s : specs_)
if (canonical(s.name) == cmd.key) fail("E_NOT_IN_WINDOW", s.name + " is only available in " + s.window);
std::string best;
size_t best_distance = 1000;
for (const Spec& s : specs_) {
const size_t d = edit_distance(cmd.key, canonical(s.name));
if (d < best_distance) best_distance = d, best = s.name;
}
fail("E_UNKNOWN_COMMAND", cmd.name + " is unknown" +
(best_distance <= std::max<size_t>(2, cmd.key.size() / 3) ? " (did you mean " + best + "?)" : ""));
}
// An engine question owns the paused kickoff. Some navigation commands are
// changes=false yet prepare Native state on entry (notably Open(Lineup)).
// Only explicit observers and the current question's answer may run here.
const bool engine_question_observer =
spec->window == "*" &&
(cmd.key == "answer" || cmd.key == "goback" || cmd.key == "status" ||
cmd.key == "help" || cmd.key == "listoptions" || cmd.key == "chat" || cmd.key == "chatlog" ||
(cmd.key == "quit" && loan_return_modal_active()));
const bool engine_question_desk_observer =
spec->window == "Desktop" && (cmd.key == "showdate" || cmd.key == "showopponent");
if (question_ && (spec->changes ||
(run_ && !engine_question_observer && !engine_question_desk_observer)))
fail("E_PENDING_QUESTION", "answer Q" + std::to_string(question_->id) + " first");
if (loan_return_offer_active() && !engine_question_observer && spec->window != "Transfer.Negotiate")
fail("E_MODE_LOCKED", "finish the loan-return negotiation first");
if (spec->changes && cmd.player && player_ && cmd.player != player_)
fail("E_NOT_YOUR_TURN", "current player is " + std::to_string(player_));
if (loan_return_modal_active() && cmd.player && cmd.player != player_ &&
(cmd.key == "goback" || cmd.key == "quit"))
fail("E_NOT_YOUR_TURN", "the loan-return modal belongs to player " + std::to_string(player_));
// A player who is not on turn shares the screen with the active one: he may use the
// commands of every window (Status, Help, Chat, Answer ...) but not those of the open
// window, which would page or open things under the active player's hands.
if (cmd.player && player_ && cmd.player != player_ && spec->window != "*")
fail("E_NOT_YOUR_TURN", "current player is " + std::to_string(player_) + " (WaitTurn waits for your turn)");
Values values = bind(*spec, cmd);
handlers_.at(spec->window + "/" + canonical(spec->name))(values);
succeeded_.insert(spec->window + "/" + spec->name);
}
Console::Values Console::bind(const Spec& spec, const Command& cmd) const {
Values values;
values.spec = &spec;
values.player = cmd.player;
std::vector<const Arg*> positional;
for (const Arg& a : cmd.args)
if (a.name.empty()) positional.push_back(&a);
const size_t required = size_t(std::count_if(spec.params.begin(), spec.params.end(), [](const Param& p) { return !p.optional; }));
if (positional.size() > spec.params.size())
fail("E_BAD_ARGUMENT", spec.name + " takes at most " + std::to_string(spec.params.size()) + " arguments");
// positional arguments fill the required parameters; the surplus fills optional ones
// from the left (Chat("x") = text, Chat(2, "x") = to + text)
// "fee:1500000" looks like the name:type of ListOptions but is a positional text; say how
// named arguments are written (references like id:7, club:3 go to text parameters)
for (const Arg* a : positional) {
const size_t colon = a->text.find(':');
if (colon == std::string::npos || colon == 0) continue;
const std::string head = canonical(a->text.substr(0, colon));
if (head == canonical("id") || head == canonical("row")) continue;
for (const Param& p : spec.params)
if (canonical(p.name) == head && p.type != Param::Type::text) // texts take references like club:3
fail("E_BAD_ARGUMENT", "named arguments are written name=value, e.g. " + p.name + "=" + a->text.substr(colon + 1));
}
size_t optional_slots = positional.size() > required ? positional.size() - required : 0;
size_t next = 0;
for (const Param& p : spec.params) {
if (next >= positional.size()) break;
if (p.optional) {
if (optional_slots == 0) continue;
--optional_slots;
}
values.args[canonical(p.name)] = *positional[next++];
}
for (const Arg& a : cmd.args) {
if (a.name.empty()) continue;
const auto it = std::find_if(spec.params.begin(), spec.params.end(), [&](const Param& p) { return canonical(p.name) == a.name; });
if (it == spec.params.end()) fail("E_BAD_ARGUMENT", spec.name + " has no parameter " + a.name);
if (values.args.count(a.name)) fail("E_BAD_ARGUMENT", "parameter " + it->name + " given twice");
values.args[a.name] = a;
}
for (const Param& p : spec.params) {
const auto it = values.args.find(canonical(p.name));
if (it == values.args.end()) {
if (!p.optional) fail("E_BAD_ARGUMENT", spec.name + " needs " + param_text(p));
continue;
}
const Arg& a = it->second;
switch (p.type) {
case Param::Type::integer: {
const auto n = to_int(a);
if (!n || *n < p.min || *n > p.max)
fail("E_BAD_ARGUMENT", p.name + " must be " + std::to_string(p.min) + ".." + std::to_string(p.max));
break;
}
case Param::Type::boolean:
if (!to_bool(a)) fail("E_BAD_ARGUMENT", p.name + " must be true or false");
break;
case Param::Type::text:
if (p.max > 0 && a.text.size() > size_t(p.max))
fail("E_BAD_ARGUMENT", p.name + " is longer than " + std::to_string(p.max) + " characters");
break;
case Param::Type::choice:
if (choice_index(p, a) < 0) fail("E_BAD_ARGUMENT", p.name + " must be one of " + param_type(p));
break;
}
}
return values;
}
// ---------------------------------------------------------------------------------------
// output
void Console::emit(char cls, const std::string& text, Json data) {
if (cls != '#') flush_status();
std::string line;
if (options_.json) {
Json::Object o;
o["class"] = class_name(cls);
o["window"] = window_;
o["player"] = player_ ? Json(player_) : Json("All");
o["text"] = text;
if (!std::holds_alternative<std::nullptr_t>(data.value)) o["data"] = std::move(data);
line = dump_json(Json(std::move(o)));
} else {
line = std::string(1, cls) + " " + text;
}
last_output_.push_back(line);
if (observer_) observer_({cls, player_, text, line});
write_(line);
}
void Console::emit_table(const std::vector<std::string>& header, const std::vector<std::vector<std::string>>& rows) {
auto row_text = [](const std::vector<std::string>& cells) {
std::string s = "|";
for (const std::string& c : cells) s += " " + c + " |";
return s.substr(2); // emit adds "| "
};
auto cells_json = [](const std::vector<std::string>& cells, bool head) {
Json::Array a;
for (const std::string& c : cells) a.emplace_back(c);
return Json(Json::Object{{"header", head}, {"cells", Json(std::move(a))}});
};
// With --json each row also carries a record keyed by the column names, the cells typed:
// whole numbers and the references id:/row:/club: as numbers, "-" and "" as null, the
// rest as text - what a graphical client needs without parsing the table (stage 2.5).
auto typed = [](const std::string& cell) -> Json {
if (cell.empty() || cell == "-") return Json(nullptr);
std::string digits = cell;
for (const char* prefix : {"id:", "row:", "club:"})
if (digits.rfind(prefix, 0) == 0) digits = digits.substr(std::string(prefix).size());
const bool negative = !digits.empty() && digits[0] == '-';
const size_t from = negative ? 1 : 0;
if (digits.size() > from && digits.size() - from <= 18 &&
digits.find_first_not_of("0123456789", from) == std::string::npos)
return Json(std::int64_t(std::stoll(digits)));
return Json(cell);
};
emit('|', row_text(header), cells_json(header, true));
for (const auto& r : rows) {
Json data = cells_json(r, false);
if (options_.json) {
Json::Object record;
for (size_t i = 0; i < r.size(); ++i)
record[i < header.size() && !header[i].empty() ? header[i] : "c" + std::to_string(i + 1)] = typed(r[i]);
data.object()->insert_or_assign("record", Json(std::move(record)));
}
emit('|', row_text(r), std::move(data));
}
}
void Console::flush_status() {
if (window_ == printed_window_ && player_ == printed_player_) return;
printed_window_ = window_;
printed_player_ = player_;
emit('#', "Window: " + window_);
emit('#', "Player: " + (player_ ? std::to_string(player_) : std::string("All")));
}
std::string Console::option_line(const Spec& spec) const {
std::string sig = spec.name + "(";
for (size_t i = 0; i < spec.params.size(); ++i) sig += (i ? ", " : "") + param_text(spec.params[i]);
sig += ")";
if (spec.description.empty()) return sig;
if (sig.size() < 48) sig.resize(48, ' ');
return sig + " - " + spec.description;
}
std::vector<const Spec*> Console::window_specs(bool include_locked) const {
std::vector<const Spec*> result;
for (const Spec& s : specs_)
if (s.window == window_) result.push_back(&s);
for (const Spec& s : specs_) {
if (s.window != "*") continue;
if (canonical(s.name) == "answer" && !question_ && !include_locked) continue;
result.push_back(&s);
}
return result;
}
// ---------------------------------------------------------------------------------------
// windows and questions
void Console::set_window(std::string window, int player) {
window_ = std::move(window);
player_ = player;
back_.clear();
}
void Console::open_window(std::string window) {
back_.push_back(window_);
window_ = std::move(window);
}
bool Console::close_window() {
if (back_.empty()) {
// the start windows have a fixed way back (02-fenster 3)
if (window_ == "NewGame.LoadGame" || (window_ == "NewGame.Select" && confirmed_.empty())) {
set_window("NewGame", 1);
return true;
}
return false;
}
window_ = back_.back();
back_.pop_back();
return true;
}
void Console::ask(std::string text, std::vector<std::string> options, std::string default_option,
std::function<void(const std::string&)> on_answer, std::string text_key) {
Question q;
q.id = next_question_++;
q.player = player_ ? player_ : 1;
q.text = std::move(text);
q.options = std::move(options);
q.default_option = std::move(default_option);
q.on_answer = std::move(on_answer);
std::string opts;
for (size_t i = 0; i < q.options.size(); ++i) opts += (i ? " | " : "") + q.options[i];
// --json: the question as data (id, the player it belongs to, the options and the answer
// GoBack gives), so a client can show a dialog without parsing the line
Json data = nullptr;
if (options_.json) {
Json::Array options;
for (const auto& o : q.options) options.emplace_back(o);
data = Json(Json::Object{{"id", q.id}, {"player", q.player}, {"text", q.text}, {"options", Json(std::move(options))},
{"default", q.default_option}, {"text_key", text_key}});
}
emit('?', "Q" + std::to_string(q.id) + " \"" + q.text + "\" options: " + opts +
(text_key.empty() ? "" : " [textKey: " + text_key + "]"),
std::move(data));
question_ = std::move(q);
}
} // namespace bmh::cli::console
+327
View File
@@ -0,0 +1,327 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The console language of openbmh_cli (docs/CLI_CONCEPT):
// - input in blocks of command lines, executed by a line "go." (01-grundlagen 1.1)
// - output lines with a class character (# status, > option, | table, + ok, ! error,
// ? question, i info, ~ event, c chat), the status lines "# Window:" / "# Player:" printed
// whenever window or player changed (2.2); --json gives one JSON object per line
// - global commands ListOptions, GoBack, Chat, ChatLog, Answer, Status, Help, Quit (9)
//
// Stage 0 (console.cpp, windows_start.cpp): options screen NewGame, load browser.
// Stage 1: manager selection NewGame.Select (+ Confirm), the info sequence after the last
// manager, Desktop with its displays, Open/Key, Kickoff (time "instant"), the file windows
// LoadGame/SaveGame, Mailbox, LeagueTable and Fixtures (windows_desk.cpp, windows_tables.cpp).
//
// The console owns no game logic: everything that changes the game goes through
// app::CareerSession (including its staged Source modal callbacks), like the SDL app. It never
// draws random numbers itself; where the original draws numbers when a window opens (the
// fixtures window), the console opens it through the same engine call.
#include <cstdint>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
#include "app/career_session.hpp"
#include "game/balance_plan.hpp"
#include "game/bank_credit.hpp"
#include "game/desk_actions.hpp"
#include "cli/console/parser.hpp"
#include "cli/json.hpp"
#include "formats/le.hpp"
#include "formats/textd.hpp"
#include "ui/league_pairings.hpp"
#include "ui/club_info.hpp"
#include "ui/mailbox_state.hpp"
#include "ui/outgoing_transfer.hpp"
#include "ui/preparation.hpp"
#include "ui/manager.hpp"
#include "ui/setup.hpp"
namespace bmh::cli::console {
// How a matchday runs (01-grundlagen 7, 07-spieltag 3.2): stepped = the clock moves only on
// Match.Step / Match.Run and the managers can intervene; instant = the day runs through and
// only the results are printed.
enum class TimeMode { stepped, instant };
struct Options {
std::filesystem::path data; // the BMH directory (data files)
std::filesystem::path save_directory; // where LoadGame/Save look; empty = data
std::uint32_t seed = 1; // Watcom seed of the session (determinism)
bool json = false; // one JSON object per output line
TimeMode time = TimeMode::stepped;
};
// A command's parameter as ListOptions/Help show it and the argument check uses it.
struct Param {
enum class Type { integer, boolean, text, choice };
std::string name;
Type type = Type::integer;
long long min = 0, max = 0; // integer range; text: max length (0 = none)
bool optional = false;
std::vector<std::string> choices; // choice: allowed names (index = number)
std::string display; // overrides the generated "name:type" text
};
struct Spec {
std::string window; // "*" = every window
std::string name; // canonical display name, e.g. "ListOptions"
std::vector<Param> params;
std::string description;
bool changes = false; // changes the game: only the active player
};
class Console {
public:
// `write` receives every finished output line (without the newline).
Console(Options options, std::function<void(const std::string&)> write);
~Console();
// Prints the first status lines. Call once before feeding input.
void start();
// One line of input. Command lines are collected until "go.". Returns false once the
// session has ended (Quit); later input is ignored.
bool feed(std::string_view line);
bool ended() const { return ended_; }
// Whose turn it is (1-4, 0 = All during a live match), the open window and the player an
// open question belongs to (0 = none): what the multi-seat mailbox (--seats) waits on.
int active_player() const { return player_; }
const std::string& window() const { return window_; }
int question_player() const { return question_ ? question_->player : 0; }
// Every finished output line with its meaning, independent of text or JSON format: the
// class character (#, |, +, !, ?, i, ~, c, >), the player it belongs to (0 = All), the
// plain text and the formatted line as written. The seat hub (several clients in one game)
// routes lines by these instead of parsing them.
struct LineInfo {
char cls = 0;
int player = 0;
std::string text;
std::string line;
};
void set_line_observer(std::function<void(const LineInfo&)> observer) { observer_ = std::move(observer); }
// The input lines of the last executed block and its output, for --log / --replay.
// After start(): no input, the start output.
const std::vector<std::string>& last_block() const { return last_block_; }
const std::vector<std::string>& last_output() const { return last_output_; }
// All registered commands (for tests against docs/CLI_CONCEPT/commands.csv).
const std::vector<Spec>& specs() const { return specs_; }
// "window/Name" of every command that ran without an error (coverage, 10-agenten 3).
const std::set<std::string>& succeeded() const { return succeeded_; }
// The engine session (tests compare it with season_sim / save files).
const app::CareerSession& session() const { return *session_; }
struct Values; // bound arguments of one call (detail.hpp)
private:
struct Question {
int id = 0;
int player = 1;
std::string text;
std::vector<std::string> options;
std::string default_option; // the answer GoBack (right mouse button) gives
std::function<void(const std::string&)> on_answer;
};
struct ChatEntry {
int from = 0, to = 0;
std::string text;
};
using Handler = std::function<void(const Values&)>;
// registry (one function per command file)
void add(Spec spec, Handler handler);
void register_global_commands();
void register_start_commands(); // windows_start.cpp
void register_file_commands(); // windows_start.cpp: NewGame.LoadGame, LoadGame, SaveGame
void register_desk_commands(); // windows_desk.cpp: Desktop, Mailbox
void register_table_commands(); // windows_tables.cpp: LeagueTable, Fixtures
void register_club_commands(); // windows_club.cpp: Tactics, Training, TrainingCamp
void register_money_commands(); // windows_money.cpp: Bank, Stadium, Toto
void register_office_commands(); // windows_office.cpp: Advertising, Contracts, Settings
void register_squad_commands(); // windows_squad.cpp: Lineup, Lineup.Pitch, PlayerCard
void register_transfer_commands(); // windows_transfer.cpp: Transfer, Transfer.Negotiate
void register_info_commands(); // windows_info.cpp: TeamInfo, HighScore
void register_match_commands(); // windows_match.cpp: Match (stage 4)
void register_friendly_commands(); // windows_friendly.cpp: Friendlies (stage 5)
void register_reschedule_commands(); // windows_reschedule.cpp: Reschedule (stage 5)
void register_balance_commands(); // windows_balance.cpp: Balance (stage 5)
void register_environment_commands(); // windows_environment.cpp: Environment (stage 5)
void register_state_commands(); // windows_state.cpp: State(view), structured data (stage 2.5)
void register_advice_commands(); // windows_state.cpp: Advice, Scoreboard (learning agents)
const Spec* find(std::string_view window, std::string_view key) const;
// execution
void execute_block();
void execute(const Command& cmd);
Values bind(const Spec& spec, const Command& cmd) const;
// output
void emit(char cls, const std::string& text, Json data = nullptr);
void emit_table(const std::vector<std::string>& header, const std::vector<std::vector<std::string>>& rows);
void flush_status();
std::string option_line(const Spec& spec) const;
std::vector<const Spec*> window_specs(bool include_locked) const;
// A TEXTD text by its index (docs/formats/textd_inventory.csv), as UTF-8.
std::string text(int index) const;
// windows and questions
void set_window(std::string window, int player);
// Opens a sub window; GoBack returns to the window it was opened from.
void open_window(std::string window);
// Leaves the current sub window (GoBack). False if there is nothing to go back to.
bool close_window();
void ask(std::string text, std::vector<std::string> options, std::string default_option,
std::function<void(const std::string&)> on_answer, std::string text_key = {});
// start (windows_start.cpp)
std::string options_text() const;
void new_game_continue();
void begin_selection(int slot);
void confirm_selection();
void finish_career();
void load_game(const std::filesystem::path& path);
void save_game(const std::filesystem::path& path, bool overwrite);
std::filesystem::path save_directory() const;
std::string shown_directory() const;
std::filesystem::path browser_file(const std::string& name) const;
int resolve_club(const std::string& text) const; // master club index
// desk (windows_desk.cpp)
int active_slot() const;
// The desk views (Advice, State) show the manager on turn; a seat that is not on turn
// would read another club as its own (learning session, October 2026), so it is refused.
void own_view_only(int player, const std::string& command) const;
ui::DeskState desk() const;
// The views of the action windows (training, bank, ...) of the active manager.
ui::PreparationState prep() const;
// Runs one engine action of an action window; `ok` is the dispatch result.
void require_engine(bool ok, const std::string& what, const std::string& error);
void enter_desktop();
void open_menu(int menu);
void kickoff();
void finish_kickoff(const ui::DeskState& before, const TurnAdvanceResult& advanced, const std::string& error);
// stage 4 (windows_match.cpp): the kickoff on the engine thread and its pauses
void start_matchday(const ui::DeskRequest& request, const ui::DeskState& before);
void resume_matchday(); // let the engine run until its next pause or the end
void engine_returned(); // the engine waits (minute, question) or has finished
void show_match_pause();
void stop_matchday(); // abort and join a started day (Quit, destructor)
bool loan_return_offer_active() const;
bool loan_return_modal_active() const;
std::optional<app::CareerSession::TransferOfferEditorDispatch> dispatch_loan_return_offer(
const ui::OutgoingTransferRequest&, const HumanBuyerSaleHooks&, std::string&,
const app::TransferOfferTeamInfoPresenter&, const app::TransferOfferPlayerInfoPresenter&);
void finish_loan_return_offer();
std::string match_status() const;
struct EngineRun;
std::shared_ptr<EngineRun> run_; // shared_ptr: EngineRun is complete only in windows_match.cpp
void report_new_mail();
void flush_info();
// Engine hooks of a new session (cup draws -> Info.CupDraw).
void install_hooks();
// tables (windows_tables.cpp)
void show_league_table();
void open_fixtures();
void show_fixtures();
void fixtures_action(LeaguePairingsAction kind, int value = -1);
bool quiet_fixtures_ = false; // SetMatchday pages through without printing each page
bool squad_view_b_ = false; // Lineup: DATEN-B (age, skills, career numbers) instead of DATEN-A
Options options_;
std::function<void(const std::string&)> write_;
std::function<void(const LineInfo&)> observer_;
std::vector<Spec> specs_;
std::map<std::string, Handler> handlers_; // window + "/" + key
// what Open(menu) does for the windows of the command files (menu_kind -> opener)
std::map<int, std::function<void()>> openers_;
// what GoBack does in windows whose closing is an engine step (Fixtures, Stadium)
std::map<std::string, std::function<void()>> closers_;
TextDb texts_;
LeImage exe_;
std::unique_ptr<app::CareerSession> session_;
uint64_t revision_ = 0; // CareerSession request revision
bool career_ = false; // a career is running (after finish or load)
ui::SetupOptions setup_;
std::string window_ = "NewGame";
int player_ = 1; // 1-4, 0 = All
std::vector<std::string> back_; // windows GoBack returns to
std::string printed_window_;
int printed_player_ = -1;
std::optional<Question> question_;
int next_question_ = 1;
std::vector<ChatEntry> chat_;
bool ended_ = false;
// manager selection: the original picker model for the player choosing (tab ranges,
// defaults), the confirmed choices and the draft of the current player
std::unique_ptr<ui::ManagerScreen> picker_;
std::vector<ui::ManagerChoice> confirmed_;
ui::ManagerChoice draft_;
// file windows
std::filesystem::path browse_directory_;
std::string selected_file_;
// info windows produced inside engine calls (cup draws), printed after the call
std::vector<std::function<void()>> pending_info_;
// mailbox: the messages of the last ListMessages (msg numbers refer to it) and the
// messages every player has already been told about
std::vector<ui::MailboxMessage> listed_mail_;
std::map<int, std::set<std::string>> seen_mail_;
// request ids of the engine calls that need increasing ids (advertising, contracts)
uint64_t next_request_id_ = 1;
// the open contract negotiation (Contracts.Negotiate)
struct Negotiation {
int row = -1, player_id = -1;
std::string name;
uint64_t quote_id = 0;
std::array<uint32_t, 4> demands{};
int years = -1; // offered term, -1 = no salary offer yet
uint32_t salary = 0; // offered monthly salary
std::array<uint8_t, 7> bonuses{};
};
std::optional<Negotiation> negotiation_;
// squad windows (windows_squad.cpp)
void show_player_card();
void show_player_statistics(int chart, bool absolute);
void show_pitch();
void show_pairs();
// the open offer editor of Transfer.Negotiate
std::optional<ui::OutgoingTransferEditorState> offer_editor_;
bool offer_submitted_ = false; // a bid of this editor stands (closing does not withdraw it)
// the bank's credit editor draft (Bank.Credit)
std::optional<BankCreditDraft> credit_draft_;
int credit_counterparty_ = 0; // Bank.Credit: 0 the bank, else the lending manager + 1
// the friendly offer of the Friendlies window
std::optional<FriendlyBookingQuote> friendly_quote_;
std::optional<BalancePlanDraft> balance_draft_; // the Balance window (BalanceFromGame2 locals)
// the open club information (TeamInfo)
std::optional<ui::ClubInfoProjection> team_info_;
int card_row_ = -1; // the squad row of the open player card
int chart_ = 0; // PlayerCard.Statistics: Value, Form, Strength, Total
bool chart_absolute_ = true;
// tables
int table_league_ = -1;
std::optional<ui::LeaguePairingsState> pairings_;
std::set<std::string> succeeded_;
std::vector<std::string> pending_; // command lines before "go."
std::vector<std::string> last_block_, last_output_;
};
} // namespace bmh::cli::console
+96
View File
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Helpers shared by the console's command files (console.cpp and windows_*.cpp). Not part of
// the console's public interface.
#include <map>
#include <string>
#include <vector>
#include "cli/console/console.hpp"
namespace bmh::cli::console::detail {
// A rejected command: "! <code>: <message> [textKey: <key>]" (01-grundlagen 6). A failed
// command changes neither the game nor the random sequence: handlers check everything they
// can before they call the engine, and engine calls that fail leave the session unchanged.
struct CliError {
std::string code, message, text_key;
};
// The eight tactic settings (manager record +0xd2..+0xd9) by their place on the original
// board KB/11.VGA (hitboxes Tactics_Click_RuntimeField..Tactics_Click_RuntimeField6, src/ui/TACTICS.md) and the manual H2 p. 71.
// Item 0 is the attitude the match engine uses for a human side (match_engine.cpp
// update_attitude): fixed for the whole match unless the assistant controls it
// (SetAutomation(Tactics)); computer sides play 2 at home and 1 away and go up when behind.
// Items 1-3 and 5-6: the exact meaning of each diagram is not proven, the names say where.
inline constexpr const char* kTacticNames[8] = {
"attitude 0 defensive .. 3 offensive",
"pass/shot diagram, lower field (lower middle)",
"pass/shot diagram, lower field (upper middle)",
"pass/shot diagram, lower field (left)",
"flat or high balls (stick figures)",
"top right diagram, left (wingers hang back / build-up from behind)",
"top right diagram, right (wingers hang back / build-up from behind)",
"emphasis (EINSATZ!!!) 0..11",
};
[[noreturn]] inline void fail(std::string code, std::string message, std::string text_key = {}) {
throw CliError{std::move(code), std::move(message), std::move(text_key)};
}
// Parameter constructors for the registry.
Param integer(std::string name, long long min, long long max, bool optional = false);
Param boolean(std::string name, bool optional = false);
Param text(std::string name, long long max_length = 0, bool optional = false);
// enum: the names (case/'.'/'_' ignored) or their index
Param choice(std::string name, std::vector<std::string> choices, bool optional = false);
std::string on_off(bool v);
std::string lower(std::string s);
// For name comparisons: lower case, also the German capitals Ä Ö Ü in UTF-8.
std::string fold(std::string s);
// Text from the engine as UTF-8. Most projections keep the original ISO 646-DE bytes
// ("M]NCHEN"), some already convert (cup draw names, results). The original encoding has no
// bytes above 0x7f, so a string with such bytes is taken as UTF-8 already.
std::string utf8(std::string_view text);
// "2027-07-01" (the concept's date type)
std::string date_text(int day, int month, int year);
// Money as whole euros without separators (01-grundlagen 2.1)
std::string money(long long value);
// A player of a list a command can refer to (01-grundlagen 1.3).
struct PlayerRef {
int row = -1; // row in the window's list (squad slot)
int id = -1; // player id of the game state (stable)
std::string name; // UTF-8
};
// Resolves id:<n>, row:<n> or a (unique part of a) name against `players`; returns the
// index into `players`. E_BAD_ARGUMENT if nothing fits, E_AMBIGUOUS with candidates.
size_t resolve_player(const std::string& reference, const std::vector<PlayerRef>& players);
// The window a desk menu (menu_kind 0-29) opens, named as in 02-fenster 6; 63 = Mailbox.
// Empty for other numbers.
std::string menu_window(int menu);
// The menu number of a window name (canonical comparison), -1 if none.
int menu_of_window(std::string_view name);
} // namespace bmh::cli::console::detail
namespace bmh::cli::console {
// The arguments of one call, bound to the parameter names and already type-checked.
struct Console::Values {
std::map<std::string, Arg> args; // canonical parameter name -> argument
const Spec* spec = nullptr;
int player = 0; // the @n of the call (0 = none)
bool has(const std::string& name) const { return args.count(canonical(name)) != 0; }
long long integer(const std::string& name, long long fallback = 0) const;
bool boolean(const std::string& name, bool fallback = false) const;
std::string text(const std::string& name, std::string fallback = {}) const;
// the index of an enum argument in its parameter's choices (-1 = absent)
int choice(const std::string& name) const;
};
} // namespace bmh::cli::console
+166
View File
@@ -0,0 +1,166 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "cli/console/parser.hpp"
#include <cctype>
#include <charconv>
namespace bmh::cli::console {
namespace {
std::string_view trim(std::string_view s) {
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.front()))) s.remove_prefix(1);
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back()))) s.remove_suffix(1);
return s;
}
bool name_char(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '.' || c == '_'; }
// Splits the text between the parentheses at top-level commas: commas inside "quotes" or
// [brackets] do not split.
std::vector<std::string> split_args(std::string_view inner) {
std::vector<std::string> parts;
std::string current;
bool quoted = false;
int depth = 0;
for (size_t i = 0; i < inner.size(); ++i) {
const char c = inner[i];
if (quoted) {
current += c;
if (c == '\\' && i + 1 < inner.size()) current += inner[++i];
else if (c == '"') quoted = false;
continue;
}
if (c == '"') quoted = true;
else if (c == '[') ++depth;
else if (c == ']') {
if (--depth < 0) throw ParseError("unbalanced ']'");
} else if (c == ',' && depth == 0) {
parts.push_back(current);
current.clear();
continue;
}
current += c;
}
if (quoted) throw ParseError("unterminated string");
if (depth != 0) throw ParseError("unbalanced '['");
parts.push_back(current);
return parts;
}
Arg parse_arg(std::string_view text) {
Arg arg;
text = trim(text);
if (text.empty()) throw ParseError("empty argument");
// name=value: a plain name before '=' (no quotes or brackets in front of it)
if (text.front() != '"' && text.front() != '[') {
const size_t eq = text.find('=');
if (eq != std::string_view::npos) {
const std::string_view name = trim(text.substr(0, eq));
bool plain = !name.empty();
for (char c : name) plain = plain && name_char(c);
if (plain) {
arg.name = canonical(name);
text = trim(text.substr(eq + 1));
if (text.empty()) throw ParseError("missing value for " + std::string(name));
}
}
}
if (text.front() == '"') {
if (text.size() < 2 || text.back() != '"') throw ParseError("unterminated string");
arg.quoted = true;
const std::string_view body = text.substr(1, text.size() - 2);
for (size_t i = 0; i < body.size(); ++i) {
if (body[i] == '\\' && i + 1 < body.size()) {
arg.text += body[++i];
} else if (body[i] == '"') {
throw ParseError("unescaped quote in string");
} else {
arg.text += body[i];
}
}
} else {
arg.text = std::string(text);
}
return arg;
}
} // namespace
std::string canonical(std::string_view name) {
std::string key;
for (char c : name)
if (c != '.' && c != '_') key += char(std::tolower(static_cast<unsigned char>(c)));
return key;
}
LineKind classify_line(std::string_view line) {
line = trim(line);
if (line.empty() || line.substr(0, 2) == "//") return LineKind::skip;
const std::string key = [&] {
std::string k;
for (char c : line) k += char(std::tolower(static_cast<unsigned char>(c)));
return k;
}();
if (key == "go.") return LineKind::go;
if (key == "clear.") return LineKind::clear;
return LineKind::command;
}
Command parse_command(std::string_view line) {
Command cmd;
line = trim(line);
if (!line.empty() && line.front() == '@') {
size_t i = 1;
while (i < line.size() && std::isdigit(static_cast<unsigned char>(line[i]))) ++i;
if (i == 1) throw ParseError("'@' needs a player number");
int player = 0;
std::from_chars(line.data() + 1, line.data() + i, player);
if (player < 1 || player > 4) throw ParseError("player must be 1-4");
cmd.player = player;
line = trim(line.substr(i));
}
size_t n = 0;
while (n < line.size() && name_char(line[n])) ++n;
if (n == 0) throw ParseError("expected a command name");
cmd.name = std::string(line.substr(0, n));
cmd.key = canonical(cmd.name);
if (cmd.key.empty()) throw ParseError("expected a command name");
std::string_view rest = trim(line.substr(n));
if (rest.empty()) return cmd;
if (rest.front() != '(' || rest.back() != ')') throw ParseError("arguments must be written as Name(a, b)");
const std::string_view inner = trim(rest.substr(1, rest.size() - 2));
if (inner.empty()) return cmd;
bool named_seen = false;
for (const std::string& part : split_args(inner)) {
Arg arg = parse_arg(part);
if (arg.name.empty() && named_seen) throw ParseError("positional argument after a named one");
named_seen = named_seen || !arg.name.empty();
cmd.args.push_back(std::move(arg));
}
return cmd;
}
std::optional<long long> to_int(const Arg& arg) {
if (arg.quoted) return std::nullopt;
std::string digits;
for (char c : arg.text)
if (c != '_') digits += c;
if (digits.empty()) return std::nullopt;
long long value = 0;
const char* begin = digits.data();
if (*begin == '+') ++begin;
const auto [ptr, ec] = std::from_chars(begin, digits.data() + digits.size(), value);
if (ec != std::errc{} || ptr != digits.data() + digits.size()) return std::nullopt;
return value;
}
std::optional<bool> to_bool(const Arg& arg) {
if (arg.quoted) return std::nullopt;
const std::string v = canonical(arg.text);
if (v == "true" || v == "yes" || v == "on" || v == "1") return true;
if (v == "false" || v == "no" || v == "off" || v == "0") return false;
return std::nullopt;
}
} // namespace bmh::cli::console
+57
View File
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The command line syntax of the console language (docs/CLI_CONCEPT/01-grundlagen.md, 1):
//
// [@<player>] Name [ ( Argument {, Argument} ) ]
//
// Names ignore case and the characters '.' and '_' ("ListOptions" = "List.Options" =
// "list_options"). Arguments are positional or named (name=value; named ones only at the
// end), separated by commas at the top level; strings are "quoted" (\" and \\ escaped) or a
// single word, lists use [a, b]. The parser only splits a line; the types are checked against
// the command's parameter list by the console (E_BAD_ARGUMENT before anything happens).
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
namespace bmh::cli::console {
// One argument as written: `text` without the surrounding quotes, `quoted` if it was a
// "string", `name` empty for a positional argument.
struct Arg {
std::string name;
std::string text;
bool quoted = false;
};
struct Command {
int player = 0; // the @n prefix (1-4), 0 = the active player
std::string name; // as written
std::string key; // canonical(name)
std::vector<Arg> args;
};
class ParseError final : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
// Lower case without '.' and '_': the key commands are compared with.
std::string canonical(std::string_view name);
// Splits one command line. Throws ParseError with a short reason on a syntax error.
Command parse_command(std::string_view line);
// What a line of input is, before parsing: a command, the block confirmation "go.", the
// block reset "clear.", or nothing (empty line or // comment).
enum class LineKind { command, go, clear, skip };
LineKind classify_line(std::string_view line);
// Value conversion for the parameter check. Integers allow '_' as thousands separator and a
// sign; booleans accept true/false/yes/no/on/off/1/0. Quoted text is never a number/bool.
std::optional<long long> to_int(const Arg& arg);
std::optional<bool> to_bool(const Arg& arg);
} // namespace bmh::cli::console
+91
View File
@@ -0,0 +1,91 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
// The balance plan (menu 28, mode III; docs/CLI_CONCEPT/06-verein.md 11, H2 p. 26-27): the
// projected income and expenses of the business year in three views, every item can be
// changed; leaving the window stores the plan figure the DFB gets on the 16th Bundesliga
// matchday.
//
// The screen logic is the engine's (src/game/balance_plan.hpp, a port of BalanceFromGame2); the
// console keeps the screen's draft while the window is open and closes it on GoBack.
#include <algorithm>
#include "app/desktop_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/balance_plan.hpp"
#include "game/messages.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// row names in screen order (labels BalancePlan_DrawRows_TextPointer5 and BalancePlan_DrawRows_TextPointer4)
const std::vector<std::string> kRowNames = {
"IncomeShirt", "IncomeBoards", "IncomeTv", "IncomeGate", "IncomePeriphery", "IncomeRentInterest",
"IncomeMisc", "ExpenseSalaries", "ExpenseStadium", "ExpenseYouth", "ExpenseCoTrainer", "ExpenseDoctor",
"ExpensePhysio", "ExpenseTrainingCamp", "ExpenseFanCare", "ExpensePr", "ExpenseInterest", "ExpenseMisc",
"LeagueHomeGames", "OtherHomeGames", "AverageGate", "TicketPrice", "GateSoFar", "Account"};
const char* const kViews[] = {"SoFar", "Real", "Future"};
} // namespace
void Console::register_balance_commands() {
auto show = [this] {
const BalancePlanDraft& d = *balance_draft_;
std::vector<std::vector<std::string>> rows;
for (int i = 0; i < kBalanceRows; i++) {
const bool money_row = i < kBalanceItems || i == kBalanceAccount;
rows.push_back({kRowNames[size_t(i)], money_row ? money(d.rows[size_t(i)]) : std::to_string(d.rows[size_t(i)]),
balance_row_maximum(d, i) >= 0 ? "yes" : "no"});
}
emit('i', std::string("view ") + kViews[int(d.view)] + ", " + std::to_string(d.months_left) + " months left");
emit_table({"Item", "Value", "Changeable"}, rows);
if (d.depreciation != 0) emit('i', "depreciation " + money(d.depreciation));
emit('i', std::string(d.total < 0 ? "planned loss " : "planned profit ") + money((long long)(d.total < 0 ? -d.total : d.total)));
};
openers_[28] = [this, show] {
balance_draft_ = app::BalanceActions(*session_).open_draft(active_slot());
open_window("Balance");
show();
};
closers_["Balance"] = [this] {
const BalancePlanDraft d = *balance_draft_;
balance_draft_.reset();
const bool warning = app::BalanceActions(*session_).close_draft(d, revision_);
close_window();
// the original's message box BalancePlan_BalanceFromGame_TextPointer2 (the plan is stored nevertheless)
if (warning) emit('i', bmh::message_text(session_->state(), ::bmh::layout::BalancePlan_BalanceFromGame_TextPointer2));
emit('+', "balance plan stored: " + money((long long)d.total));
};
add({"Balance", "ShowBalance", {}, "all items, the view and the planned profit or loss", false}, [show](const Values&) { show(); });
add({"Balance", "SetBalanceView", {choice("view", {kViews[0], kViews[1], kViews[2]})}, "left button: so far / real / future", false},
[this, show](const Values& v) {
while (int(balance_draft_->view) != v.choice("view")) app::BalanceActions(*session_).cycle_draft(*balance_draft_);
show();
});
std::vector<std::string> editable;
for (int i = 0; i < 0x16; i++)
if (balance_row_maximum(BalancePlanDraft{}, i) >= 0) editable.push_back(kRowNames[size_t(i)]);
add({"Balance", "SetBalanceItem", {choice("item", editable), integer("value", 0, 30000000)}, "change a planned value (views Real and Future)", false},
[this, show, editable](const Values& v) {
const std::string& name = editable[size_t(v.choice("item"))];
const int row = int(std::find(kRowNames.begin(), kRowNames.end(), name) - kRowNames.begin());
switch (app::BalanceActions(*session_).edit_draft(*balance_draft_, row, int32_t(v.integer("value")))) {
case BalanceEditStatus::changed: break;
case BalanceEditStatus::view_so_far: fail("E_RULE", "Bitte den linken Button auf REAL oder ZUKUNFT stellen (SetBalanceView)");
case BalanceEditStatus::out_of_range:
fail("E_BAD_ARGUMENT", name + " goes up to " + std::to_string(balance_row_maximum(*balance_draft_, row)));
default: fail("E_RULE", name + " cannot be changed");
}
show();
});
add({"Balance", "TakeActuals", {}, "\"Werte akt.\": drop the own changes, back to the game's figures", false}, [this, show](const Values&) {
app::BalanceActions(*session_).reset_draft(*balance_draft_);
show();
});
}
} // namespace bmh::cli::console
+334
View File
@@ -0,0 +1,334 @@
// SPDX-License-Identifier: GPL-3.0-only
// The club windows of docs/CLI_CONCEPT/06-verein.md: Tactics (menu 18), Training (menu 16)
// and TrainingCamp (menu 15). The views come from CareerSession::preparation_projection, the
// changes go through dispatch_tactics / dispatch_training / dispatch_training_camp with the
// same requests the SDL screens build (src/ui/tactics.cpp, training.cpp, training_camp.cpp).
#include <algorithm>
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// 06-verein 2: the value range of the eight tactics settings (H2 p. 71)
constexpr int kTacticMax[8] = {3, 3, 3, 3, 1, 1, 1, 11};
const std::vector<std::string> kTypes = {"TOR", "ABW", "MIT", "STU"};
const std::vector<std::string> kAreas = {"Fitness", "Skill", "Corner", "FreeKick", "Tackling", "Pass", "Shot", "Speed", "Game"};
constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU (TrainingPlayer::position 0-3)
// TEXTD indices (docs/formats/textd_inventory.csv)
constexpr int kCampQualityTitles = 362; // campPitchQuality .. campAccommodation (362-365)
constexpr int kCampResorts = 371; // campResortLodz .. (371-378), names differ per edition
constexpr int kCampPlayersReturnHappy = 1259;
constexpr int kCampRecentlyVisited = 1265;
constexpr int kCampBoardDeniesFurtherVisits = 1266;
std::string balls(int n) { return std::string(size_t(std::max(0, n)), 'o'); }
} // namespace
void Console::register_club_commands() {
// --- Tactics (06-verein 2) ------------------------------------------------------------
auto show_tactics = [this] {
const ui::TacticsState t = prep().tactics;
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 8; ++i)
rows.push_back({std::to_string(i), detail::kTacticNames[i], std::to_string(t.values[i]), std::to_string(kTacticMax[i])});
emit_table({"Item", "Setting", "Value", "Max"}, rows);
emit('i', std::string("assistant attitude control: ") + on_off(t.assistant_attitude != 0));
};
openers_[18] = [this, show_tactics] {
open_window("Tactics");
show_tactics();
};
add({"Tactics", "ShowTactics", {}, "the eight settings with value and maximum", false}, [show_tactics](const Values&) { show_tactics(); });
auto set_tactic = [this, show_tactics](int item, int value) {
const ui::TacticsState t = prep().tactics;
if (value < 0 || value > kTacticMax[item])
fail("E_BAD_ARGUMENT", "item " + std::to_string(item) + " takes 0.." + std::to_string(kTacticMax[item]));
if (t.values[size_t(item)] == value) {
emit('+', "item " + std::to_string(item) + " already " + std::to_string(value));
return;
}
ui::TacticsRequest req;
req.kind = ui::TacticsRequestKind::set_tactic;
req.manager_slot = t.manager_slot;
req.runtime_club = t.runtime_club;
req.revision = revision_;
req.index = item;
req.desired_value = value;
// the offensive/defensive arrows switch the assistant's attitude control off
if (item == 0) req.desired_assistant_attitude = 0;
std::string error;
require_engine(session_->dispatch_tactics(req, revision_, error), "tactics", error);
emit('+', "item " + std::to_string(item) + " = " + std::to_string(value));
};
add({"Tactics", "SetTactic", {integer("item", 0, 7), integer("value", 0, 11)}, "set a value directly (item 0 ends the assistant's D/O control)", true},
[set_tactic](const Values& v) { set_tactic(int(v.integer("item")), int(v.integer("value"))); });
add({"Tactics", "CycleTactic", {integer("item", 0, 6)}, "a click: value + 1, after the maximum 0", true}, [this, set_tactic](const Values& v) {
const int item = int(v.integer("item"));
const int value = prep().tactics.values[size_t(item)];
set_tactic(item, value >= kTacticMax[item] ? 0 : value + 1);
});
// --- Training (06-verein 3) -----------------------------------------------------------
auto training = [this] {
const auto p = prep();
if (!p.training) fail("E_MODE_LOCKED", "there is no training in mode I");
return *p.training;
};
auto training_request = [this](const ui::TrainingState& t, ui::TrainingRequestKind kind) {
ui::TrainingRequest r;
r.kind = kind;
r.manager_slot = t.manager_slot;
r.runtime_club = t.runtime_club;
r.revision = revision_;
r.desired_types = t.types;
r.desired_areas = t.areas;
r.desired_automation = t.automation;
return r;
};
auto dispatch_training = [this](const ui::TrainingRequest& r) {
std::string error;
require_engine(session_->dispatch_training(r, revision_, error), "training", error);
};
auto players_of = [](const ui::TrainingState& t) {
std::vector<PlayerRef> refs;
for (const auto& p : t.players) refs.push_back({p.row, p.player_id, utf8(p.name)});
return refs;
};
auto show_training = [this, training] {
const ui::TrainingState t = training();
int type_sum = 0, fitness = 0, other = 0;
std::vector<std::vector<std::string>> types, areas;
for (size_t i = 0; i < 4; ++i) {
type_sum += t.types[i];
types.push_back({kTypes[i], std::to_string(t.types[i]), balls(t.types[i])});
}
for (size_t i = 0; i < 9; ++i) {
(i < 2 ? fitness : other) += t.areas[i];
areas.push_back({kAreas[i], std::to_string(t.areas[i]), balls(t.areas[i])});
}
emit_table({"Type", "Balls", ""}, types);
emit_table({"Area", "Balls", ""}, areas);
emit('i', "balls: type=" + std::to_string(type_sum) + "/8 areas=" + std::to_string(other) + "/18 (Fitness+Skill=" +
std::to_string(fitness) + "/4)" + (other > 14 ? " [specialTraining]" : ""));
std::vector<std::vector<std::string>> players;
for (const auto& p : t.players)
players.push_back({"row:" + std::to_string(p.row), "id:" + std::to_string(p.player_id), utf8(p.name),
p.position >= 0 && p.position < 4 ? text(kPositionNames + p.position) : "?", std::to_string(p.intensity),
std::to_string(p.focus)});
emit_table({"Row", "Id", "Player", "Pos", "Intensity", "Focus"}, players);
emit('i', "automation bits: " + std::to_string(t.automation & 0x1f) + (t.needs_initialization() ? " (not initialized)" : ""));
};
openers_[16] = [this, training, training_request, dispatch_training, show_training] {
const ui::TrainingState t = training();
open_window("Training");
// Initialize: the first opening initializes the plan (06-verein 3)
if (t.needs_initialization()) {
auto r = training_request(t, ui::TrainingRequestKind::initialize);
r.desired_automation = 0x9f;
dispatch_training(r);
emit('+', "Training initialized");
}
show_training();
};
add({"Training", "ShowTraining", {}, "types, areas, sums, players, automation", false}, [show_training](const Values&) { show_training(); });
// The engine accepts 1-3 balls (CareerSession::dispatch_training, valid_plan); the
// concept's 0..3 would leave a field empty, which the original screen does not allow.
add({"Training", "SetTrainingType", {choice("type", kTypes), integer("balls", 1, 3)}, "balls of a player type (sum <= 8)", true},
[this, training, training_request, dispatch_training](const Values& v) {
const ui::TrainingState t = training();
const int type = v.choice("type"), value = int(v.integer("balls"));
if (t.types[size_t(type)] == value) {
emit('+', kTypes[size_t(type)] + " already " + std::to_string(value));
return;
}
auto r = training_request(t, ui::TrainingRequestKind::set_type);
r.index = type;
r.value = value;
r.desired_types[size_t(type)] = uint8_t(value);
r.desired_automation &= uint8_t(~2);
int sum = 0;
for (auto b : r.desired_types) sum += b;
if (sum > 8) fail("E_RULE", "the four player types may have 8 balls together (would be " + std::to_string(sum) + ")");
dispatch_training(r);
emit('+', kTypes[size_t(type)] + " = " + std::to_string(value));
});
add({"Training", "SetTrainingArea", {choice("area", kAreas), integer("balls", 1, 3)}, "balls of a training area (F+S <= 4, rest <= 18)", true},
[this, training, training_request, dispatch_training](const Values& v) {
const ui::TrainingState t = training();
const int area = v.choice("area"), value = int(v.integer("balls"));
if (t.areas[size_t(area)] == value) {
emit('+', kAreas[size_t(area)] + " already " + std::to_string(value));
return;
}
auto r = training_request(t, ui::TrainingRequestKind::set_area);
r.index = area;
r.value = value;
r.desired_areas[size_t(area)] = uint8_t(value);
r.desired_automation &= uint8_t(~4);
int fitness = 0, other = 0;
for (size_t i = 0; i < 9; ++i) (i < 2 ? fitness : other) += r.desired_areas[i];
if (fitness > 4) fail("E_RULE", "Fitness and Skill may have 4 balls together (would be " + std::to_string(fitness) + ")");
if (other > 18) fail("E_RULE", "the seven other areas may have 18 balls together (would be " + std::to_string(other) + ")");
dispatch_training(r);
emit('+', kAreas[size_t(area)] + " = " + std::to_string(value));
});
Param player = detail::text("player");
player.display = "player:Player";
add({"Training", "SetPlayerIntensity", {player, integer("intensity", 1, 3)}, "training intensity of a player", true},
[this, training, training_request, dispatch_training, players_of](const Values& v) {
const ui::TrainingState t = training();
const auto& p = t.players[resolve_player(v.text("player"), players_of(t))];
const int value = int(v.integer("intensity"));
if (p.intensity == value) {
emit('+', utf8(p.name) + " already " + std::to_string(value));
return;
}
auto r = training_request(t, ui::TrainingRequestKind::set_player_intensity);
r.index = p.row;
r.player_id = p.player_id;
r.value = value;
r.desired_automation &= uint8_t(~8);
dispatch_training(r);
emit('+', utf8(p.name) + ": intensity " + std::to_string(value));
});
add({"Training", "CyclePlayerFocus", {player}, "the player's focus symbol: next focus", true},
[this, training, training_request, dispatch_training, players_of](const Values& v) {
const ui::TrainingState t = training();
const auto& p = t.players[resolve_player(v.text("player"), players_of(t))];
auto r = training_request(t, ui::TrainingRequestKind::set_player_focus);
r.index = p.row;
r.player_id = p.player_id;
r.value = (int(p.focus) + 1) % 8;
dispatch_training(r);
emit('+', utf8(p.name) + ": focus " + std::to_string(r.value));
});
add({"Training", "SetTrainingAutomation", {integer("index", 0, 4), boolean("on")}, "one automation bit (D p. 109)", true},
[this, training, training_request, dispatch_training](const Values& v) {
const ui::TrainingState t = training();
const int index = int(v.integer("index"));
const bool on = v.boolean("on");
const uint8_t mask = uint8_t(1u << index);
if (((t.automation & mask) != 0) == on) {
emit('+', "automation bit " + std::to_string(index) + " already " + on_off(on));
return;
}
auto r = training_request(t, ui::TrainingRequestKind::set_automation);
r.index = index;
r.value = on ? 1 : 0;
r.desired_automation = uint8_t((t.automation & ~mask) | (on ? mask : 0));
dispatch_training(r);
emit('+', "automation bit " + std::to_string(index) + " " + on_off(on));
});
add({"Training", "InitializeTraining", {}, "the original initialization (only when needed)", true},
[this, training, training_request, dispatch_training](const Values&) {
const ui::TrainingState t = training();
if (!t.needs_initialization()) {
emit('+', "training is already initialized");
return;
}
auto r = training_request(t, ui::TrainingRequestKind::initialize);
r.desired_automation = 0x9f;
dispatch_training(r);
emit('+', "Training initialized");
});
// --- TrainingCamp (06-verein 4) -------------------------------------------------------
auto camp = [this] {
const auto p = prep();
if (!p.training_camp) fail("E_MODE_LOCKED", "no training camp available");
return *p.training_camp;
};
auto camp_request = [this](const ui::TrainingCampState& c, ui::TrainingCampRequestKind kind) {
ui::TrainingCampRequest r;
r.kind = kind;
r.manager_slot = c.manager_slot;
r.runtime_club = c.runtime_club;
r.revision = revision_;
r.focus = c.focus;
return r;
};
auto visits_text = [this](const ui::TrainingCampState& c) {
if (c.booked_this_week()) return "booked this week";
return c.visit_count() < 3 ? "" : "no visit possible";
};
auto show_camp = [this, camp, visits_text] {
const ui::TrainingCampState c = camp();
emit_table({"Slider", "Value"},
{{text(367), std::to_string(c.focus[0])}, {text(368), std::to_string(c.focus[1])},
{text(369), std::to_string(c.focus[2])}, {text(370), std::to_string(c.focus[3])}});
std::string state = visits_text(c);
emit('i', "visits this season: " + std::to_string(c.visit_count()) + "/3" + (state.empty() ? "" : " (" + state + ")") +
", balance " + money(c.balance));
};
openers_[15] = [this, camp, camp_request, show_camp] {
const ui::TrainingCampState c = camp();
open_window("TrainingCamp");
// SetTrainingCampFocus derives the fourth slider while drawing; the screen writes it back
// once when it differs (TrainingCampScreen::initialize_focus)
if (c.focus_normalization_required) {
std::string error;
require_engine(session_->dispatch_training_camp(camp_request(c, ui::TrainingCampRequestKind::set_focus), revision_, error),
"training camp", error);
}
show_camp();
};
add({"TrainingCamp", "ListResorts", {}, "the eight sports schools with stars and price", false}, [this, camp, visits_text](const Values&) {
const ui::TrainingCampState c = camp();
std::vector<std::vector<std::string>> rows;
for (size_t r = 0; r < 8; ++r)
rows.push_back({std::to_string(r), text(kCampResorts + int(r)), std::to_string(c.quality[r][0]), std::to_string(c.quality[r][1]),
std::to_string(c.quality[r][2]), std::to_string(c.quality[r][3]), money(c.prices[r])});
emit_table({"Resort", "Name", text(kCampQualityTitles), text(kCampQualityTitles + 1), text(kCampQualityTitles + 2),
text(kCampQualityTitles + 3), "Price"},
rows);
std::string state = visits_text(c);
emit('i', "visits this season: " + std::to_string(c.visit_count()) + "/3" + (state.empty() ? "" : " (" + state + ")"));
});
add({"TrainingCamp", "ShowCamp", {}, "sliders, recuperation, visits", false}, [show_camp](const Values&) { show_camp(); });
add({"TrainingCamp", "SetCampFocus", {integer("fitness", 0, 15), integer("skill", 0, 15), integer("game", 0, 15)},
"the three sliders; recuperation follows", true},
[this, camp, camp_request, show_camp](const Values& v) {
const ui::TrainingCampState c = camp();
auto r = camp_request(c, ui::TrainingCampRequestKind::set_focus);
r.focus[0] = uint8_t(v.integer("fitness"));
r.focus[1] = uint8_t(v.integer("skill"));
r.focus[2] = uint8_t(v.integer("game"));
r.focus[3] = uint8_t(15 - (r.focus[0] + r.focus[1] + r.focus[2]) / 3); // SetTrainingCampFocus
if (r.focus == c.focus) {
emit('+', "sliders unchanged");
return;
}
std::string error;
require_engine(session_->dispatch_training_camp(r, revision_, error), "training camp", error);
show_camp();
});
add({"TrainingCamp", "BookCamp", {integer("resort", 0, 7)}, "MACH ICH: book the sports school", true},
[this, camp, camp_request](const Values& v) {
const ui::TrainingCampState c = camp();
if (c.booked_this_week()) fail("E_RULE", text(kCampRecentlyVisited), "campRecentlyVisited");
if (c.visit_count() >= 3) fail("E_RULE", text(kCampBoardDeniesFurtherVisits), "campBoardDeniesFurtherVisits");
auto r = camp_request(c, ui::TrainingCampRequestKind::book);
r.resort = int(v.integer("resort"));
std::string error;
require_engine(session_->dispatch_training_camp(r, revision_, error), "training camp", error);
const ui::TrainingCampState after = camp();
switch (after.feedback) {
case ui::TrainingCampFeedback::insufficient_funds: fail("E_INSUFFICIENT_FUNDS", "the camp costs " + money(c.prices[size_t(r.resort)]));
case ui::TrainingCampFeedback::booked_this_week: fail("E_RULE", text(kCampRecentlyVisited), "campRecentlyVisited");
case ui::TrainingCampFeedback::visit_limit: fail("E_RULE", text(kCampBoardDeniesFurtherVisits), "campBoardDeniesFurtherVisits");
default: break;
}
emit('+', text(kCampResorts + r.resort) + " booked for " + money(c.prices[size_t(r.resort)]) + ". " + text(kCampPlayersReturnHappy));
});
}
} // namespace bmh::cli::console
+470
View File
@@ -0,0 +1,470 @@
// SPDX-License-Identifier: GPL-3.0-only
// The desk (docs/CLI_CONCEPT/04-schreibtisch.md): its displays, Open/Key, the widgets
// (ticket price, automation), Kickoff with the day's results, and the mailbox "Kicker".
#include <algorithm>
#include <utility>
#include "app/window_actions.hpp"
#include "app/desktop_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/schedule.hpp"
#include "ui/advertising.hpp"
#include "ui/desk_state.hpp"
#include "ui/desktop.hpp"
#include "ui/league_table.hpp"
#include "ui/matchday_results.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// 02-fenster 6: menu_kind -> window
const char* const kMenuWindows[30] = {
"LeagueTable", "Fixtures", "Strengths", "Lineup", "Achievements", "OtherGames", "Friendlies", "Reschedule",
"Calendar", "IndoorTable", "LoadGame", "SaveGame", "Kickoff", "Toto", "Bank", "TrainingCamp",
"Training", "Transfer", "Tactics", "Settings", "TopScorers", "Advertising", "Stadium", "Statistics",
"Environment", "FairPlay", "HighScore", "Contracts", "Balance", "NewPlayer"};
constexpr int kMailboxMenu = 63; // the mailbox shortcut (desk item kind 63)
// 02-fenster 5: the desk's keys (H2 S. 17). The training camp has no key (conflict with L).
const std::map<char, int> kKeys = {{'Z', 28}, {'T', 0}, {'S', 2}, {'X', 5}, {'K', 8}, {'G', 12}, {'B', 14}, {'I', 16},
{'E', 19}, {'W', 21}, {'U', 24}, {'N', 29}, {'L', 1}, {'A', 3}, {'F', 6}, {'H', 9},
{'O', 13}, {'M', 17}, {'D', 18}, {'C', 20}, {'Y', 22}, {'V', 27}};
// The ten warning lamps in the order of DeskState::warnings (Fill, 04-schreibtisch 2).
const char* const kLamps[10] = {"shares", "overdraft", "freeAdSlots", "specialTraining", "exhaustedPlayer",
"squadSize", "reserve", "tacticsEmphasis", "contracts", "license"};
// The five automations in the order of DeskState::automation (ManagerAutomation + manager * 5).
const std::vector<std::string> kAutomation = {"Lineup", "Substitution", "Tactics", "Marking", "Training"};
constexpr int kCompetitionNames = 579; // CupDraw_FormatError_ExecutableField6: competitionNameDfbCup, UefaCup, ...
const char* const kWeekdays[7] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
} // namespace
namespace detail {
std::string menu_window(int menu) {
if (menu >= 0 && menu < 30) return kMenuWindows[menu];
if (menu == kMailboxMenu) return "Mailbox";
return {};
}
int menu_of_window(std::string_view name) {
for (int i = 0; i < 30; ++i)
if (canonical(kMenuWindows[i]) == canonical(name)) return i;
if (canonical(name) == "mailbox") return kMailboxMenu;
return -1;
}
} // namespace detail
int Console::active_slot() const { return session_->desktop_projection(revision_).manager_slot; }
void Console::own_view_only(int player, const std::string& command) const {
if (player && player_ && player != player_)
detail::fail("E_NOT_YOUR_TURN", command + " shows the manager on turn (player " + std::to_string(player_) +
"), not yours - WaitTurn waits for your turn");
}
ui::DeskState Console::desk() const { return session_->desktop_projection(revision_); }
ui::PreparationState Console::prep() const { return session_->preparation_projection(revision_); }
// The engine says why it refused; the console passes it on (E_INSUFFICIENT_FUNDS for money).
// The engine reports refusals in two internal forms: snake_case codes of the session
// ("amount_unavailable") and, from the ported Source functions, "SubmitTransferBidSourceHumanBuyer: <reason>" for a
// case the port does not cover yet. Players and agents get readable text instead: codes
// with a known meaning get a sentence, other codes their words, and a FUN prefix marks an
// engine gap (the reason stays for the bug report, the internal name goes).
void Console::require_engine(bool ok, const std::string& what, const std::string& error) {
if (ok) return;
static const std::pair<const char*, const char*> kReadable[] = {
{"invalid_amount", "the amount is not valid (1 to 99,999,999)"},
{"amount_unavailable", "not that much money there (account balance or fixed deposit)"},
{"insufficient_funds", "not enough money"},
{"invalid_ticket_price", "the ticket price is out of range"},
{"invalid_share_count", "the number of shares is not valid"},
{"invalid_fund_count", "the number of fund shares is not valid"},
{"investment_limit", "the investment limit is reached"},
{"visit_limit", "no more visits possible"},
{"career_complete", "the game is over"},
{"toto_coupon_requires_eleven_matches", "the coupon needs a tip for all eleven matches"},
{"free_agent_loan_refused", "a free agent (Spielerberater) can only be bought, not loaned - the original refuses it too"},
};
std::string text = error.empty() ? std::string("refused") : error;
if (text.size() > 4 && text.compare(0, 3, "FUN") == 0) {
const size_t colon = text.find(": ");
if (colon != std::string::npos && colon < 12)
fail("E_ENGINE_GAP", what + ": this case is not ported yet (" + text.substr(colon + 2) + ")");
}
bool code = !text.empty();
for (const char c : text) code = code && ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_');
if (code) {
std::string readable;
for (const auto& [key, sentence] : kReadable)
if (text == key) readable = sentence;
if (readable.empty()) {
readable = text;
std::replace(readable.begin(), readable.end(), '_', ' ');
}
text = readable;
}
if (error.find("insufficient") != std::string::npos || error.find("funds") != std::string::npos)
fail("E_INSUFFICIENT_FUNDS", what + ": " + text);
fail("E_RULE", what + ": " + text);
}
// The desk of the active manager: window, player, and the messages not yet reported.
void Console::enter_desktop() {
const ui::DeskState d = desk();
set_window("Desktop", d.manager_slot + 1);
report_new_mail();
// Advertising places whose contract ran out stay blocked until the manager answers the
// renewal (CheckAdvertisingRenewal, on the click = ListAdOffers); the month-change message is easy
// to miss, so the desk repeats it (issue #44).
if (!d.national_team) {
try {
const ui::AdvertisingState a = ui::advertising_from_game(session_->state(), d.manager_slot, revision_);
std::string expired;
for (int slot = 0; slot < 16; ++slot)
if (a.offers[size_t(slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension)
expired += (expired.empty() ? "" : ", ") +
(slot < 14 ? "Board" + std::to_string(slot + 1) : std::string(slot == 14 ? "Shirt" : "Tv"));
if (!expired.empty())
emit('i', "advertising contracts ran out: " + expired + " (Open(Advertising), ListAdOffers(<slot>) renews or frees them)");
} catch (const std::exception&) {
}
}
}
// New messages show as "i" lines on the desk of the manager they belong to (04-schreibtisch 3).
// The mailbox has no read flag; the console remembers what it has shown per manager.
void Console::report_new_mail() {
const int slot = active_slot();
const ui::MailboxState mail = ui::mailbox_state_from_game(session_->state(), slot, revision_);
auto& seen = seen_mail_[slot];
for (const auto& m : mail.messages) {
const std::string key = std::to_string(m.date_counter) + "|" + m.text;
if (seen.insert(key).second) emit('i', "New message: " + m.text);
}
}
void Console::register_desk_commands() {
// --- Desktop: displays (04-schreibtisch 1) ---------------------------------------------
auto show_date = [this] {
const ui::DeskState d = desk();
std::vector<std::vector<std::string>> rows = {
{"date", date_text(d.date.day, d.date.month, d.date.year)},
{"weekday", d.date.weekday >= 0 && d.date.weekday < 7 ? kWeekdays[d.date.weekday] : "?"},
{"season", std::to_string(d.season_index + 1)},
{"seasonDay", std::to_string(d.season_day)}};
if (d.league_round) rows.push_back({"leagueRound", std::to_string(*d.league_round)});
emit_table({"Date", "Value"}, rows);
};
auto show_finance = [this] {
const ui::DeskState d = desk();
emit_table({"Finance", "Value"},
{{"balance", money(d.balance)}, {"savings", money(d.savings)}, {"ticketPrice", std::to_string(d.ticket_price)}});
};
auto show_fans = [this] { emit_table({"Fans", "Value"}, {{"standing", std::to_string(desk().fans)}}); };
auto show_lamps = [this] {
const ui::DeskState d = desk();
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 10; ++i)
rows.push_back({std::to_string(i / 5 + 1) + "." + std::to_string(i % 5 + 1), kLamps[i],
d.warnings[i] ? on_off(*d.warnings[i]) : "unknown"});
emit_table({"Lamp", "Name", "State"}, rows);
};
auto show_automation = [this] {
const ui::DeskState d = desk();
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 5; ++i) {
// Lineup holds the number of the saved formation used (0 = off, SizeT6);
// the others are bit 0 of their option byte
std::string state = i == 0 ? (d.automation[0] ? "on (formation " + std::to_string(d.automation[0]) + ")" : "off")
: on_off(d.automation[i] & 1);
rows.push_back({kAutomation[i], state});
}
emit_table({"Automation", "State"}, rows);
};
auto show_opponent = [this] {
const ui::DeskState d = desk();
std::vector<std::vector<std::string>> rows;
rows.push_back({"competition", utf8(d.next_competition_label) +
(d.next_competition_detail.empty() ? "" : " " + utf8(d.next_competition_detail))});
rows.push_back({"opponent", d.next_opponent_name.empty() ? "-" : utf8(d.next_opponent_name)});
if (!d.next_opponent_name.empty()) rows.push_back({"venue", d.next_match_away ? "away" : "home"});
if (d.table_position) rows.push_back({"ownTablePosition", std::to_string(*d.table_position)});
if (d.strength) rows.push_back({"ownStrength", std::to_string(*d.strength)});
emit_table({"Next game", "Value"}, rows);
};
add({"Desktop", "ShowDesk", {}, "all displays of the desk", false},
[this, show_date, show_finance, show_fans, show_lamps, show_automation, show_opponent](const Values&) {
const ui::DeskState d = desk();
emit_table({"Manager", "Club"}, {{utf8(d.manager_name), utf8(d.club_name)}});
show_date();
show_finance();
show_fans();
show_opponent();
show_lamps();
show_automation();
const auto mail = ui::mailbox_state_from_game(session_->state(), d.manager_slot, revision_);
emit_table({"Mailbox", "Value"}, {{"messages", std::to_string(mail.messages.size())}});
});
add({"Desktop", "ShowDate", {}, "date, weekday, season day, league round", false}, [show_date](const Values&) { show_date(); });
add({"Desktop", "ShowFinance", {}, "balance, savings, ticket price", false}, [show_finance](const Values&) { show_finance(); });
add({"Desktop", "ShowFanStanding", {}, "standing with the fans", false}, [show_fans](const Values&) { show_fans(); });
add({"Desktop", "ShowLamps", {}, "the ten warning lamps", false}, [show_lamps](const Values&) { show_lamps(); });
add({"Desktop", "ShowLastGames", {}, "the last six games", false}, [](const Values&) {
fail("E_ENGINE_GAP", "the last games are not in the desk projection yet");
});
add({"Desktop", "ShowOpponent", {}, "the next game and opponent", false}, [show_opponent](const Values&) { show_opponent(); });
Param curves = detail::text("which", 0, true);
curves.display = "[own|opponent]";
add({"Desktop", "ShowPositionCurves", {curves}, "table positions per matchday", false}, [](const Values&) {
fail("E_ENGINE_GAP", "the position curves are not in the desk projection yet");
});
add({"Desktop", "ShowAutomation", {}, "the five automations", false}, [show_automation](const Values&) { show_automation(); });
// --- Desktop: actions ------------------------------------------------------------------
Param target = detail::text("window");
target.display = "window:enum|menu:int";
add({"Desktop", "Open", {target}, "open a window (click on its icon); see the lines below", false}, [this](const Values& v) {
Arg a;
a.text = v.text("window");
int menu = menu_of_window(a.text);
if (menu < 0)
if (const auto n = to_int(a); n && (*n >= 0 && *n < 30)) menu = int(*n);
if (menu < 0) fail("E_BAD_ARGUMENT", "no window " + a.text + " on the desk (ListOptions shows them)");
open_menu(menu);
});
add({"Desktop", "Key", {choice("letter", {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"})},
"a key on the desk (G = Kickoff)", false},
[this](const Values& v) {
const char letter = char('A' + v.choice("letter"));
const auto it = kKeys.find(letter);
if (it == kKeys.end()) fail("E_BAD_ARGUMENT", std::string("the key ") + letter + " has no function on the desk");
open_menu(it->second);
});
// The desk settings without the drawer layout (CareerSession::dispatch_ticket_price /
// dispatch_automation, issue #11): the same writes as the open widgets.
auto setting_owner = [this] {
const ui::DeskState d = desk();
app::DeskSettingIdentity id;
id.manager_slot = d.manager_slot;
id.runtime_club = d.runtime_club;
if (d.runtime_club >= 0 && size_t(d.runtime_club) < session_->state().club_ids.size())
id.stable_club_identity = int(session_->state().club_ids[size_t(d.runtime_club)]);
id.revision = revision_;
return id;
};
add({"Desktop", "SetTicketPrice", {integer("price", 8, 25)}, "the ticket price (price scale)", true}, [this](const Values& v) {
std::string error;
require_engine(app::DeskActions(*session_).ticket_price(desk(), int(v.integer("price")), revision_, error), "ticket price", error);
emit('+', "ticket price: " + std::to_string(desk().ticket_price));
});
Param formation = integer("formation", 1, 8, true);
add({"Desktop", "SetAutomation", {choice("feature", kAutomation), boolean("on"), formation},
"switch one of the five automations (Lineup: a saved formation 1-8)", true},
[this, setting_owner](const Values& v) {
const int feature = v.choice("feature");
const bool on = v.boolean("on");
app::AutomationRequest r;
r.identity = setting_owner();
r.automation = static_cast<app::DeskAutomation>(feature);
r.enabled = on;
if (feature == 0 && on) {
// the line-up automation uses a saved formation: the given one, or the first available
int slot = int(v.integer("formation", 0));
if (!slot) {
const auto p = prep();
if (p.pitch)
for (int f = 0; f < 8 && !slot; ++f)
if (p.pitch->formation_mask & (1 << f)) slot = f + 1;
}
if (!slot) fail("E_RULE", "no saved formation for the lineup automation");
r.formation = slot;
} else if (v.has("formation")) {
fail("E_BAD_ARGUMENT", "only Lineup on takes a formation");
}
std::string error;
require_engine(session_->dispatch_automation(r, revision_, error), "automation", error);
emit('+', kAutomation[size_t(feature)] + " " + on_off(on) + (r.formation ? " (formation " + std::to_string(*r.formation) + ")" : ""));
});
add({"Desktop", "Kickoff", {}, "hand over to the next player or start the day", true}, [this](const Values&) { kickoff(); });
add({"Desktop", "OpenMailbox", {}, "open the mailbox (Kicker)", false}, [this](const Values&) { open_menu(kMailboxMenu); });
add({"Desktop", "OpenDrawer", {}, "open the menu bar", false}, [](const Values&) {
fail("E_ENGINE_GAP", "the desk layout (drawer, folders) is not ported yet");
});
add({"Desktop", "PullPlug", {}, "the plug: quit after a question", false}, [this](const Values&) {
ask("Quit the game? Unsaved progress is lost.", {"Yes", "No"}, "No", [this](const std::string& answer) {
if (answer == "Yes") {
ended_ = true;
emit('+', "session ended");
} else {
emit('+', "quit cancelled");
}
});
});
// --- Mailbox (04-schreibtisch 3) -------------------------------------------------------
add({"Mailbox", "ListMessages", {}, "the messages of this manager (msg numbers for Keep/Delete)", false}, [this](const Values&) {
const ui::MailboxState mail = ui::mailbox_state_from_game(session_->state(), active_slot(), revision_);
listed_mail_ = mail.messages;
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < mail.messages.size(); ++i) {
const auto& m = mail.messages[i];
std::string to = m.general_broadcast ? "all" : "";
if (!m.general_broadcast)
for (int r : m.recipient_managers) to += (to.empty() ? "P" : ",P") + std::to_string(r + 1);
rows.push_back({std::to_string(i + 1), std::to_string(m.date_counter), m.text, m.kept_for_manager ? "yes" : "no", to});
}
emit_table({"Msg", "Day", "Text", "Kept", "To"}, rows);
});
auto mail_action = [this](const Values& v, ui::MailboxActionKind kind) {
const size_t n = size_t(v.integer("msg"));
if (n < 1 || n > listed_mail_.size()) fail("E_BAD_ARGUMENT", "msg numbers refer to the last ListMessages");
const auto& m = listed_mail_[n - 1];
const auto req = app::MailboxActions::request(active_slot(), revision_, kind, m);
std::string error;
if (!app::MailboxActions(*session_).dispatch(req, revision_, error)) fail("E_RULE", "mailbox: " + error);
listed_mail_.clear(); // entries are compacted; numbers are no longer valid
};
add({"Mailbox", "KeepMessage", {integer("msg", 1, 1000)}, "keep a message / let it go (at most five)", true},
[this, mail_action](const Values& v) {
mail_action(v, ui::MailboxActionKind::toggle_keep);
emit('+', "keep toggled (list again for new numbers)");
});
add({"Mailbox", "DeleteMessage", {integer("msg", 1, 1000)}, "throw a message away", true}, [this, mail_action](const Values& v) {
mail_action(v, ui::MailboxActionKind::delete_for_manager);
emit('+', "message deleted (list again for new numbers)");
});
}
// A click on a desk icon. Mode-locked icons answer E_MODE_LOCKED (02-fenster 4); windows the
// console does not have yet answer E_ENGINE_GAP.
void Console::open_menu(int menu) {
const ui::DeskState d = desk();
if (menu == 12) {
kickoff();
return;
}
const bool shortcut = menu == kMailboxMenu && d.mailbox_shortcut;
const auto item = std::find_if(d.items.begin(), d.items.end(), [menu](const ui::DeskItem& i) { return i.kind == menu; });
// An icon is dimmed by the game mode, at the national coach's desk, or for the moment
// (HasNoEquivalentCondition's button states); name the reason that applies.
if (!shortcut && (item == d.items.end() || item->disabled))
fail("E_MODE_LOCKED", menu_window(menu) +
(d.national_team ? " is not available while you coach the national team"
: item == d.items.end()
? " is not available in this game (mode " + std::to_string(d.options.mode) + ")"
: " is not available at the moment"));
switch (menu) {
case 0:
open_window("LeagueTable");
table_league_ = -1;
show_league_table();
return;
case 1:
open_fixtures();
return;
case 10:
case 11:
browse_directory_ = std::filesystem::absolute(save_directory()).lexically_normal();
selected_file_.clear();
open_window(menu == 10 ? "LoadGame" : "SaveGame");
emit('+', "directory: " + shown_directory());
return;
case kMailboxMenu:
open_window("Mailbox");
listed_mail_.clear();
emit('+', "mailbox opened (ListMessages)");
return;
default:
if (const auto it = openers_.find(menu); it != openers_.end()) {
it->second();
return;
}
fail("E_ENGINE_GAP", menu_window(menu) + " is not in the console yet (stage 2/3 of docs/CLI_CONCEPT)");
}
}
// The calendar (key G): the active manager hands over; after the last one the day runs
// (04-schreibtisch 4). Time mode "instant": the matches run without intervention and the
// results are printed afterwards (Info.FinalResults, 07-spieltag).
void Console::kickoff() {
const ui::DeskState before = desk();
ui::DeskRequest req;
req.kind = ui::DeskRequestKind::advance_turn;
req.manager_slot = before.manager_slot;
req.revision = revision_;
// The day runs on the engine thread (windows_match.cpp): a human match pauses it in the
// Match window (time mode stepped), a question of the engine (offers for own players)
// pauses it in any mode; finish_kickoff follows when the engine is done.
start_matchday(req, before);
}
// After the engine finished a kickoff: the info windows, the day's results and the next desk.
void Console::finish_kickoff(const ui::DeskState& before, const TurnAdvanceResult& advanced, const std::string& error) {
if (advanced.kind == TurnDeskKind::Failed || advanced.kind == TurnDeskKind::WaitingAtDesk) {
pending_info_.clear();
fail("E_INTERNAL", "kickoff failed: " + (error.empty() ? advanced.reason : error));
}
flush_info();
if (const auto& results = session_->completed_matchday_results(); results && results->valid && !results->groups.empty()) {
set_window("Info.FinalResults", 0);
emit('i', "Results " + results->date_label);
for (const auto& group : results->groups) {
// the group's own competition: a league by its table title, a cup by the TEXTD
// competition names CupDraw_FormatError_ExecutableField6 (competitionNameDfbCup ..), as the cup draw does
std::string name = group.competition;
if (group.league_id)
name = ui::league_table_from_game(session_->state(), active_slot(), *group.league_id).league_name;
// (the indoor tournament, 0xb, has a runtime name: TEXTD only holds the placeholder
// "...xxx"; the projection already carries the name frozen for these results)
else if (group.cup_id && *group.cup_id >= 0 && *group.cup_id < 13 && (*group.cup_id != 0xb || bmh::kEnglishCompetitions))
name = text(kCompetitionNames + *group.cup_id);
if (group.matches.empty()) continue;
emit('i', name + ":");
std::vector<std::vector<std::string>> rows;
for (const auto& m : group.matches) {
std::string result;
switch (m.status) {
case ui::MatchResultStatus::played:
result = (m.home_goals ? std::to_string(*m.home_goals) : "?") + ":" + (m.away_goals ? std::to_string(*m.away_goals) : "?");
// a cup match beyond 90 minutes; on penalties the score holds the
// shoot-out goals too (as the original stores it)
if (m.decided == 1) result += " aet";
if (m.decided == 2) result += " pen (incl. shoot-out)";
break;
case ui::MatchResultStatus::postponed: result = "postponed"; break;
case ui::MatchResultStatus::not_played: result = "not played"; break;
case ui::MatchResultStatus::unknown: result = "?"; break;
}
rows.push_back({m.home, m.away, result});
}
emit_table({"Home", "Away", "Result"}, rows);
}
}
if (advanced.kind == TurnDeskKind::CareerComplete) {
set_window("GameEnd", 0);
emit('+', "Game over (" + std::to_string(session_->state().season) + " seasons)");
career_ = false;
return;
}
const ui::DeskState after = desk();
set_window("Desktop", after.manager_slot + 1);
if (after.day_counter == before.day_counter && after.manager_slot != before.manager_slot)
emit('+', "Next: Player " + std::to_string(after.manager_slot + 1));
else
emit('+', std::string(advanced.kind == TurnDeskKind::SeasonEndDesk ? "Season end: " : "Next day: ") +
date_text(after.date.day, after.date.month, after.date.year));
report_new_mail();
}
} // namespace bmh::cli::console
+57
View File
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: GPL-3.0-only
// OpenBMH deviates from the original: uses monthly staff levels in increments of five thousand and the supported youth-academy controls.
// The club environment (menu 24, docs/CLI_CONCEPT/06-verein.md 10, H2 p. 93, supported rule profile p. 107,
// 111): co-trainer, doctor and physio in levels of 5 000 a month, and the supported rule profile youth
// academy that costs a season price of the league.
//
// The rules are the engine's (src/game/environment.hpp, a port of Image with the
// supported rule profile patch); a command is one click of the original screen.
#include "app/desktop_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/environment.hpp"
namespace bmh::cli::console {
using namespace detail;
void Console::register_environment_commands() {
auto show = [this] {
const EnvironmentState s = environment_state(session_->state(), active_slot());
std::vector<std::vector<std::string>> rows = {
{"AssistantCoach", std::to_string(s.level[kCoTrainer]), money(s.monthly[kCoTrainer])},
{"Doctor", std::to_string(s.level[kDoctor]), money(s.monthly[kDoctor])},
{"Physio", std::to_string(s.level[kPhysio]), money(s.monthly[kPhysio])},
{"YouthAcademy", s.monthly[kYouthAcademy] != 0 ? "on" : "off", money(s.youth_price) + " per season"}};
emit_table({"Item", "Level", "Costs"}, rows);
emit('i', std::string("youth academy: ") + (s.youth_paid ? "paid this season" : s.youth_open ? "can be started (July/August)"
: "too late for this season"));
};
openers_[24] = [this, show] {
open_window("Environment");
show();
};
add({"Environment", "ShowEnvironment", {}, "staff levels and the youth academy", false}, [show](const Values&) { show(); });
auto apply = [this, show](int item, int level) {
std::string error;
const auto r=app::EnvironmentActions(*session_).set_console(
ui::environment_from_game(session_->state(),revision_),item,level,revision_,error,
[this](const GameState&,const std::string& message) { emit('i',utf8(message));return true; });
if(!r||*r==EnvironmentResult::invalid) fail("E_BAD_ARGUMENT", "no such item or level");
show();
};
add({"Environment", "SetStaffLevel", {choice("role", {"AssistantCoach", "Doctor", "Physio"}), integer("level", 0, 6)},
"click a staff tile: level 0..6, 5 000 a month each", true},
[apply](const Values& v) { apply(kCoTrainer + v.choice("role"), int(v.integer("level"))); });
add({"Environment", "SetYouthAcademy", {choice("state", {"On", "Off"})}, "start (July/August) or stop the youth academy", true},
[this, apply](const Values& v) {
const bool on = environment_state(session_->state(), active_slot()).monthly[kYouthAcademy] != 0;
const bool want = v.choice("state") == 0;
// the original's click on an active academy switches it off: click only for a change
if (on == want) emit('+', std::string("youth academy already ") + (on ? "on" : "off"));
else apply(kYouthAcademy, want ? 6 : 0);
});
}
} // namespace bmh::cli::console
+137
View File
@@ -0,0 +1,137 @@
// SPDX-License-Identifier: GPL-3.0-only
// Friendly matches (menu 6, docs/CLI_CONCEPT/06-verein.md, H2 p. 50-51): choose an opponent and
// the venue, see the costs, pick a free date and book it.
//
// The engine functions are the ones the SDL app's controller uses (src/app/controller.cpp
// serve_friendly_action): quote_friendly_match (pure), friendly_match_date_status (pure) and
// book_friendly_match, which writes the plan. A human opponent must agree and the paying
// manager must accept the costs; the console asks those managers (hot seat) before booking.
#include <algorithm>
#include "app/desktop_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/desk_actions.hpp"
#include "game/schedule.hpp"
#include "ui/desk_state.hpp"
#include "ui/league_table.hpp"
namespace bmh::cli::console {
using namespace detail;
void Console::register_friendly_commands() {
auto manager = [this] { return active_slot(); };
openers_[6] = [this] {
friendly_quote_.reset();
open_window("Friendlies");
emit('+', "friendlies: ListFriendlyOpponents, ProposeFriendly(club, Home|Away)");
};
add({"Friendlies", "ListFriendlyOpponents", {integer("league", 0, kLeagueCount - 1, true)}, "the clubs of a league (default: own)", false},
[this](const Values& v) {
const ui::DeskState d = desk();
const int league = v.has("league") ? int(v.integer("league")) : std::max(0, d.league);
const ui::LeagueTableState t = ui::league_table_from_game(session_->state(), d.manager_slot, league);
std::vector<std::vector<std::string>> rows;
for (const auto& r : t.rows)
if (r.runtime_team_id != d.runtime_club) rows.push_back({"club:" + std::to_string(r.runtime_team_id), r.name});
emit('i', t.league_name);
emit_table({"Club", "Name"}, rows);
});
Param club = detail::text("club");
club.display = "club:Club";
add({"Friendlies", "ProposeFriendly", {club, choice("venue", {"Home", "Away"})}, "the offer: costs and who pays", false},
[this, manager](const Values& v) {
// a club by club:<runtime id> or a unique part of a name (all leagues)
const std::string reference = v.text("club");
int opponent = -1;
std::string number = lower(reference).rfind("club:", 0) == 0 ? reference.substr(5) : reference;
Arg a;
a.text = number;
if (const auto id = to_int(a)) {
opponent = int(*id);
} else {
std::vector<int> found;
for (int league = 0; league < kLeagueCount; ++league)
for (const auto& r : ui::league_table_from_game(session_->state(), manager(), league).rows)
if (fold(r.name).find(fold(reference)) != std::string::npos) found.push_back(r.runtime_team_id);
if (found.size() != 1) fail(found.empty() ? "E_BAD_ARGUMENT" : "E_AMBIGUOUS", "\"" + reference + "\" fits " +
std::to_string(found.size()) + " clubs; use club:<n>");
opponent = found.front();
}
const FriendlyBookingQuote q = app::FriendlyActions(*session_).quote(manager(), opponent, v.choice("venue") == 0);
if (q.status != FriendlyQuoteStatus::quoted) fail("E_RULE", "no friendly possible against this club");
friendly_quote_ = q;
const GameState& g = session_->state();
emit('+', utf8(g.club_name(q.home_team)) + " - " + utf8(g.club_name(q.away_team)) + ", costs " + money(q.cost) +
(q.payer_manager >= 0 ? " (paid by player " + std::to_string(q.payer_manager + 1) + ")" : "") +
(q.opponent_manager >= 0 ? ", player " + std::to_string(q.opponent_manager + 1) + " must agree" : "") +
"; ListFreeDates, SetFriendlyDate(YYYY-MM-DD)");
});
auto free_dates = [this]() {
if (!friendly_quote_) fail("E_RULE", "no offer (ProposeFriendly first)");
std::vector<std::pair<int, std::string>> dates;
const GameState& g = session_->state();
for (int day = 0; day <= 365; ++day) {
const FriendlyDateStatus s = app::FriendlyActions(*session_).date_status(*friendly_quote_, uint16_t(day));
if (s != FriendlyDateStatus::available && s != FriendlyDateStatus::available_with_calendar_event) continue;
const ui::DeskDate date = ui::desk_date(g.season_start + uint32_t(day), exe_);
dates.push_back({day, date_text(date.day, date.month, date.year)});
}
return dates;
};
add({"Friendlies", "ListFreeDates", {}, "the days the friendly can be played", false}, [this, free_dates](const Values&) {
std::vector<std::vector<std::string>> rows;
for (const auto& [day, date] : free_dates()) rows.push_back({date, std::to_string(day)});
emit_table({"Date", "SeasonDay"}, rows);
});
add({"Friendlies", "SetFriendlyDate", {detail::text("date")}, "book the friendly on a free date (YYYY-MM-DD)", true},
[this, free_dates](const Values& v) {
int day = -1;
for (const auto& [d, date] : free_dates())
if (date == v.text("date")) day = d;
if (day < 0) fail("E_RULE", v.text("date") + " is not free (ListFreeDates)");
const FriendlyBookingQuote q = *friendly_quote_;
// the costs are accepted by the paying manager, a human opponent agrees; then book
auto book = [this, q, day](bool accept_cost, bool accept_opponent) {
const FriendlyBookingResult r = app::FriendlyActions(*session_).book_console(
q, uint16_t(day), accept_opponent, q.opponent_manager, accept_cost, q.payer_manager, revision_);
friendly_quote_.reset();
switch (r.status) {
case FriendlyBookingStatus::booked: break;
case FriendlyBookingStatus::insufficient_funds: fail("E_INSUFFICIENT_FUNDS", "the money is not enough for this match");
case FriendlyBookingStatus::declined: fail("E_RULE", "the costs were declined");
case FriendlyBookingStatus::opponent_declined: fail("E_RULE", "the opponent did not agree");
default: fail("E_RULE", "the date could not be booked");
}
const ui::DeskDate date = ui::desk_date(session_->state().season_start + uint32_t(day), exe_);
emit('+', "friendly booked for " + date_text(date.day, date.month, date.year));
};
auto ask_opponent = [this, q, book](bool accept_cost) {
if (q.opponent_manager < 0) {
book(accept_cost, false);
return;
}
const int previous = player_;
player_ = q.opponent_manager + 1;
ask("Player " + std::to_string(q.manager + 1) + " proposes a friendly. Agree?", {"Yes", "No"}, "No",
[this, book, accept_cost, previous](const std::string& answer) {
player_ = previous;
book(accept_cost, answer == "Yes");
});
};
if (q.cost > 0 && q.payer_manager >= 0) {
const int previous = player_;
player_ = q.payer_manager + 1;
ask("The friendly costs " + money(q.cost) + ". Pay?", {"Yes", "No"}, "No", [this, ask_opponent, previous](const std::string& answer) {
player_ = previous;
ask_opponent(answer == "Yes");
});
return;
}
ask_opponent(false);
});
}
} // namespace bmh::cli::console
+220
View File
@@ -0,0 +1,220 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
// Information windows of docs/CLI_CONCEPT/05-information.md that the engine can already
// project: TeamInfo (club information, from LeagueTable / Fixtures), HighScore (menu 26) and
// TopScorers (menu 20).
//
// TeamInfo opens like the SDL app's club information (src/app/main.cpp
// present_club_information): CareerSession::enter_club_information prepares the entry
// (OpenTransferEditor's entry step, prepare_club_info_entry) for league teams, then the pure
// ui::club_info_from_game projection is read.
//
// Strengths, Achievements, OtherGames, TopScorers, FairPlay, Statistics and Calendar have no
// projection in the engine/UI yet; Open() answers E_ENGINE_GAP for them (windows_desk.cpp).
#include <algorithm>
#include <memory>
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/highscore.hpp"
#include "game/schedule.hpp"
#include "game/top_scorers.hpp"
#include "ui/club_info.hpp"
#include "ui/league_table.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU
constexpr int kHighscorePrefix = 889; // the high score file prefix ("high/h.") of TEXTD
} // namespace
void Console::register_info_commands() {
// --- TopScorers (05-information 7, menu 20) -------------------------------------------
// Codex's read-only port of TopScorersFromGame (game/top_scorers.hpp): the best ten of the own
// league by goals, assists or both (one point each), for the whole league or only the
// managers' clubs. No state changes and no random draws, so the console reads it directly.
struct ScorerView {
game::TopScorersMetric metric = game::TopScorersMetric::goals;
game::TopScorersScope scope = game::TopScorersScope::league;
};
auto scorers = std::make_shared<ScorerView>();
auto show_scorers = [this, scorers] {
const game::TopScorersProjection t = game::top_scorers_from_game(session_->state(), active_slot(), scorers->metric, scorers->scope);
static const char* const kMetric[3] = {"goals", "assists", "scorer points"};
emit('i', std::string("top ") + kMetric[int(scorers->metric)] +
(scorers->scope == game::TopScorersScope::league ? ", whole league" : ", managers' clubs only"));
if (t.no_results) {
emit('i', "no results yet");
return;
}
std::vector<std::vector<std::string>> rows;
for (const auto& r : t.rows)
rows.push_back({std::to_string(r.rank), "id:" + std::to_string(r.player), utf8(r.player_name), utf8(r.team_name),
std::to_string(r.goals), std::to_string(r.assists), std::to_string(r.score)});
emit_table({"Rank", "Id", "Player", "Club", "Goals", "Assists", "Points"}, rows);
};
openers_[20] = [this, scorers, show_scorers] {
*scorers = ScorerView{};
open_window("TopScorers");
show_scorers();
};
Param list = choice("list", {"Goals", "Assists", "Score"}, true), scope = choice("scope", {"League", "Managers"}, true);
add({"TopScorers", "ShowScorers", {list, scope}, "the best ten: goals, assists or both; whole league or managers' clubs", false},
[scorers, show_scorers](const Values& v) {
if (v.has("list")) scorers->metric = game::TopScorersMetric(v.choice("list"));
if (v.has("scope")) scorers->scope = game::TopScorersScope(v.choice("scope"));
show_scorers();
});
Param list_needed = choice("list", {"Goals", "Assists", "Score"}), scope_needed = choice("scope", {"League", "Managers"});
add({"TopScorers", "SetList", {list_needed}, "TORSCHÜTZEN / VORLAGEN / SCORER", false}, [scorers, show_scorers](const Values& v) {
scorers->metric = game::TopScorersMetric(v.choice("list"));
show_scorers();
});
add({"TopScorers", "SetScope", {scope_needed}, "GESAMTE LIGA / NUR MANAGER", false}, [scorers, show_scorers](const Values& v) {
scorers->scope = game::TopScorersScope(v.choice("scope"));
show_scorers();
});
// --- TeamInfo (05-information 4) ------------------------------------------------------
// A club of the nine leagues by name (unique part) or club:<runtime id>.
auto team_of = [this](const std::string& reference) {
std::vector<std::pair<int, std::string>> teams;
for (int league = 0; league < kLeagueCount; ++league)
for (const auto& row : ui::league_table_from_game(session_->state(), active_slot(), league).rows)
teams.push_back({row.runtime_team_id, row.name});
std::string number = lower(reference).rfind("club:", 0) == 0 ? reference.substr(5) : reference;
Arg a;
a.text = number;
if (const auto id = to_int(a)) {
for (const auto& t : teams)
if (t.first == *id) return t.first;
fail("E_BAD_ARGUMENT", "no club " + reference + " in the leagues");
}
std::vector<int> exact, partial;
for (const auto& t : teams) {
const std::string name = fold(t.second);
if (name == fold(reference)) exact.push_back(t.first);
else if (name.find(fold(reference)) != std::string::npos) partial.push_back(t.first);
}
const auto& found = exact.empty() ? partial : exact;
if (found.size() == 1) return found.front();
if (found.empty()) fail("E_BAD_ARGUMENT", "no club named \"" + reference + "\" in the leagues");
std::string candidates;
for (size_t i = 0; i < found.size() && i < 8; ++i)
candidates += (i ? ", " : "") + utf8(session_->state().club_name(found[i])) + " = club:" + std::to_string(found[i]);
fail("E_AMBIGUOUS", "\"" + reference + "\" fits several clubs: " + candidates);
};
auto show_team = [this] {
if (!team_info_) fail("E_INTERNAL", "no club information");
const auto& t = *team_info_;
emit('i', utf8(t.original_club_name) + (t.has_squad ? "" : " (no squad data)"));
std::vector<std::vector<std::string>> rows;
for (const auto& p : t.players) {
if (p.player_id < 0) continue; // free squad places
const auto& a = p.attributes;
rows.push_back({"id:" + std::to_string(p.player_id), utf8(p.original_name), text(kPositionNames + a.position()),
std::to_string(a.age()), std::to_string(a.condition()), std::to_string(a.technique()),
std::to_string(a.form()), std::to_string(a.strength()), p.borrowed ? "[loan]" : ""});
}
emit_table({"Id", "Player", "Pos", "Age", "K", "T", "F", "Str", ""}, rows);
};
auto open_team = [this, team_of, show_team](const std::string& reference) {
const int team = team_of(reference);
// The club-info entry rewrites the squad flags of the club (PrepareLineupEntry), which makes the
// engine's pairings draft stale: the fixtures page could neither act nor close any
// more. So the fixtures page closes first; GoBack from TEAM-INFO then returns to the
// window the fixtures were opened from.
if (window_ == "Fixtures" && pairings_) fixtures_action(LeaguePairingsAction::close);
std::string error;
ClubInfoEntry entry;
if (team < int(exe_.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField))) { // league teams get the entry step (as the app does)
const auto prepared = session_->enter_club_information(team, error);
if (!prepared) fail("E_RULE", "club information: " + error);
entry = *prepared;
}
team_info_ = ui::club_info_from_game(session_->state(), team, entry, exe_, texts_);
// from TEAM-INFO itself the page is replaced: one club information at a time, so
// GoBack/CloseTeamInfo leads back to where the first one was opened
if (window_ != "TeamInfo") open_window("TeamInfo");
show_team();
};
Param club = detail::text("club");
club.display = "club:Club";
for (const char* window : {"LeagueTable", "Fixtures", "TeamInfo"})
add({window, "OpenTeamInfo", {club}, "TEAM-INFO of a club: club:<n> or a name", false},
[open_team](const Values& v) { open_team(v.text("club")); });
add({"TeamInfo", "ShowTeamSquad", {choice("view", {"A", "B"}, true)}, "the club's squad", false}, [show_team](const Values&) { show_team(); });
add({"TeamInfo", "ShowPlayer", {detail::text("player")}, "a player of this club", false}, [this](const Values& v) {
if (!team_info_) fail("E_INTERNAL", "no club information");
// free squad places (player -1) are no players; `index` maps refs back to the rows
std::vector<PlayerRef> refs;
std::vector<size_t> index;
for (size_t i = 0; i < team_info_->players.size(); ++i) {
const auto& p = team_info_->players[i];
if (p.player_id < 0) continue;
refs.push_back({p.row, p.player_id, utf8(p.original_name)});
index.push_back(i);
}
const auto& p = team_info_->players[index[resolve_player(v.text("player"), refs)]];
const auto& a = p.attributes;
emit_table({"Player", "Value"},
{{"name", utf8(p.original_name)},
{"id", "id:" + std::to_string(p.player_id)},
{"position", text(kPositionNames + a.position())},
{"age", std::to_string(a.age())},
{"condition/technique/form", std::to_string(a.condition()) + "/" + std::to_string(a.technique()) + "/" + std::to_string(a.form())},
{"strength", std::to_string(a.strength())}});
});
add({"TeamInfo", "CloseTeamInfo", {}, "back to where it was opened", false}, [this](const Values&) {
team_info_.reset();
close_window();
emit('+', "club information closed");
});
for (const char* name : {"ShowTeamStatistics", "SetBroadcast"})
add({"TeamInfo", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " is not in the console yet"); });
// --- HighScore (menu 26, H2 p. 94) ----------------------------------------------------
auto show_highscore = [this] {
const GameState& g = session_->state();
const uint16_t signature = g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField7) ? g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) : 0;
if (signature != 0) {
// the ranked list of this game's level, stored next to the saved games
const auto file = highscore_file(save_directory(), signature, texts_.strings.at(kHighscorePrefix));
HighscoreTable rows{};
std::error_code ec;
if (std::filesystem::exists(file, ec)) rows = load_highscore_table(file);
std::vector<std::vector<std::string>> table;
int rank = 0;
for (const auto& r : rows)
if (!r.manager_name.empty())
table.push_back({std::to_string(++rank), utf8(r.manager_name), utf8(r.club_name), std::to_string(r.score)});
if (table.empty()) emit('i', "the high score list is empty");
else emit_table({"Rank", "Manager", "Club", "Score"}, table);
} else {
emit('i', "no ranked high score list in this game (level changed or signature 0)");
}
const HighscoreScore s = highscore_score(g, active_slot());
emit_table({"Score", "Points"}, {{"assets", std::to_string(s.assets)},
{"patience", std::to_string(s.patience)},
{"facilities", std::to_string(s.facilities)},
{"team", std::to_string(s.team)},
{"history", std::to_string(s.history)},
{"titles", std::to_string(s.titles)},
{"total", std::to_string(s.total)}});
};
openers_[26] = [this, show_highscore] {
open_window("HighScore");
show_highscore();
};
add({"HighScore", "ShowHighScore", {}, "the high score list and your current score", false},
[show_highscore](const Values&) { show_highscore(); });
}
} // namespace bmh::cli::console
+901
View File
@@ -0,0 +1,901 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
// Stage 4 of docs/CLI_CONCEPT: the matchday window Match (07-spieltag 3) with a stepped clock.
//
// The engine plays a day inside one synchronous call (CareerSession::dispatch_kickoff ->
// TurnDriver::advance_to_next_desk) and calls TurnDriver::live_minute after every minute.
// The SDL app shows its live screen from inside that callback. The console cannot wait for
// input inside a call, so in time mode "stepped" the kickoff runs on an engine thread: the
// minute callback hands control to the console thread and blocks until the console lets the
// clock run again (Match.Step / Match.Run). Exactly one of the two threads runs at a time
// (a mutex/condition handshake), so the game stays deterministic: the same input gives the
// same game, whatever the timing.
//
// During a pause the console may change the human team as the original allows from the
// match (EndPhase -> line-up screen): Match.Substitute calls manual_substitution on the
// engine's state and MatchEngine::rerate_team, as tests/season_sim.cpp SIM_INTERVENE does.
//
// The events come from the engine's presentation log (MatchEngine::show, presentation.hpp):
// the console points it at its own vector at the first minute; appending draws no random
// numbers. Events of the first simulated minute are therefore not listed (the log is only
// reachable from the minute callback).
#include <algorithm>
#include <array>
#include <condition_variable>
#include <limits>
#include <mutex>
#include <set>
#include <stdexcept>
#include <thread>
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/lineup.hpp"
#include "game/match_engine.hpp"
#include "game/presentation.hpp"
#include "game/schedule.hpp"
#include "game/season.hpp"
#include "game/messages.hpp"
#include "game/month.hpp"
#include "game/pending_offer.hpp"
#include "game/weekly.hpp"
#include "ui/incoming_transfer.hpp"
#include "ui/league_table.hpp"
#include "ui/live_matchday.hpp"
#include "ui/pending_offer.hpp"
#include "ui/tactics.hpp"
#include "app/window_actions.hpp"
#include "ui/preparation.hpp"
namespace bmh::cli::console {
using namespace detail;
struct Console::EngineRun {
std::thread worker;
std::mutex m;
std::condition_variable cv;
bool engine_turn = false; // true: the engine thread runs and the console waits
bool finished = false;
TurnAdvanceResult result;
std::string error;
ui::DeskState before;
// the pause (valid while the engine waits in the minute callback)
int minute = 0;
MatchEngine* engine = nullptr;
std::vector<MatchGroup>* groups = nullptr;
GameState* state = nullptr;
bool intro_shown = false;
// the clock: minutes to run before the next pause, or a minute to run to
int steps = 0;
int until = -1;
bool to_end = false;
std::vector<ShowEvent> events; // the engine's presentation log
std::set<std::pair<int, int>> human_matches; // (group, match) with a human team
size_t printed = 0;
bool quiet = false; // time mode instant: no minute pauses, no "~" lines
// a question of the engine during the kickoff (stage 5): the engine thread waits in a
// hook until the console has the answer (PendingOfferHooks, 07-spieltag 7.3)
enum class Pause { minute, question, loan_offer } pause = Pause::minute;
bool aborted = false;
bool loan_question = false;
// These capabilities refer to the month caller's staged transaction, never
// CareerSession's live state. They live only while its synchronous hook waits.
GameState* loan_state = nullptr;
GameRandom* loan_game = nullptr;
WatcomRandom* loan_random = nullptr;
app::ClubModalServices* loan_services = nullptr;
TransferOfferEditorState loan_owner;
HumanBuyerSaleHooks loan_hooks;
int loan_result = -1;
int question_player = 0; // 1-4
std::string question_text, question_default, answer;
std::vector<std::string> question_options;
std::vector<std::string> notices; // the engine's notices, printed when the console runs
// Engine thread: hands a question to the console and waits for its answer.
std::string ask(int player, std::string text, std::vector<std::string> options, std::string fallback) {
std::unique_lock lock(m);
if (aborted) throw std::runtime_error("console matchday aborted");
pause = Pause::question;
question_player = player;
question_text = std::move(text);
question_options = std::move(options);
question_default = std::move(fallback);
answer.clear();
engine_turn = false;
cv.notify_all();
cv.wait(lock, [this] { return engine_turn; });
pause = Pause::minute;
if (aborted) throw std::runtime_error("console matchday aborted");
return answer.empty() ? question_default : answer;
}
};
Console::~Console() {
if (run_) {
try {
stop_matchday();
} catch (...) {
}
}
}
namespace {
// The human teams in this minute's groups.
bool human_playing(const std::vector<MatchGroup>& groups, const GameState& g) {
for (const auto& group : groups)
for (size_t side = 0; side < group.fixtures.size(); ++side)
if (!(group.void_mask() >> (side / 2) & 1) &&
g.manager_of(group.fixtures[side]) >= 0) return true;
return false;
}
const char* booking_name(int kind) {
switch (kind) {
case 0: return "yellow card";
case 1: return "red card";
case 2: return "injury";
case 3: return "yellow-red card";
default: return "booking";
}
}
} // namespace
void Console::start_matchday(const ui::DeskRequest& request, const ui::DeskState& before) {
run_ = std::make_shared<EngineRun>();
run_->before = before;
EngineRun* run = run_.get();
if (options_.time == TimeMode::instant) run->quiet = run->to_end = true;
session_->set_loan_return_presenter([run](GameState&, WatcomRandom&, int manager, const std::string& question) {
run->loan_question = true;
struct Reset { bool& flag; ~Reset() { flag = false; } } reset{run->loan_question};
return run->ask(manager + 1, utf8(question), {"Yes", "No"}, "No") == "Yes" ? 1 : 0;
});
session_->set_loan_return_offer_presenter([run](GameState& state, GameRandom& game, WatcomRandom& random,
app::ClubModalServices& services, int manager, int source_slot, int list_entry,
const HumanBuyerSaleHooks& hooks) -> int {
if (run->aborted || manager < 0 || size_t(manager) >= state.manager_teams.size() ||
list_entry < 40 || list_entry >= 44 || source_slot != 2928 + list_entry ||
!state.memory.has(::bmh::layout::EditorList + uint32_t(list_entry) * 0x58 + 0x57)) return -1;
const uint32_t row = ::bmh::layout::EditorList + uint32_t(list_entry) * 0x58;
TransferOfferEditorRequest input;
input.manager = manager;
input.runtime_club = state.manager_teams.at(size_t(manager));
input.list_entry = list_entry;
input.source_slot = source_slot;
input.expected_player = state.squad_slots.at(size_t(source_slot)) & 0x0fff;
input.expected_seller_word = state.memory.u16(row + 8);
for (int bid = 0; bid < 4; ++bid) {
const uint16_t club = state.memory.u16(row + uint32_t(bid) * 2);
if (club == 0xffff || club == input.runtime_club) { input.expected_bid_slot = bid; break; }
}
input.loan_return_entry = true;
auto owner = open_transfer_offer_editor_source(state, input, game, random);
if (!owner.supported || owner.closed) return -1;
std::unique_lock lock(run->m);
run->loan_state = &state;
run->loan_game = &game;
run->loan_random = &random;
run->loan_services = &services;
run->loan_owner = std::move(owner);
run->loan_hooks = hooks;
run->loan_result = -1;
run->pause = EngineRun::Pause::loan_offer;
run->engine_turn = false;
run->cv.notify_all();
run->cv.wait(lock, [run] { return run->engine_turn; });
run->pause = EngineRun::Pause::minute;
run->loan_state = nullptr;
run->loan_game = nullptr;
run->loan_random = nullptr;
run->loan_services = nullptr;
run->loan_hooks = {};
return run->aborted ? -1 : run->loan_result;
});
// DayStepRest2 can enter InstallDefaultHooks while advancing the calendar. Bridge
// that synchronous Source callback through the same engine-question pause
// used by the kickoff's transfer questions. Offers are the actual four
// Source demands; no guessed renewal term or salary is applied.
session_->set_contract_expiry_presenter([run](GameState& state, WatcomRandom& random, int manager, int row) {
if (manager < 0 || size_t(manager) >= state.manager_teams.size())
throw std::runtime_error("contract expiry: invalid manager owner");
const SquadRange squad = squad_range(state.manager_teams[size_t(manager)]);
if (row < 0 || size_t(row) >= squad.count || squad.first + size_t(row) >= state.squad_slots.size())
throw std::runtime_error("contract expiry: invalid squad row");
const size_t board = size_t(manager) * 0x840 + size_t(row) * 0x58;
if (board + 0x54 > state.tactics.size())
throw std::runtime_error("contract expiry: missing board row");
const int player = int(state.squad_slots[squad.first + size_t(row)] & 0x0fff);
if (player == 0x0fff || size_t(player) >= state.players.size())
throw std::runtime_error("contract expiry: missing player");
const std::string player_name = utf8(state.player_name(player));
const GameState before = state;
const WatcomRandom before_random = random;
std::array<uint32_t, 4> demands{};
try {
// InstallDefaultHooks passes the physical squad row as param5, so
// ContractBonuses enters with from_desk=false (the 0x80 desk bit is absent).
demands = contract_demands(state, manager, row, false, random);
} catch (const std::exception&) {
state = before;
random = before_random;
throw;
}
std::vector<std::string> options;
std::vector<int> columns;
for (int year = 0; year < 4; ++year) {
const uint32_t demand = demands[size_t(year)];
if (demand == 0 || demand == std::numeric_limits<uint32_t>::max()) continue;
columns.push_back(year);
options.push_back(std::to_string(year + 1) + " year" + (year == 0 ? "" : "s") +
" — " + std::to_string(demand) + " monthly");
}
options.push_back("No offer (release player)");
const std::string fallback = options.back();
const std::string prompt = player_name + utf8(message_text(state, ::bmh::layout::Month_BoardMonth_TextPointer4)) +
" Choose an offer at the player's salary demand or release the player.";
const std::string answer = run->ask(manager + 1, prompt, options, fallback);
if (answer == fallback) return 0;
const auto selected = std::find(options.begin(), options.end() - 1, answer);
if (selected == options.end() - 1)
throw std::runtime_error("contract expiry: invalid question answer");
const size_t index = size_t(selected - options.begin());
const int column = columns[index];
bool accepted = false;
try {
accepted = contract_offer(state, manager, row, column, demands[size_t(column)], demands[size_t(column)],
false, true, random);
} catch (const std::exception&) {
state = before;
random = before_random;
throw;
}
if (!accepted) {
// With an exact Source demand the acceptance threshold is necessarily
// met. Keep an unexpected rejection distinct from the Source close path:
// ContractBonuses returns to the still-open InstallDefaultHooks screen.
throw std::runtime_error("contract expiry: unexpected rejection of the exact salary demand");
}
run->notices.push_back("Contract renewed: " + player_name);
return 1;
});
// The engine's questions during the kickoff, as the SDL app asks them (src/app/main.cpp
// make_pending_offer_hooks): a club's salary demand or severance (yes/no) and the
// choice among the clubs' fee offers for an own player. normal_interactive is the
// session's mode for a frontend that presents them (legacy_unpresented answers them
// without asking).
PendingOfferHooks hooks;
hooks.answer = [run](const GameState&, const PendingOfferQuestion& q) {
// the severance a sold player's management asks for: refusing it ends the transfer
// (QA: sales of 2.7M and 3.4M were lost on a "No" that looked like a side question)
const std::string hint =
q.kind == PendingOfferQuestionKind::severance ? " [No = the transfer does not take place]" : "";
const std::string answer =
run->ask(q.manager + 1, utf8(q.original_message) + hint, {"Yes", "No"}, "No");
return answer == "Yes" ? PendingOfferAnswer::yes : PendingOfferAnswer::no;
};
hooks.select_transfer = [run](const GameState& staged, const TransferOfferListView& offers) {
const ui::IncomingTransferDecisionState panel = ui::pending_offer_transfer_decision_from_game(staged, offers);
std::string text = "Offers for " + utf8(panel.player_name) + ":";
std::vector<std::string> options;
std::vector<int> slots;
for (size_t i = 0; i < panel.offers.size(); ++i) {
const auto& o = panel.offers[i];
if (!o.present) continue;
options.push_back("Accept" + std::to_string(options.size() + 1));
slots.push_back(int(i));
text += " " + options.back() + " = " + (o.loan ? "loan to " : "sell to ") + utf8(panel.buyer_names[i]) + " for " + std::to_string(o.fee) + " (" +
std::to_string(o.monthly_salary) + " monthly" + (o.loan ? ", loan" : "") + ");";
}
options.push_back("Decline");
// IncomingTransferScreen: the right mouse button declines (IncomingTransferScreen::click)
const std::string answer = run->ask(panel.viewer_manager + 1, text, options, "Decline");
for (size_t i = 0; i < slots.size(); ++i)
if (options[i] == answer) return PendingOfferTransferChoice{PendingOfferTransferChoiceKind::bid, slots[i]};
return PendingOfferTransferChoice{PendingOfferTransferChoiceKind::decline, -1};
};
hooks.notice = [run](const GameState&, const PendingOfferNotice& n) { run->notices.push_back(utf8(n.original_message)); };
session_->set_pending_offer_hooks(std::move(hooks));
// IncomingTransferScreen at the weekly list deadline: the bids for a player a manager put on the
// transfer list. Without this chooser the engine declines every bid for a human seller
// (GameState::transfer_offer_selector), so listed players could never be sold.
session_->set_transfer_offer_selector([run](const GameState& g, const TransferOfferListView& view) -> int {
const std::string notice = view.notice_text_address ? utf8(message_text(g, view.notice_text_address)) : std::string();
if (view.offer_count <= 0) { // the final refusal notice; the response is ignored
if (!notice.empty()) run->notices.push_back(notice);
return -1;
}
std::string text = (notice.empty() ? std::string() : notice + " ") + "Offers for " + utf8(g.player_name(view.player)) + ":";
std::vector<std::string> options;
std::vector<int> slots;
for (const auto& o : view.offers) {
if (!o.present) continue;
options.push_back("Accept" + std::to_string(options.size() + 1));
slots.push_back(o.bid_index);
text += " " + options.back() + " = " + (o.loan ? "loan to " : "sell to ") + utf8(g.club_name(o.buyer)) + " for " + std::to_string(o.fee) + " (" +
std::to_string(o.monthly_salary) + " monthly" + (o.loan ? ", loan" : "") + ");";
}
options.push_back("Decline");
const std::string answer = run->ask(view.seller_manager + 1, text, options, "Decline");
for (size_t i = 0; i < slots.size(); ++i)
if (options[i] == answer) return slots[i];
return -1;
});
// IncomingTransferScreen also presents the automatic result when a human bid loses
// to another club. The engine already supplies this read-only snapshot;
// relay it at the next thread handoff instead of silently dropping it.
session_->set_transfer_decision_observer([this, run](const TransferDecisionEvent& event) {
const auto& g = session_->state();
const std::string player = utf8(g.player_name(event.offers.player));
if (event.kind == TransferDecisionEventKind::last_week) {
run->notices.push_back(player + utf8(message_text(g, event.result_text_address)));
return;
}
if (event.kind == TransferDecisionEventKind::confirmation) {
run->notices.push_back(player + ": " + utf8(message_text(g, event.result_text_address)));
return;
}
// The Original marks each row NEIN up to the accepted row (OK), or
// every row NEIN when no bid is accepted. It stops at the OK row.
for (const auto& offer : event.offers.offers) {
if (!offer.present) continue;
const bool accepted = event.accepted && offer.bid_index == event.selected_bid_index;
run->notices.push_back(player + ": " + utf8(g.club_name(offer.buyer)) + ": " +
utf8(message_text(g, accepted ? ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer3 : ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer4)));
if (accepted) break;
}
// The rows stop at the accepted bid, so a human bid behind it never shows up; a manager
// then waits for a player who has gone (learning session, finding G-006). The console
// says it for every human bidder that lost (OpenBMH deviates from the original screen
// here: an extra line, nothing in the engine changes).
for (const auto& offer : event.offers.offers) {
if (!offer.present || (event.accepted && offer.bid_index == event.selected_bid_index)) continue;
if (g.manager_of(offer.buyer) < 0) continue;
std::string line = player + ": the bid of " + utf8(g.club_name(offer.buyer)) + " was not accepted";
for (const auto& winner : event.offers.offers)
if (event.accepted && winner.present && winner.bid_index == event.selected_bid_index)
line += " - he signs for " + utf8(g.club_name(winner.buyer));
run->notices.push_back(line);
}
});
session_->set_pending_offer_entry_policy(app::PendingOfferEntryPolicy::normal_interactive);
// The season change inside the kickoff (season_transition): the tax notice and the
// question whether to "adjust" the tax return (GameEndTaxAnimationScreen, Season_SeasonApplyProfitTax_TextPointer3; caught or not
// follows), the promoted/relegated clubs and the cup draws, as the SDL app shows them.
SeasonTaxHooks tax;
tax.observe = [run](const GameState&, const SeasonTaxEvent& e) {
if (!e.text.empty()) run->notices.push_back(utf8(e.text));
};
tax.choose = [run](const GameState&, const SeasonTaxEvent& e) {
return run->ask(e.manager_slot + 1, utf8(e.text), {"Yes", "No"}, "No") == "Yes";
};
session_->set_season_tax(std::move(tax));
session_->set_season_promotion([run](const GameState& g, const SeasonPromotionEvent& e) {
// The first promotion screen comes before any club changes its league: the tables
// are final here. The managers' leagues are listed once each (the table window
// shows the new season afterwards).
if (e.group == 0) {
std::set<int> shown;
for (size_t m = 0; m < g.manager_teams.size(); ++m) {
const int league = team_league(g.manager_teams[m]);
if (league < 0 || league >= kLeagueCount || !shown.insert(league).second) continue;
const ui::LeagueTableState t = ui::league_table_from_game(g, int(m), league);
std::string line = "final table " + t.league_name + ":";
for (const auto& r : t.rows)
line += " " + std::to_string(r.rank) + ". " + r.name + " " + std::to_string(r.points) + ";";
run->notices.push_back(line);
}
}
static const char* const kGroups[4] = {"1st division", "2nd division", "3rd divisions", "4th division"};
std::string up, down;
for (size_t i = 0; i < e.count && i < e.promoted.size(); ++i) up += (up.empty() ? "" : ", ") + utf8(g.club_name(e.promoted[i]));
for (size_t i = 0; i < e.count && i < e.relegated.size(); ++i) down += (down.empty() ? "" : ", ") + utf8(g.club_name(e.relegated[i]));
run->notices.push_back(std::string(kGroups[std::clamp(e.group, 0, 3)]) + ": relegated " + down + "; promoted " + up);
});
session_->set_season_cup_draw([run](const GameState& g, const SeasonCupDrawEvent& e) {
if (e.phase != SeasonCupDrawPhase::draw) return;
std::string pairs;
for (size_t i = 0; i + 1 < e.participants.size() && i + 1 < e.count; i += 2)
pairs += (pairs.empty() ? "" : "; ") + utf8(g.club_name(e.participants[i])) + " - " + utf8(g.club_name(e.participants[i + 1]));
run->notices.push_back("cup draw (competition " + std::to_string(e.competition) + ", round " + std::to_string(e.round + 1) + "): " + pairs);
});
session_->set_live_minute([run](int minute, MatchEngine& engine, std::vector<MatchGroup>& groups, GameState& g) {
if (run->aborted) throw std::runtime_error("console matchday aborted");
if (!engine.show) engine.show = &run->events;
// remember which matches have a human team: only their events are printed (07-spieltag 3.1)
for (size_t gi = 0; gi < groups.size(); ++gi)
for (size_t mi = 0; mi * 2 + 1 < groups[gi].fixtures.size(); ++mi)
for (int side = 0; side < 2; ++side)
if (std::find(g.manager_teams.begin(), g.manager_teams.end(), groups[gi].fixtures[mi * 2 + size_t(side)]) !=
g.manager_teams.end())
run->human_matches.insert({int(gi), int(mi)});
if (run->to_end || !human_playing(groups, g)) return;
if (run->until >= 0) {
if (minute < run->until) return;
run->until = -1;
} else if (run->steps > 0 && --run->steps > 0) {
return;
}
// pause: hand the clock to the console until it lets the engine run again
std::unique_lock lock(run->m);
run->minute = minute;
run->engine = &engine;
run->groups = &groups;
run->state = &g;
run->engine_turn = false;
run->cv.notify_all();
run->cv.wait(lock, [run] { return run->engine_turn; });
run->engine = nullptr;
run->groups = nullptr;
run->state = nullptr;
if (run->aborted) throw std::runtime_error("console matchday aborted");
});
run->engine_turn = true;
run->worker = std::thread([this, run, request] {
TurnAdvanceResult result;
std::string error;
try {
result = session_->dispatch_kickoff(request, revision_, error);
} catch (const std::exception& e) {
result.kind = TurnDeskKind::Failed;
error = std::string("engine exception: ") + e.what();
}
std::unique_lock lock(run->m);
run->result = result;
run->error = error;
run->finished = true;
run->engine_turn = false;
run->cv.notify_all();
});
{
std::unique_lock lock(run->m);
run->cv.wait(lock, [run] { return !run->engine_turn; });
}
engine_returned();
}
// Lets the engine run until the next pause or the end of the day.
void Console::resume_matchday() {
EngineRun* run = run_.get();
if (!run) fail("E_RULE", "no matchday is running");
if (!run->finished) {
std::unique_lock lock(run->m);
run->engine_turn = true;
run->cv.notify_all();
run->cv.wait(lock, [run] { return !run->engine_turn; });
}
engine_returned();
}
// The engine thread waits (a minute pause or a question) or has finished the kickoff:
// show the pause, ask the question, or finish (results, next desk).
void Console::engine_returned() {
EngineRun* run = run_.get();
for (const auto& n : run->notices) emit('i', n);
run->notices.clear();
if (!run->finished && run->pause == EngineRun::Pause::question) {
// the question belongs to the manager concerned (his desk); the answer resumes the engine
set_window("Desktop", run->question_player);
ask(run->question_text, run->question_options, run->question_default, [this](const std::string& answer) {
run_->answer = answer;
resume_matchday();
});
return;
}
if (loan_return_offer_active()) {
const auto& state = *run->loan_state;
offer_editor_ = app::loan_return_offer_editor_projection(state, run->loan_owner, revision_,
!state.memory.has(::bmh::layout::TextGradientDisabled) || state.memory.u8(::bmh::layout::TextGradientDisabled) == 0);
offer_submitted_ = false;
set_window("Transfer.Negotiate", run->loan_owner.request.manager + 1);
emit('i', "Loan returned: negotiate a purchase with ShowNegotiation, SetOfferField, SubmitOffer; GoBack cancels the offer");
return;
}
if (!run->finished) {
show_match_pause();
return;
}
run->worker.join();
session_->set_live_minute({});
session_->set_pending_offer_hooks({});
session_->set_transfer_offer_selector({});
session_->set_transfer_decision_observer({});
session_->set_season_tax({});
session_->set_season_promotion({});
session_->set_season_cup_draw({});
session_->set_pending_offer_entry_policy(app::PendingOfferEntryPolicy::legacy_unpresented);
session_->set_contract_expiry_presenter({});
session_->set_loan_return_presenter({});
session_->set_loan_return_offer_presenter({});
// the events after the last pause
if (!run->aborted && !run->quiet && run->printed < run->events.size()) show_match_pause();
const ui::DeskState before = run->before;
const TurnAdvanceResult result = run->result;
const std::string error = run->error;
const bool aborted = run->aborted;
run_.reset();
if (aborted) {
set_window("Desktop", int(session_->state().memory.u8(::bmh::layout::ActiveManager)) + 1);
return;
}
finish_kickoff(before, result, error);
}
void Console::stop_matchday() {
if (!run_) return;
run_->to_end = true;
// Termination must not silently choose a default answer or commit a staged
// return/purchase. Wake the Source owner with an abort; CareerSession owns rollback.
run_->aborted = true;
question_.reset();
offer_editor_.reset();
resume_matchday();
}
bool Console::loan_return_offer_active() const {
return run_ && !run_->finished && run_->pause == EngineRun::Pause::loan_offer;
}
bool Console::loan_return_modal_active() const {
return run_ && (run_->loan_question || loan_return_offer_active());
}
std::optional<app::CareerSession::TransferOfferEditorDispatch> Console::dispatch_loan_return_offer(
const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& presenters, std::string& error,
const app::TransferOfferTeamInfoPresenter& team_info,
const app::TransferOfferPlayerInfoPresenter& player_info) {
error.clear();
if (!loan_return_offer_active()) { error = "no loan-return editor"; return std::nullopt; }
auto& run = *run_;
// Match the complete identity/quote to the Source owner. The UI fields may
// already contain the proposed value, so validate against a fresh projection.
const auto projected = app::loan_return_offer_editor_projection(*run.loan_state, run.loan_owner, revision_, false);
const auto expected = app::TransferActions::editor(projected, request.kind, request.field, request.value);
if (request.identity.manager_slot != expected.identity.manager_slot ||
request.identity.runtime_club != expected.identity.runtime_club ||
request.identity.list_entry != expected.identity.list_entry ||
request.identity.source_slot != expected.identity.source_slot ||
request.identity.player != expected.identity.player || request.identity.seller != expected.identity.seller ||
request.identity.bid_slot != expected.identity.bid_slot || request.identity.revision != revision_ ||
request.quoted_fee != expected.quoted_fee || request.quoted_monthly_salary != expected.quoted_monthly_salary ||
request.quoted_years != expected.quoted_years) {
error = "loan return: mismatched editor identity or quote"; return std::nullopt;
}
auto next = *run.loan_state;
auto game = *run.loan_game;
auto random = *run.loan_random;
auto owner = run.loan_owner;
TransferActionResult action;
int completed = -1;
const bool information = request.kind == ui::OutgoingTransferRequestKind::team_info ||
request.kind == ui::OutgoingTransferRequestKind::player_info;
try {
if (request.kind == ui::OutgoingTransferRequestKind::quote_change) {
owner = app::edit_transfer_offer_from_ui(next, owner, request, game, random);
} else if (request.kind == ui::OutgoingTransferRequestKind::cancel) {
owner = cancel_transfer_offer_editor_source(next, owner);
completed = 0;
} else if (request.kind == ui::OutgoingTransferRequestKind::team_info ||
request.kind == ui::OutgoingTransferRequestKind::player_info) {
// These services already belong to the staged month transaction.
const auto valid = cancel_transfer_offer_editor_source(next, owner);
if (!valid.supported) { error = valid.reason; return std::nullopt; }
auto& services = *run.loan_services;
if (request.kind == ui::OutgoingTransferRequestKind::team_info) {
if (!team_info || !team_info(services, int(owner.request.expected_seller_word & 0x7fff), Image{}))
throw std::runtime_error("loan return: TeamInfo presenter stopped");
next = *run.loan_state; game = *run.loan_game; random = *run.loan_random;
owner = resume_transfer_offer_team_info_source(next, owner, random);
} else {
const auto selection = transfer_offer_player_info_selection_source(next, owner);
services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField, 1);
if (!player_info || !player_info(services, selection, Image{}))
throw std::runtime_error("loan return: PlayerInfo presenter stopped");
next = *run.loan_state; game = *run.loan_game; random = *run.loan_random;
owner = resume_transfer_offer_player_info_source(next, owner,
services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField), services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2), random);
}
} else if (request.kind == ui::OutgoingTransferRequestKind::submit) {
auto hooks = run.loan_hooks;
hooks.confirm = presenters.confirm;
hooks.notice = presenters.notice;
MinuteReport report;
auto result = submit_transfer_offer_editor_source(next, owner, random, hooks, report);
owner = std::move(result.editor); action = result.action;
if (report.unsupported || action.status == TransferActionStatus::unsupported) {
error = report.reason; return std::nullopt;
}
// DayStepRest2's SDL owner returns after these statuses even when the
// generic market editor would remain open. The month caller clears its row.
if (owner.closed || action.status == TransferActionStatus::pending ||
action.status == TransferActionStatus::rejected || action.status == TransferActionStatus::insufficient_funds)
completed = 1;
} else { error = "loan return: unsupported editor event"; return std::nullopt; }
if (!owner.supported) {
error = owner.reason;
if (information) stop_matchday();
return std::nullopt;
}
app::CareerSession::TransferOfferEditorDispatch result;
result.editor = app::loan_return_offer_editor_projection(next, owner, revision_, false);
result.editor.closed = owner.closed || completed >= 0;
result.action = action;
*run.loan_state = std::move(next);
*run.loan_game = game;
*run.loan_random = random;
run.loan_owner = std::move(owner);
run.loan_result = completed;
return result;
} catch (const std::exception& e) {
error = e.what();
// ClubModalServices also owns opaque transient bytes. Once an info
// presenter has entered, a failed event must discard the whole month
// transaction, not leave its partial effects for a later Cancel/Submit.
if (information) {
stop_matchday();
throw; // A presenter exception is an internal failure, not a rule refusal.
}
return std::nullopt;
}
}
void Console::finish_loan_return_offer() {
if (loan_return_offer_active() && run_->loan_result >= 0) resume_matchday();
}
// The new events since the last pause as "~" lines, then the human matches' scores.
void Console::show_match_pause() {
EngineRun* run = run_.get();
set_window("Match", 0);
if (!run->intro_shown && run->groups && run->state) {
// Info.MatchdayIntro (07-spieltag 2): the day's human matches
run->intro_shown = true;
emit('i', "Matchday: the clock stops after every minute; Step(n) or Run(Halftime|End)");
}
for (; run->printed < run->events.size(); ++run->printed) {
const ShowEvent& e = run->events[run->printed];
if (!run->human_matches.count({int(e.group), int(e.match)})) continue;
std::string what;
switch (e.what) {
case Show::Booking: what = std::string(booking_name(e.kind)) + ": "; break;
case Show::Substitution: what = "substitution: "; break;
case Show::Chance: what = e.flag ? "GOAL: " : "chance: "; break;
case Show::PenaltyKick: what = std::string("penalty ") + (e.flag ? "scored: " : "missed: "); break;
case Show::ShootoutEnd: what = "shoot-out: "; break;
default: continue; // set pieces and shots are picture data only
}
std::string text = utf8(e.text);
if (e.what == Show::Substitution && run->state && e.player >= 0 && e.player < 0xfff && e.other >= 0 && e.other < 0xfff)
text = utf8(run->state->player_name(e.other)) + " for " + utf8(run->state->player_name(e.player));
if (text.empty() && run->state && e.player >= 0 && e.player < 0xfff) text = utf8(run->state->player_name(e.player));
Json::Object data{{"kind", int(e.what)}, {"group", int(e.group)}, {"match", int(e.match)}, {"side", int(e.side)},
{"team", int(e.team)}, {"player", int(e.player)}, {"other", int(e.other)}};
emit('~', std::to_string(e.minute) + "' [match " + std::to_string(e.group) + "." + std::to_string(e.match) + "] " + what + text,
Json(std::move(data)));
}
if (!run->groups || !run->state) return;
const ui::LiveMatchdayFrame frame = ui::live_matchday_frame(run->minute, *run->groups, *run->state);
const auto& teams = run->state->manager_teams;
for (const auto& m : frame.matches) {
const bool human = std::find(teams.begin(), teams.end(), m.home_team) != teams.end() ||
std::find(teams.begin(), teams.end(), m.away_team) != teams.end();
if (!human) continue;
emit('i', std::to_string(run->minute) + "' " + utf8(m.home) + " " + std::to_string(m.home_goals) + ":" +
std::to_string(m.away_goals) + " " + utf8(m.away));
}
}
void Console::register_match_commands() {
auto paused = [this]() -> EngineRun& {
if (!run_ || run_->finished || !run_->state) fail("E_RULE", "no match is running");
return *run_;
};
add({"Match", "Step", {integer("minutes", 1, 130, true)}, "let the clock run n minutes (default 1)", true}, [this, paused](const Values& v) {
paused().steps = int(v.integer("minutes", 1));
resume_matchday();
});
add({"Match", "Run", {choice("until", {"Halftime", "End"}, true)}, "run to half time or to the end of the day", true},
[this, paused](const Values& v) {
EngineRun& run = paused();
if (v.has("until") && v.choice("until") == 0) {
// the indoor tournament plays 2 x 20 minutes (driver.cpp): its half time is at
// 20; waiting for 45 there ran the whole day through (learning session F-run2-004)
const int half = run.state && run.state->indoor ? 20 : 45;
if (run.minute >= half) fail("E_RULE", "half time is over");
run.until = half;
} else {
run.to_end = true;
}
resume_matchday();
});
add({"Match", "ShowMatchStats", {integer("match", 0, 99, true)}, "the scoreboard: score, chances, cards, spectators, weather", false},
[this, paused](const Values&) {
EngineRun& run = paused();
const ui::LiveMatchdayFrame frame = ui::live_matchday_frame(run.minute, *run.groups, *run.state);
std::vector<std::vector<std::string>> rows;
for (const auto& m : frame.matches)
rows.push_back({utf8(m.home), utf8(m.away), std::to_string(m.home_goals) + ":" + std::to_string(m.away_goals),
std::to_string(m.home_stats[1]) + "/" + std::to_string(m.away_stats[1]),
m.spectators_known ? std::to_string(m.spectators) : "-", utf8(m.temperature_text)});
emit_table({"Home", "Away", "Score", "Chances", "Spectators", "Weather"}, rows);
});
// the human team a command acts for: @n, or the only human team playing
auto team_of = [this, paused](const Values& v) {
EngineRun& run = paused();
const auto& teams = run.state->manager_teams;
if (v.player) {
if (size_t(v.player) > teams.size()) fail("E_BAD_ARGUMENT", "there is no player " + std::to_string(v.player));
return teams[size_t(v.player - 1)];
}
if (teams.size() > 1) fail("E_BAD_ARGUMENT", "with several managers write @n before the command");
return teams.front();
};
// the squad rows of a team in the running match: 0-10 on the pitch, bench rows have 0x4000
auto squad_refs = [this, paused](int team) {
EngineRun& run = paused();
const SquadRange range = squad_range(team);
std::vector<PlayerRef> refs;
for (size_t row = 0; row < range.count; ++row) {
const uint16_t slot = run.state->squad_slots.at(range.first + row);
if ((slot & 0x0fff) == 0x0fff || !(slot & 0xc000)) continue;
refs.push_back({int(row), slot & 0x0fff, utf8(run.state->player_name(slot & 0x0fff))});
}
return refs;
};
add({"Match", "ShowSquad", {}, "your team on the pitch and on the bench", false}, [this, paused, team_of, squad_refs](const Values& v) {
EngineRun& run = paused();
const int team = team_of(v);
const SquadRange range = squad_range(team);
std::vector<std::vector<std::string>> rows;
for (const auto& r : squad_refs(team)) {
const uint16_t slot = run.state->squad_slots.at(range.first + size_t(r.row));
rows.push_back({"row:" + std::to_string(r.row), r.name, (slot & 0x8000) ? "pitch" : "bench"});
}
emit_table({"Row", "Player", "Place"}, rows);
});
Param out = detail::text("out"), in = detail::text("in");
out.display = "out:Player";
in.display = "in:Player";
add({"Match", "Substitute", {out, in}, "a substitution: a player leaves, a bench player comes on", true},
[this, paused, team_of, squad_refs](const Values& v) {
EngineRun& run = paused();
const int team = team_of(v);
const auto refs = squad_refs(team);
const PlayerRef leaving = refs[resolve_player(v.text("out"), refs)];
const PlayerRef coming = refs[resolve_player(v.text("in"), refs)];
const SquadRange range = squad_range(team);
if (!(run.state->squad_slots.at(range.first + size_t(leaving.row)) & 0x8000))
fail("E_RULE", leaving.name + " is not on the pitch");
if (!(run.state->squad_slots.at(range.first + size_t(coming.row)) & 0x4000))
fail("E_RULE", coming.name + " is not on the bench");
// manual_substitution refuses after kMaxSubstitutions or for a player who already played
if (!manual_substitution(*run.state, team, leaving.row, coming.row))
fail("E_RULE", "no substitution possible (" + std::to_string(kMaxSubstitutions) + " used, or the player already played)");
MinuteReport report;
run.engine->rerate_team(team, report);
if (report.unsupported) fail("E_INTERNAL", "re-rating after the substitution: " + report.reason);
emit('+', std::to_string(run.minute) + "' substitution: " + coming.name + " for " + leaving.name);
});
// --- the tactics board during the match (the original's live tactics, mode 8) ---------
// The tactics of the manager's team as the match sees them (ActiveManager set to him, as
// the SDL live tactics screen does).
auto live_tactics = [this, paused](int manager) {
EngineRun& run = paused();
GameState view = *run.state;
if (view.memory.has(::bmh::layout::ActiveManager)) view.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager));
return ui::tactics_from_game(view, exe_, revision_);
};
add({"Match", "ShowTactics", {}, "the eight tactic settings of your team in this match", false},
[this, paused, team_of, live_tactics](const Values& v) {
EngineRun& run = paused();
const int team = team_of(v);
const ui::TacticsState t = live_tactics(run.state->manager_of(team));
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 8; ++i) rows.push_back({std::to_string(i), detail::kTacticNames[i], std::to_string(t.values[i])});
emit_table({"Item", "Setting", "Value"}, rows);
if (t.assistant_attitude) emit('i', "the assistant adapts the attitude (item 0) to the score");
});
// One change of a tactic setting in the running match: the session opens the live
// intervention (begin_live_intervention, mode 8), applies the request like the tactics
// window (dispatch_live_tactic re-rates the side) and closes it; a refused change aborts
// the intervention, so the match goes on as before. From minute 3 on, as in the SDL app.
add({"Match", "SetTactic", {integer("item", 0, 7), integer("value", 0, 11)},
"change a tactic setting during the match (item 0 ends the assistant's D/O control)", true},
[this, paused, team_of, live_tactics](const Values& v) {
EngineRun& run = paused();
const int team = team_of(v);
const int manager = run.state->manager_of(team);
if (manager < 0) fail("E_RULE", "not a human team");
if (run.minute <= 2) fail("E_RULE", "tactics can be changed from minute 3 on");
const int item = int(v.integer("item")), value = int(v.integer("value"));
std::string error;
if (!session_->begin_live_intervention(run.minute, 8, manager, team, *run.engine, revision_, error))
require_engine(false, "live tactics", error);
const ui::TacticsState t = live_tactics(manager);
ui::TacticsRequest req;
req.kind = ui::TacticsRequestKind::set_tactic;
req.manager_slot = t.manager_slot;
req.runtime_club = t.runtime_club;
req.revision = revision_;
req.index = item;
req.desired_value = value;
if (item == 0) req.desired_assistant_attitude = 0;
if (!session_->dispatch_live_tactic(req, run.minute, 8, *run.engine, revision_, error)) {
session_->abort_live_intervention(run.minute, 8, manager, team, *run.engine, revision_);
require_engine(false, "live tactics", error);
}
if (!session_->finish_live_intervention(run.minute, 8, manager, team, *run.engine, revision_, error)) {
session_->abort_live_intervention(run.minute, 8, manager, team, *run.engine, revision_);
require_engine(false, "live tactics", error);
}
emit('+', std::to_string(run.minute) + "' tactics: item " + std::to_string(item) + " = " + std::to_string(value));
});
// Re-arranging the side in the running match (the live line-up, mode 2). The original's
// PitchScreen offers no formation templates during a match (its param_2 is nonzero:
// formations and automatic weights belong to the preparation only); a starter can be
// placed on another depth/lane, as Lineup.Pitch MovePlayer does before the match.
Param mover = detail::text("player");
mover.display = "player:Player";
add({"Match", "MovePlayer", {mover, integer("depth", 0, 19), integer("lane", 0, 8)},
"place a starter on another position for the rest of the match (from minute 3)", true},
[this, paused, team_of](const Values& v) {
EngineRun& run = paused();
const int team = team_of(v);
const int manager = run.state->manager_of(team);
if (manager < 0) fail("E_RULE", "not a human team");
if (run.minute <= 2) fail("E_RULE", "positions can be changed from minute 3 on");
std::string error;
if (!session_->begin_live_intervention(run.minute, 2, manager, team, *run.engine, revision_, error))
require_engine(false, "live position", error);
auto abort = [&](const std::string& why) {
session_->abort_live_intervention(run.minute, 2, manager, team, *run.engine, revision_);
require_engine(false, "live position", why);
};
// the projection of the paused match for the manager (as the SDL live line-up)
GameState view = *run.state;
if (view.memory.has(::bmh::layout::ActiveManager)) view.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager));
ui::PreparationState p = ui::preparation_from_game(view, exe_, revision_);
p.lineup.in_match = true;
p.lineup.entry_prepared = true;
if (!p.pitch || !p.pitch->indoor.has_value()) abort("no pitch projection in this match");
std::vector<PlayerRef> refs;
for (const auto& pl : p.lineup.players)
if (pl.player_id >= 0) refs.push_back({pl.row, pl.player_id, utf8(pl.name)});
const int index = resolve_player(v.text("player"), refs);
const ui::LineupPlayer& player = p.lineup.players.at(size_t(refs[size_t(index)].row));
if (player.row >= 11 || !(player.slot & 0x8000)) abort(utf8(player.name) + " is not on the pitch");
const ui::PitchRequest r = app::LineupActions::move(p, player, int(v.integer("depth")), int(v.integer("lane")));
const app::LiveSubstitutionResult result = session_->dispatch_live_pitch_result(r, run.minute, 2, *run.engine, revision_);
if (result.status == app::LiveSubstitutionStatus::rejected) abort(result.error.empty() ? "refused" : result.error);
if (!session_->finish_live_intervention(run.minute, 2, manager, team, *run.engine, revision_, error)) abort(error);
emit('+', std::to_string(run.minute) + "' " + utf8(player.name) + " to depth " + std::to_string(v.integer("depth")) +
", lane " + std::to_string(v.integer("lane")));
});
add({"Match", "SetFormation", {integer("slot", 1, 8)}, "not during a match (move single players with MovePlayer)", true},
[](const Values&) {
fail("E_RULE", "the original offers no formation templates during a match; MovePlayer places single players");
});
for (const char* name : {"SetMarking", "SetOrder", "Open", "Watch", "Pause", "Resume"})
add({"Match", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " during the match is not in the console yet"); });
// GoBack in the match: the original opens the tactics of the own team (02-fenster 3);
// until Match.Tactics exists the clock simply keeps waiting
closers_["Match"] = [this] { emit('+', "the match waits: Step(n) or Run(Halftime|End)"); };
}
std::string Console::match_status() const {
if (!run_) return {};
if (loan_return_offer_active()) return "matchday paused for loan-return negotiation";
return "matchday running, minute " + std::to_string(run_->minute);
}
} // namespace bmh::cli::console
+544
View File
@@ -0,0 +1,544 @@
// SPDX-License-Identifier: GPL-3.0-only
// The money windows of docs/CLI_CONCEPT/06-verein.md: Bank (menu 14) with savings, shares and
// real estate, Stadium (menu 22) with the periphery and the stand blocks, and Toto (menu 13).
// Views from CareerSession::preparation_projection; changes through dispatch_bank /
// dispatch_stadium / dispatch_toto with the requests the SDL screens build.
//
// Opening the stadium draws random numbers (CareerSession::dispatch_stadium "open":
// construction_price_percent restarts the game generator), so the console opens it through
// the engine exactly when the window opens, never as a side effect of a read command.
#include <algorithm>
#include <limits>
#include "app/window_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/bank_credit.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// TEXTD indices (docs/formats/textd_inventory.csv)
constexpr int kFinanceLabels = 339; // Bank_OriginalToUtf8_RuntimeField6: the seven lines of the finance overview
constexpr int kCreditLabels = 352; // Bank_OriginalToUtf8_TextPointer4: the credit view's eight lines
constexpr int kShareNames = 322; // Bank_FormatError_ExecutableField2: the twelve listed companies (sponsorNameC01..)
constexpr int kShareTips = 334; // Bank_FormatError_RuntimeField19: schnell verk. / verkaufen / halten / kaufen ...
constexpr int kPeripheryNames = 720; // Stadium_RenderPanorama_TextPointer: stadiumFeatureTrafficAccess .. FanShop4 (14)
constexpr int32_t kMaxMoney = std::numeric_limits<int32_t>::max();
} // namespace
void Console::register_money_commands() {
// --- Bank (06-verein: Bank) -----------------------------------------------------------
auto bank = [this] {
const auto p = prep();
if (!p.bank) fail("E_MODE_LOCKED", "no bank available (national team?)");
return *p.bank;
};
auto dispatch_bank = [this](const ui::BankRequest& r) {
std::string error;
require_engine(app::BankActions(*session_).dispatch(r, revision_, error), "bank", error);
};
auto show_bank = [this, bank] {
const ui::BankState b = bank();
emit_table({"Bank", "Value"},
{{"balance", money(b.balance)}, {"savings", money(b.deposit)}, {"creditLine", money(b.credit_line)},
// record +0x324: the balance the season result is measured from (season start,
// moved with deposits and share deals; result = balance - this, season.cpp)
{"seasonBase", money(b.investment_balance)}});
};
openers_[14] = [this, show_bank] {
open_window("Bank");
show_bank();
};
add({"Bank", "ShowBank", {}, "balance, savings, credit line, season base", false}, [show_bank](const Values&) { show_bank(); });
auto show_overview = [this, bank] {
const ui::BankState b = bank();
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 7; ++i) rows.push_back({text(kFinanceLabels + int(i)), money(b.finance_values[i])});
emit_table({"Finance", "Value"}, rows);
};
// opening a bank page shows its content at once (as the original screen does)
add({"Bank", "OpenAccount", {}, "the finance overview (Bank.Account)", false}, [this, show_overview](const Values&) {
open_window("Bank.Account");
show_overview();
});
add({"Bank", "OpenSavings", {}, "the fixed deposit (Bank.Savings)", false}, [this](const Values&) { open_window("Bank.Savings"); emit('+', "savings (ShowSavings, Deposit, Withdraw)"); });
add({"Bank", "OpenShares", {}, "the stock market (Bank.Shares)", false}, [this](const Values&) { open_window("Bank.Shares"); emit('+', "shares (ListShares, ShowShare, BuyShares, SellShares)"); });
add({"Bank", "OpenRealEstate", {}, "real estate funds (Bank.RealEstate)", false}, [this](const Values&) { open_window("Bank.RealEstate"); emit('+', "real estate (ListRealEstate shows the funds)"); });
Param lender = choice("lender", {"Bank", "Manager1", "Manager2", "Manager3", "Manager4"}, true);
add({"Bank", "OpenCredit", {lender}, "the credit view (Bank.Credit)", false}, [this](const Values& v) {
// case 5 (MaxSharesToBuy): a credit from another human manager (row lender + 1)
const int lender = v.has("lender") ? v.choice("lender") - 1 : -1;
if (lender >= 0 && (size_t(lender) >= session_->state().manager_teams.size() || lender == active_slot()))
fail("E_RULE", "no other manager " + std::to_string(lender + 1) + " in this game");
credit_counterparty_ = lender + 1;
credit_draft_.reset();
open_window("Bank.Credit");
emit('+', std::string("credit ") + (lender >= 0 ? "from player " + std::to_string(lender + 1) : "from the bank") + " (ShowCredit)");
});
add({"Bank.Account", "ShowFinanceOverview", {}, "assets, debts and net worth", false},
[show_overview](const Values&) { show_overview(); });
add({"Bank.Account", "ShowAssetProfitLoss", {integer("asset", 0, 11)}, "profit/loss of a share", false}, [this, bank](const Values& v) {
const ui::BankState b = bank();
const auto& s = b.stocks[size_t(v.integer("asset"))];
emit_table({"Share", "Owned", "Paid", "Price", "Value"},
{{text(kShareNames + int(v.integer("asset"))), std::to_string(s.owned), money(s.paid), std::to_string(s.price),
money(int64_t(s.owned) * s.price)}});
});
auto show_savings = [this, bank] {
const ui::BankState b = bank();
emit_table({"Savings", "Value"}, {{"balance", money(b.balance)}, {"savings", money(b.deposit)}});
};
add({"Bank.Savings", "ShowSavings", {}, "account and fixed deposit", false}, [show_savings](const Values&) { show_savings(); });
add({"Bank.Savings", "Deposit", {integer("amount", 1, kMaxMoney)}, "account -> fixed deposit", true},
[bank, dispatch_bank, show_savings](const Values& v) {
const auto r = app::BankActions::savings(bank(), int32_t(v.integer("amount")));
dispatch_bank(r);
show_savings();
});
add({"Bank.Savings", "Withdraw", {integer("amount", 1, kMaxMoney)}, "fixed deposit -> account", true},
[bank, dispatch_bank, show_savings](const Values& v) {
const auto r = app::BankActions::savings(bank(), -int32_t(v.integer("amount")));
dispatch_bank(r);
show_savings();
});
auto share_row = [this](const ui::BankState& b, size_t i) {
const auto& s = b.stocks[i];
std::string trend = s.price > s.previous_price ? "up" : s.price < s.previous_price ? "down" : "=";
return std::vector<std::string>{std::to_string(i), text(kShareNames + int(i)), std::to_string(s.price), trend,
std::to_string(s.owned), money(s.paid), std::to_string(s.max_to_buy)};
};
const std::vector<std::string> share_header = {"Asset", "Share", "Price", "Trend", "Owned", "Paid", "MaxBuy"};
add({"Bank.Shares", "ListShares", {}, "the twelve shares", false}, [this, bank, share_row, share_header](const Values&) {
const ui::BankState b = bank();
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 12; ++i) rows.push_back(share_row(b, i));
emit_table(share_header, rows);
});
add({"Bank.Shares", "ShowShare", {integer("asset", 0, 11)}, "one share with its last 30 prices", false},
[this, bank, share_row, share_header](const Values& v) {
const ui::BankState b = bank();
const size_t i = size_t(v.integer("asset"));
emit_table(share_header, {share_row(b, i)});
std::string history;
for (uint16_t p : b.stocks[i].history) history += (history.empty() ? "" : " ") + std::to_string(p);
emit('i', "history: " + history);
});
add({"Bank.Shares", "ShareAdvice", {integer("asset", 0, 11)}, "the bank's tip for a share", true},
[this, bank, dispatch_bank](const Values& v) {
const auto r = app::BankActions::investment(bank(), ui::BankRequestKind::stock_tip, int(v.integer("asset")));
dispatch_bank(r);
// the screen shows the TEXTD advice Bank_FormatError_RuntimeField19 + tip * 4 (src/ui/bank.cpp)
const ui::BankState b = bank();
if (!b.last_tip) fail("E_INTERNAL", "the bank gave no tip");
emit('+', text(kShareNames + r.asset_index) + ": " + text(kShareTips + *b.last_tip));
});
auto trade = [this, bank, dispatch_bank, share_row, share_header](const Values& v, ui::BankRequestKind kind) {
const auto r = app::BankActions::investment(bank(), kind, int(v.integer("asset")), int(v.integer("count")));
dispatch_bank(r);
emit_table(share_header, {share_row(bank(), size_t(r.asset_index))});
};
add({"Bank.Shares", "BuyShares", {integer("asset", 0, 11), integer("count", 1, 9999)}, "buy shares", true},
[trade](const Values& v) { trade(v, ui::BankRequestKind::buy_shares); });
add({"Bank.Shares", "SellShares", {integer("asset", 0, 11), integer("count", 1, 9999)}, "sell shares", true},
[trade](const Values& v) { trade(v, ui::BankRequestKind::sell_shares); });
auto show_funds = [this, bank] {
const ui::BankState b = bank();
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 6; ++i) {
const auto& f = b.funds[i];
// the original writes the name stem plus a singular/plural ending (Bank_OriginalToUtf8_RuntimeField)
rows.push_back({std::to_string(i), utf8(f.name) + f.plural_suffix, money(f.price), std::to_string(f.owned), money(f.paid), std::to_string(f.max_to_buy)});
}
emit_table({"Type", "Fund", "Price", "Owned", "Paid", "MaxBuy"}, rows);
if (b.property_notice) emit('i', utf8(b.property_notice->text));
};
add({"Bank.RealEstate", "ListRealEstate", {}, "the six real estate funds", false}, [show_funds](const Values&) { show_funds(); });
add({"Bank.RealEstate", "BuyRealEstate", {integer("type", 0, 5), integer("units", 1, 10)}, "buy units", true},
[bank, dispatch_bank, show_funds](const Values& v) {
const auto r = app::BankActions::investment(bank(), ui::BankRequestKind::buy_fund,
int(v.integer("type")), int(v.integer("units")));
dispatch_bank(r);
show_funds();
});
add({"Bank.RealEstate", "SellRealEstate", {integer("type", 0, 5), integer("units", 1, 10)}, "sell units", true},
[bank, dispatch_bank, show_funds](const Values& v) {
const auto r = app::BankActions::investment(bank(), ui::BankRequestKind::sell_fund,
int(v.integer("type")), int(v.integer("units")));
dispatch_bank(r);
show_funds();
});
// --- Bank.Credit: the bank's credit editor (MaxSharesToBuy case 4, H2 p. 60-61) ----------
// As the screen does it (src/ui/bank.cpp): a local draft of the eight rows, edited field
// by field within the engine's bounds (bank_credit_bounds / edit_bank_credit, read-only);
// ConfirmCredit books the edits through dispatch_bank (commit_bank_credit replays them
// against the saved loan). Fees (5,000 EU for a change, interest adjustment) need a yes.
// the loan row of the open credit: the bank's from the bank projection, a manager's from the
// engine (bank_credit_context with the counterparty)
auto credit_context = [this, bank] {
if (credit_counterparty_ == 0) return bank().credit;
return bank_credit_context(session_->state(), exe_, active_slot(), credit_counterparty_);
};
auto credit_draft = [this, credit_context] {
if (!credit_draft_) credit_draft_ = bank_credit_draft(credit_context());
return *credit_draft_;
};
auto show_credit = [this, credit_context, credit_draft] {
const BankCreditDraft d = credit_draft();
std::vector<std::vector<std::string>> rows;
for (int i = 0; i < 8; ++i) {
const BankCreditBounds bounds = bank_credit_bounds(credit_context(), d, i);
rows.push_back({std::to_string(i), text(kCreditLabels + i), money(d.values[size_t(i)]),
bounds.available ? money(bounds.minimum) + ".." + money(bounds.maximum) : "-"});
}
emit_table({"Row", "Credit", "Value", "Editable"}, rows);
// only the bank charges fees and the interest adjustment (case 5 has none)
const int32_t fees = credit_counterparty_ ? 0 : d.fees + d.interest_adjustment;
if (!d.edits.empty()) emit('i', "changes not booked yet" + (fees ? ", fees and interest " + money(fees) : std::string()));
};
// the editable rows: 0 amount paid out, 1 total amount, 3 term, 6 repayment
auto edit_credit = [this, credit_context, credit_draft, show_credit](int field, long long value) {
BankCreditDraft d = credit_draft();
const BankCreditBounds bounds = bank_credit_bounds(credit_context(), d, field);
if (!bounds.available) fail("E_RULE", text(kCreditLabels + field) + " cannot be changed now");
if (value < bounds.minimum || value > bounds.maximum)
fail("E_BAD_ARGUMENT", text(kCreditLabels + field) + " must be " + money(bounds.minimum) + ".." + money(bounds.maximum));
if (!edit_bank_credit(credit_context(), d, field, uint32_t(value))) fail("E_RULE", "the bank does not accept this value");
credit_draft_ = d;
show_credit();
};
add({"Bank.Credit", "ShowCredit", {lender}, "the credit rows with the editable ranges", false},
[show_credit](const Values&) { show_credit(); });
add({"Bank.Credit", "SetCreditAmount", {integer("amount", 0, kMaxMoney)}, "AUSGEZAHLTER BETRAG: the credit", false},
[edit_credit](const Values& v) { edit_credit(0, v.integer("amount")); });
add({"Bank.Credit", "SetCreditPayment", {integer("monthly", 0, kMaxMoney)},
"the monthly payment: within 20 % of the annuity for a credit from a manager", false},
[this, edit_credit](const Values& v) {
if (credit_counterparty_ == 0) fail("E_RULE", "the monthly payment follows from the amount and the term (SetCreditTerm)");
edit_credit(2, v.integer("monthly"));
});
add({"Bank.Credit", "SetCreditTerm", {integer("months", 1, 48)}, "LAUFZEIT in months", false},
[edit_credit](const Values& v) { edit_credit(3, v.integer("months")); });
Param repay = detail::text("amount");
repay.display = "amount:money|All";
add({"Bank.Credit", "RepayCredit", {repay}, "RÜCKZAHLUNG: pay back (All = as much as possible)", false},
[this, credit_context, credit_draft, edit_credit](const Values& v) {
Arg a;
a.text = v.text("amount");
long long amount = 0;
if (lower(a.text) == "all") {
const BankCreditBounds bounds = bank_credit_bounds(credit_context(), credit_draft(), 6);
if (!bounds.available) fail("E_RULE", "nothing to repay");
amount = bounds.maximum;
} else if (const auto n = to_int(a)) {
amount = *n;
} else {
fail("E_BAD_ARGUMENT", "amount is a number or All");
}
edit_credit(6, amount);
});
auto book = [this, bank, credit_context, credit_draft, dispatch_bank](bool accept_fees) {
const BankCreditDraft d = credit_draft();
const auto r = app::BankActions::credit(bank(), credit_context(), d, accept_fees, credit_counterparty_);
dispatch_bank(r);
credit_draft_.reset();
const ui::BankState after = bank();
if (after.credit_notice) emit('i', after.credit_notice->text);
emit('+', "credit booked, balance " + money(after.balance));
};
add({"Bank.Credit", "ConfirmCredit", {}, "book the changes (asks about fees)", true}, [this, credit_draft, book](const Values&) {
const BankCreditDraft d = credit_draft();
if (d.edits.empty()) fail("E_RULE", "nothing changed");
const int32_t fees = credit_counterparty_ ? 0 : d.fees + d.interest_adjustment;
if (fees == 0) {
book(false);
return;
}
// the screen's fee confirmation (credit_fee_confirmation_open_); the console's wording
ask("The change costs " + money(fees) + " in fees and interest. Book it?", {"Yes", "No"}, "No", [this, book](const std::string& answer) {
if (answer == "Yes") book(true);
else emit('+', "credit not changed (the draft stays)");
});
});
add({"Bank.Credit", "CancelCredit", {}, "discard the changes", false}, [this](const Values&) {
credit_draft_.reset();
emit('+', "credit changes discarded");
});
// --- Stadium (06-verein 8) ------------------------------------------------------------
auto stadium = [this] {
const auto p = prep();
if (!p.stadium) fail("E_MODE_LOCKED", "no stadium view (national team?)");
return *p.stadium;
};
// Requests carry the engine's stadium scope (stable club, scope, sequence) as the SDL
// screen's do (StadiumScreen::request); a stale request is refused by the engine.
auto stadium_request = [](const ui::StadiumState& observed, ui::StadiumRequestKind kind,
int object = -1, int option = -1, int32_t price = 0, bool accept_tip = false) {
return app::StadiumActions::request(observed, kind, object, option, price, accept_tip);
};
auto dispatch_stadium = [this](const ui::StadiumRequest& r) {
std::string error;
require_engine(app::StadiumActions(*session_).dispatch(r, revision_, error), "stadium", error);
};
auto show_stadium = [this, stadium] {
const ui::StadiumState s = stadium();
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 8; ++i) {
const auto& row = s.investments[i];
std::string offers;
for (size_t o = 0; o < row.options.size(); ++o)
offers += (o ? ", " : "") + std::string("level ") + std::to_string(row.options[o].target_level) + " for " +
money(row.options[o].base_price);
rows.push_back({std::to_string(i), utf8(row.original_label), std::to_string(row.current_level),
row.construction_weeks ? std::to_string(row.construction_weeks) + " weeks" : "-",
row.available && !row.options.empty() ? offers : "-"});
}
emit_table({"Item", "Name", "Level", "Building", "Options"}, rows);
std::vector<std::vector<std::string>> blocks;
for (size_t b = 0; b < 8; ++b)
blocks.push_back({std::string(1, char('A' + b)), std::to_string(int(s.blocks[b].capacity_level) * 1000),
s.blocks[b].construction_weeks ? std::to_string(int(s.blocks[b].capacity) * 1000) : "-",
s.blocks[b].construction_weeks ? std::to_string(s.blocks[b].construction_weeks) + " weeks" : "-"});
emit_table({"Block", "Places", "PlannedPlaces", "Building"}, blocks);
emit('i', "balance " + money(s.balance) + ", construction prices " + std::to_string(s.construction_percent) + " %" +
(s.action_feedback.empty() ? "" : ", " + utf8(s.action_feedback)));
};
auto show_periphery = [this, stadium] {
const ui::StadiumState s = stadium();
std::vector<std::vector<std::string>> rows;
for (size_t o = 0; o < 14; ++o) {
const bool building = s.days[o] != 0;
const bool built = o == 0 ? s.level[o] >= 0xab : s.level[o] != 0; // as dispatch_stadium checks
rows.push_back({std::to_string(o), text(kPeripheryNames + int(o)), building ? "building" : built ? "built" : "-",
std::to_string(s.days[o])});
}
emit_table({"Object", "Name", "State", "Days"}, rows);
emit('i', "balance " + money(s.balance));
};
openers_[22] = [this, stadium, stadium_request, dispatch_stadium, show_stadium] {
const ui::StadiumState s = stadium();
open_window("Stadium");
if (!s.opened) dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::open));
show_stadium();
};
// leaving the stadium is an engine step (close), refused while an offer is open
closers_["Stadium"] = [this, stadium, stadium_request, dispatch_stadium] {
const ui::StadiumState s = stadium();
if (s.opened) dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::close));
close_window();
emit('+', "stadium closed");
};
add({"Stadium", "ShowStadium", {}, "facilities, maintenance and blocks", false}, [show_stadium](const Values&) { show_stadium(); });
add({"Stadium", "OpenPeriphery", {}, "SICHT: PANORAMA (Stadium.Periphery)", false}, [this, show_periphery](const Values&) {
open_window("Stadium.Periphery");
show_periphery();
});
// AUSBAUEN for one of the eight investments (Front / PayConstruction): a tier is
// chosen, confirmed, then the builder asks about a tip; each answer is one engine step.
auto invest = [this, stadium, stadium_request, dispatch_stadium](int item) {
ui::StadiumState s = stadium();
const auto& row = s.investments[size_t(item)];
if (!row.available || row.options.empty())
fail("E_RULE", utf8(row.original_label) + (row.construction_weeks ? " is being built" : " cannot be built now"));
const std::string label = utf8(row.original_label);
dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::select_investment, item));
s = stadium();
std::vector<std::string> choices;
std::string list;
for (const auto& option : s.investments[size_t(item)].options) {
choices.push_back("Level" + std::to_string(option.target_level));
list += (list.empty() ? "" : ", ") + choices.back() + " = " + money(option.base_price);
}
choices.push_back("Cancel");
ask(label + ": " + list, choices, "Cancel", [this, item, label, stadium, stadium_request, dispatch_stadium](const std::string& answer) {
ui::StadiumState s = stadium();
if (answer == "Cancel") {
dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::cancel_investment, item));
emit('+', "nothing built");
return;
}
const auto& options = s.investments[size_t(item)].options;
int index = -1;
for (size_t o = 0; o < options.size(); ++o)
if ("Level" + std::to_string(options[o].target_level) == answer) index = int(o);
if (index < 0) fail("E_INTERNAL", "the offer changed");
const int32_t price = int32_t(options[size_t(index)].base_price);
dispatch_stadium(stadium_request(s, ui::StadiumRequestKind::select_investment_option, item, index, price));
dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::confirm_investment, item, index, price));
s = stadium();
if (!s.construction_tip_dialog) fail("E_INTERNAL", "the builder asked nothing");
const int32_t tip_price = int32_t(s.construction_tip_price);
// the original's composed TEXTD sentence: a small tip of n percent makes them faster
ask(utf8(s.construction_tip_dialog->body) + " (" + money(tip_price) + " instead of " + money(price) + ")", {"Yes", "No"}, "No",
[this, item, index, price, tip_price, label, stadium, stadium_request, dispatch_stadium](const std::string& tip) {
const bool accept = tip == "Yes";
dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::answer_construction_tip, item, index,
accept ? tip_price : price, accept));
const ui::StadiumState after = stadium();
if (!after.action_feedback.empty()) fail("E_INSUFFICIENT_FUNDS", utf8(after.action_feedback));
emit('+', label + " ordered for " + money(accept ? tip_price : price));
});
});
};
add({"Stadium", "BuildFacility", {choice("facility", {"Floodlights", "Scoreboard", "PitchHeating", "VipLounge"})},
"technical expansion (AUSBAUEN): tier and tip questions", true},
[invest](const Values& v) { invest(v.choice("facility")); });
add({"Stadium", "Maintain", {choice("item", {"Pitch", "Comfort", "Condition", "Safety"})}, "maintenance: tier and tip questions", true},
[invest](const Values& v) { invest(4 + v.choice("item")); });
// The GUI and CareerSession already implement the A-H block editor and stadium
// data. These console commands still lack their own argument/projection adapter
// (the stage-2 placeholders from issue #16); this is a console-only gap.
for (const char* name : {"QuoteBlockExpansion", "ConfirmBlockExpansion", "DeclineBlockExpansion", "ShowFutureExpansion", "OpenData"})
add({"Stadium", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + ": the block editor / stadium data are not ported yet"); });
add({"Stadium", "SetTicketPrice", {integer("price", 8, 25)}, "the ticket price (as on the desk)", true}, [this](const Values& v) {
// the same engine write as the desk's price scale (CareerSession::dispatch_ticket_price)
const ui::DeskState d = desk();
std::string error;
require_engine(app::DeskActions(*session_).ticket_price(d, int(v.integer("price")), revision_, error), "ticket price", error);
emit('+', "ticket price: " + std::to_string(desk().ticket_price));
});
add({"Stadium.Periphery", "ListPeriphery", {}, "the 14 objects: built, building, days", false}, [show_periphery](const Values&) { show_periphery(); });
auto periphery = [this, stadium, stadium_request, dispatch_stadium](int object, int32_t price, bool build) {
try {
dispatch_stadium(stadium_request(stadium(), build ? ui::StadiumRequestKind::build_periphery : ui::StadiumRequestKind::decline_periphery,
object, -1, price));
} catch (...) {
// a refused build (no money) must not leave the offer open: the stadium could not
// be closed any more. It ends like NEIN, then the refusal is reported.
if (build && stadium().quoted_object) {
try {
dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::decline_periphery, object, -1, price));
} catch (...) {}
}
throw;
}
emit('+', text(kPeripheryNames + object) + (build ? " is being built for " + money(price) : " not built"));
};
add({"Stadium.Periphery", "QuotePeriphery", {integer("object", 0, 13)}, "the building firm's current offer (question)", true},
[this, stadium, stadium_request, dispatch_stadium, periphery](const Values& v) {
dispatch_stadium(stadium_request(stadium(), ui::StadiumRequestKind::quote_periphery, int(v.integer("object"))));
const ui::StadiumState s = stadium();
if (!s.quoted_object) fail("E_INTERNAL", "the engine gave no offer");
const int object = *s.quoted_object;
const int32_t price = s.quoted_price;
// OK / NEIN of the original; the console's own wording, the original shows a
// composed TEXTD sentence with the price
ask(text(kPeripheryNames + object) + ": offer " + money(price) + ". Accept?", {"Yes", "No"}, "No",
[periphery, object, price](const std::string& answer) { periphery(object, price, answer == "Yes"); });
});
add({"Stadium.Periphery", "BuildPeriphery", {integer("object", 0, 13), integer("price", 1, kMaxMoney)}, "accept the offer", true},
[periphery](const Values& v) { periphery(int(v.integer("object")), int32_t(v.integer("price")), true); });
add({"Stadium.Periphery", "DeclinePeriphery", {integer("object", 0, 13), integer("price", 1, kMaxMoney)}, "decline the offer", true},
[periphery](const Values& v) { periphery(int(v.integer("object")), int32_t(v.integer("price")), false); });
add({"Stadium.Periphery", "OpenInterior", {}, "SICHT: INNEN (back to Stadium)", false}, [this](const Values&) { close_window(); });
// --- Toto (05/06: Toto, H2 p. 56-57) --------------------------------------------------
auto toto = [this] {
const auto p = prep();
if (!p.toto) fail("E_MODE_LOCKED", "no Toto in this game");
return *p.toto;
};
// tip draft of the open coupon (the original keeps the picks in the screen until MACH ICH)
auto tips = std::make_shared<std::array<uint8_t, 11>>();
auto stake = std::make_shared<uint32_t>(0);
auto show_toto = [this, toto, tips, stake] {
const ui::TotoState t = toto();
if (!t.available) {
emit('i', "no Toto coupon this week" + (t.feedback.empty() ? std::string() : ": " + utf8(t.feedback)));
return;
}
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < t.matches.size(); ++i) {
const uint8_t pick = i < tips->size() ? (*tips)[i] : 0;
rows.push_back({std::to_string(i + 1), utf8(t.matches[i].home_name), utf8(t.matches[i].away_name), pick == 0 ? "1" : pick == 1 ? "X" : "2"});
}
emit_table({"Match", "Home", "Away", "Tip"}, rows);
emit('i', "stake " + money(*stake) + ", balance " + money(t.balance) + (t.feedback.empty() ? "" : ", " + utf8(t.feedback)));
};
openers_[13] = [this, toto, tips, stake, show_toto] {
const ui::TotoState t = toto();
for (size_t i = 0; i < tips->size(); ++i) (*tips)[i] = i < t.matches.size() ? t.matches[i].pick : 0;
*stake = t.stake;
open_window("Toto");
show_toto();
};
add({"Toto", "ShowToto", {}, "the eleven matches with your tips", false}, [show_toto](const Values&) { show_toto(); });
// tips are written 1 (home), X or 0 (draw), 2 (away); stored 0, 1, 2 (src/ui/toto.cpp)
auto parse_tip = [](const std::string& s) -> int {
const std::string t = lower(s);
if (t == "1") return 0;
if (t == "x" || t == "0") return 1;
if (t == "2") return 2;
fail("E_BAD_ARGUMENT", "a tip is 1, X (or 0) or 2");
};
Param tip_param = detail::text("tip");
tip_param.display = "tip:enum(1,X,2)";
add({"Toto", "SetTip", {integer("match", 1, 11), tip_param}, "the tip for one match", false}, [this, tips, parse_tip](const Values& v) {
(*tips)[size_t(v.integer("match") - 1)] = uint8_t(parse_tip(v.text("tip")));
emit('+', "match " + std::to_string(v.integer("match")) + ": " + v.text("tip"));
});
add({"Toto", "SetStake", {integer("amount", 0, kMaxMoney)}, "the stake", false}, [this, stake](const Values& v) {
*stake = uint32_t(v.integer("amount"));
emit('+', "stake " + money(*stake));
});
Param tip_list = detail::text("tips", 0, true);
tip_list.display = "[tips:list(11)]";
add({"Toto", "SubmitToto", {integer("stake", 0, kMaxMoney, true), tip_list}, "MACH ICH: hand in the coupon", true},
[this, toto, tips, stake, parse_tip, show_toto](const Values& v) {
const ui::TotoState t = toto();
if (!t.available) fail("E_RULE", "no Toto coupon this week");
if (v.has("stake")) *stake = uint32_t(v.integer("stake"));
// submit_pools_coupon: no stake, or 10.000 to 400.000
if (*stake != 0 && (*stake < 10000 || *stake > 400000)) fail("E_BAD_ARGUMENT", "the stake is 0 or 10000 to 400000");
if (v.has("tips")) {
std::string list = v.text("tips");
if (list.size() < 2 || list.front() != '[' || list.back() != ']') fail("E_BAD_ARGUMENT", "tips is a list [1, X, 2, ...]");
list = list.substr(1, list.size() - 2);
std::vector<int> parsed;
size_t start = 0;
while (start <= list.size()) {
size_t comma = list.find(',', start);
std::string item = list.substr(start, comma == std::string::npos ? std::string::npos : comma - start);
item.erase(0, item.find_first_not_of(' '));
item.erase(item.find_last_not_of(' ') + 1);
parsed.push_back(parse_tip(item));
if (comma == std::string::npos) break;
start = comma + 1;
}
if (parsed.size() != 11) fail("E_BAD_ARGUMENT", "tips needs 11 values");
for (size_t i = 0; i < 11; ++i) (*tips)[i] = uint8_t(parsed[i]);
}
ui::TotoRequest r;
r.kind = ui::TotoRequestKind::submit;
r.manager_slot = t.manager_slot;
r.runtime_club = t.runtime_club;
r.revision = revision_;
r.stake = *stake;
r.tips = *tips;
std::string error;
require_engine(session_->dispatch_toto(r, revision_, error), "Toto", error);
emit('+', "coupon handed in, stake " + money(*stake));
show_toto();
});
add({"Toto", "ClearToto", {}, "all tips back to 1, stake 0", false}, [this, tips, stake](const Values&) {
tips->fill(0);
*stake = 0;
emit('+', "coupon cleared");
});
}
} // namespace bmh::cli::console
+346
View File
@@ -0,0 +1,346 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
// The office windows of docs/CLI_CONCEPT: Advertising (menu 21, 06-verein 9), Contracts
// (menu 27, 06-verein 6) and Settings (menu 19, 08-einstellungen). Views from the pure
// projections ui::advertising_from_game / contracts_from_game / settings_from_game, changes
// through dispatch_advertising / dispatch_contract / dispatch_settings with the requests
// the SDL screens build (src/ui/advertising.cpp, contracts.cpp, settings.cpp).
#include <algorithm>
#include <limits>
#include "app/desktop_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "ui/advertising.hpp"
#include "ui/contracts.hpp"
#include "ui/settings.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
const std::vector<std::string> kAdSlots = {"Board1", "Board2", "Board3", "Board4", "Board5", "Board6", "Board7", "Board8",
"Board9", "Board10", "Board11", "Board12", "Board13", "Board14", "Shirt", "Tv"};
// the seven bonuses, in the order of the manager record / ContractRequest::proposed_bonuses
// the three spending targets 16-18 (AdvertisingSpendingView::target_slot); the original
// labels them with pictures, its TEXTD labels ("Monatsausgaben:") do not tell PR from fan care
const std::vector<std::string> kSpending = {"FanItems", "PublicRelations", "FanCare"};
const std::vector<std::string> kBonuses = {"Goal", "Points", "Appearance", "Champion", "Place2to5", "Place6to10", "AvoidRelegation"};
// the first three bonuses are percentages up to 20, the others up to 200 (dispatch_contract)
int bonus_max(int kind) { return kind < 3 ? 20 : 200; }
constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU
// Settings: row A-T, column 1-9 (08-einstellungen); A1 = row 0, column 0.
std::pair<int, int> switch_key(const std::string& key) {
if (key.size() < 2 || key.size() > 2) fail("E_BAD_ARGUMENT", "a switch is A1 ... T9");
const int row = std::toupper(static_cast<unsigned char>(key[0])) - 'A';
const int column = key[1] - '1';
if (row < 0 || row >= 20 || column < 0 || column >= 9) fail("E_BAD_ARGUMENT", "a switch is A1 ... T9");
return {row, column};
}
} // namespace
void Console::register_office_commands() {
// --- Advertising ----------------------------------------------------------------------
auto adverts = [this] { return ui::advertising_from_game(session_->state(), active_slot(), revision_); };
auto contract_of = [](const ui::AdvertisingState& a, int slot) -> const ui::AdvertisingContract& {
return slot < 14 ? a.boards.at(size_t(slot)) : slot == 14 ? a.shirt : a.television;
};
auto show_adverts = [this, adverts, contract_of] {
const ui::AdvertisingState a = adverts();
std::vector<std::vector<std::string>> rows;
for (int slot = 0; slot < 16; ++slot) {
const auto& c = contract_of(a, slot);
rows.push_back({kAdSlots[size_t(slot)], c.active ? utf8(c.sponsor_name) : "free", c.active ? money(c.monthly_amount) : "-",
c.active ? std::to_string(c.months_remaining) : "-", c.option_marker ? "option" : ""});
}
emit_table({"Slot", "Sponsor", "Monthly", "Months", ""}, rows);
std::vector<std::vector<std::string>> spending;
for (size_t i = 0; i < 3; ++i)
spending.push_back({kSpending[i], money(a.spending[i].current_amount), money(a.spending[i].maximum_amount),
a.spending[i].available ? "" : "locked"});
emit_table({"Spending", "Amount", "Maximum", ""}, spending);
emit('i', "monthly: income " + money(a.finance_preview.income) + ", expenses " + money(a.finance_preview.expenses) +
", balance " + money(a.finance_preview.balance));
if (!a.notification_text.empty()) emit('i', utf8(a.notification_text));
};
openers_[21] = [this, show_adverts] {
open_window("Advertising");
show_adverts();
};
add({"Advertising", "ShowAdvertising", {}, "all boards, shirt, TV and the spending", false}, [show_adverts](const Values&) { show_adverts(); });
auto offers_of = [](const ui::AdvertisingState& a, int slot) {
std::vector<const AdvertisingOfferCandidate*> list;
for (const auto& o : a.offers[size_t(slot)].offers)
if (o.present && o.monthly_amount != 0) list.push_back(&o);
return list;
};
add({"Advertising", "ListAdOffers", {choice("slot", kAdSlots)}, "the offers for a board, the shirt or TV (an expired contract: renewal first)", true},
[this, adverts, offers_of](const Values& v) {
const int slot = v.choice("slot");
// A contract whose months ran out: the click on it asks for the renewal first
// (CheckAdvertisingRenewal) - the sponsor may decline, otherwise the manager decides; a
// declined or refused renewal frees the place for the offers below.
if (adverts().offers[size_t(slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension) {
std::string error;
const auto renewal = session_->check_advertising_renewal(adverts().manager_slot, slot, revision_, error);
if (!renewal) require_engine(false, "advertising", error);
if (renewal->status == AdvertisingRenewal::Status::declined_by_sponsor) {
emit('i', utf8(renewal->notice));
} else if (renewal->status == AdvertisingRenewal::Status::offered) {
const int manager = adverts().manager_slot, contract = renewal->contract_slot;
ask(utf8(renewal->question), {"Yes", "No"}, "No", [this, manager, contract, slot](const std::string& answer) {
std::string err;
if (!session_->answer_advertising_renewal(manager, contract, answer == "Yes", revision_, err))
require_engine(false, "advertising", err);
emit('+', answer == "Yes" ? "contract renewed" : "contract not renewed: ListAdOffers(" +
kAdSlots[size_t(slot)] + ") shows the offers");
});
return;
}
}
const ui::AdvertisingState a = adverts();
const auto& list = a.offers[size_t(slot)];
const auto& names = list.pool_group == 2 ? a.television_sponsor_names : a.board_sponsor_names;
std::vector<std::vector<std::string>> rows;
int n = 0;
for (const auto* o : offers_of(a, slot))
rows.push_back({std::to_string(++n), utf8(names[size_t(std::clamp(int(o->sponsor_id), 0, 9))]), money(o->monthly_amount),
std::to_string(o->months), std::to_string(o->bundle_units), o->can_accept ? "" : "not possible"});
if (rows.empty()) emit('i', "no offers for " + kAdSlots[size_t(slot)]);
else emit_table({"Offer", "Sponsor", "Monthly", "Months", "Boards", ""}, rows);
});
add({"Advertising", "AcceptAdOffer", {choice("slot", kAdSlots), integer("offer", 1, 10)}, "ANNEHMEN", true},
[this, adverts, offers_of, show_adverts](const Values& v) {
const ui::AdvertisingState a = adverts();
const int slot = v.choice("slot");
const auto list = offers_of(a, slot);
const size_t n = size_t(v.integer("offer"));
if (n > list.size()) fail("E_BAD_ARGUMENT", "no offer " + std::to_string(n) + " (ListAdOffers)");
if (a.offers[size_t(slot)].status == bmh::AdvertisingOfferStatus::unsupported_extension)
fail("E_RULE", "the contract on " + kAdSlots[size_t(slot)] + " ran out: ListAdOffers(" + kAdSlots[size_t(slot)] +
") asks for the renewal first");
if (!list[n - 1]->can_accept) fail("E_RULE", "this offer cannot be accepted");
std::string error;
if (!session_->accept_advertising_selection(a, slot, list[n - 1]->raw_slot,
next_request_id_++, revision_, error))
require_engine(false, "advertising", error);
emit('+', "offer accepted for " + kAdSlots[size_t(slot)]);
show_adverts();
});
add({"Advertising", "DeclineAdOffer", {}, "ABBRECHEN", false}, [this](const Values&) { emit('+', "no offer accepted"); });
auto spend = [this, adverts](int target, uint32_t amount) {
const ui::AdvertisingState a = adverts();
const auto& view = a.spending[size_t(target - 16)];
if (!view.available) fail("E_RULE", utf8(a.spending_blocked_text.empty() ? "not available now" : a.spending_blocked_text));
if (amount > view.maximum_amount) fail("E_BAD_ARGUMENT", "at most " + money(view.maximum_amount));
AdvertisingSpendingResult result;
std::string error;
if (!session_->set_advertising_budget(a, target, amount, next_request_id_++, revision_, error, result))
require_engine(false, "advertising", error);
const std::string message = result.message_address >= ::bmh::layout::TextPointerTable ? text(int((result.message_address - ::bmh::layout::TextPointerTable) / 4)) : "";
if (result.status == AdvertisingSpendingStatus::insufficient_funds) fail("E_INSUFFICIENT_FUNDS", message);
emit('+', kSpending[size_t(target - 16)] + ": " + money(amount) + (message.empty() ? "" : ". " + message));
};
add({"Advertising", "SetSpending", {choice("kind", {"PublicRelations", "FanCare"}), integer("amount", 0, std::numeric_limits<int32_t>::max())},
"monthly budget for press work or fan care", true},
[spend](const Values& v) { spend(17 + v.choice("kind"), uint32_t(v.integer("amount"))); });
add({"Advertising", "BuyFanItems", {integer("amount", 1, std::numeric_limits<int32_t>::max())}, "buy fan articles (sold in 6-9 weeks)", true},
[spend](const Values& v) { spend(16, uint32_t(v.integer("amount"))); });
// --- Contracts ------------------------------------------------------------------------
auto contracts = [this] { return ui::contracts_from_game(session_->state(), active_slot(), revision_); };
auto dispatch_contract = [this](const ui::ContractRequest& r) {
ui::ContractActionResult result;
std::string error;
require_engine(app::ContractActions(*session_).dispatch(r, revision_, result, error), "contracts", error);
return result;
};
auto show_contracts = [this, contracts] {
const ui::ContractsState c = contracts();
std::vector<std::vector<std::string>> rows;
for (const auto& p : c.players)
rows.push_back({"row:" + std::to_string(p.row), "id:" + std::to_string(p.player_id), utf8(p.name),
p.position >= 0 && p.position < 4 ? text(kPositionNames + p.position) : "?", std::to_string(p.age),
money(p.current_monthly_salary), std::to_string(p.remaining_months),
p.insurance ? std::to_string(p.insurance) : "-", p.offer_blocked ? "[sulking]" : ""});
emit_table({"Row", "Id", "Player", "Pos", "Age", "Salary", "Months", "Insurance", ""}, rows);
};
openers_[27] = [this, show_contracts] {
session_->clear_contract_quote();
open_window("Contracts");
show_contracts();
};
add({"Contracts", "ShowContracts", {choice("sheet", {"A", "B"}, true)}, "the squad with salaries and contract months", false},
[show_contracts](const Values&) { show_contracts(); });
add({"Contracts", "ShowTeamBonuses", {}, "the seven team bonuses (percent of the salary)", false}, [this, contracts](const Values&) {
const ui::ContractsState c = contracts();
if (!c.mode_three) fail("E_MODE_LOCKED", "team bonuses only in mode III");
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i < 7; ++i) rows.push_back({kBonuses[i], std::to_string(c.team_premiums[i]), std::to_string(bonus_max(int(i)))});
emit_table({"Bonus", "Percent", "Max"}, rows);
});
add({"Contracts", "SetTeamBonus", {choice("kind", kBonuses), integer("percent", 0, 200)}, "a team bonus; it can only be raised", true},
[this, contracts, dispatch_contract](const Values& v) {
const ui::ContractsState c = contracts();
if (!c.mode_three) fail("E_MODE_LOCKED", "team bonuses only in mode III");
const int kind = v.choice("kind"), percent = int(v.integer("percent"));
if (percent > bonus_max(kind)) fail("E_BAD_ARGUMENT", kBonuses[size_t(kind)] + " is at most " + std::to_string(bonus_max(kind)));
const auto r = app::ContractActions::team_bonus(c, kind, uint8_t(percent), next_request_id_++);
const auto result = dispatch_contract(r);
if (!result.accepted) fail("E_RULE", result.feedback.empty() ? "the team does not accept this" : result.feedback);
emit('+', result.feedback.empty() ? kBonuses[size_t(kind)] + " = " + std::to_string(percent) : result.feedback);
});
Param player = detail::text("player");
player.display = "player:Player";
add({"Contracts", "OpenNegotiation", {player}, "the player's demands (Contracts.Negotiate)", true},
[this, contracts, dispatch_contract](const Values& v) {
const ui::ContractsState c = contracts();
std::vector<PlayerRef> refs;
for (const auto& p : c.players) refs.push_back({p.row, p.player_id, utf8(p.name)});
const auto& p = c.players[resolve_player(v.text("player"), refs)];
if (p.offer_blocked) fail("E_RULE", utf8(p.name) + " does not negotiate at the moment");
const auto r = app::ContractActions::demands(c, p, next_request_id_++);
const auto result = dispatch_contract(r);
negotiation_ = Negotiation{p.row, p.player_id, utf8(p.name), result.quote_id, result.demands, -1, 0, p.team_premiums};
open_window("Contracts.Negotiate");
std::vector<std::vector<std::string>> rows;
for (size_t y = 0; y < 4; ++y) rows.push_back({std::to_string(y + 1), money(result.demands[y])});
emit('i', utf8(p.name) + ": " + std::to_string(p.remaining_months) + " months left, salary " + money(p.current_monthly_salary));
emit_table({"Years", "Demand"}, rows);
});
add({"Contracts.Negotiate", "ShowDemands", {}, "the demands for 1-4 years", false}, [this](const Values&) {
if (!negotiation_) fail("E_INTERNAL", "no negotiation");
std::vector<std::vector<std::string>> rows;
for (size_t y = 0; y < 4; ++y) rows.push_back({std::to_string(y + 1), money(negotiation_->demands[y])});
emit_table({"Years", "Demand"}, rows);
if (negotiation_->years > 0)
emit('i', "offer: " + std::to_string(negotiation_->years) + " years, " + money(negotiation_->salary) + " monthly");
});
add({"Contracts.Negotiate", "SetContractOffer", {integer("years", 1, 4), integer("salary", 1, 200000)}, "the salary offer (monthly)", false},
[this](const Values& v) {
if (!negotiation_) fail("E_INTERNAL", "no negotiation");
negotiation_->years = int(v.integer("years"));
negotiation_->salary = uint32_t(v.integer("salary"));
emit('+', "offer: " + std::to_string(negotiation_->years) + " years, " + money(negotiation_->salary) + " monthly");
});
add({"Contracts.Negotiate", "SetInsurance", {choice("form", {"A", "B", "C", "D"}), integer("months", 1, 60)}, "insure the player (no question)", true},
[this, contracts, dispatch_contract](const Values& v) {
if (!negotiation_) fail("E_INTERNAL", "no negotiation");
const auto r = app::ContractActions::insurance(contracts(), negotiation_->row, negotiation_->player_id,
negotiation_->quote_id, uint8_t(v.choice("form")), uint8_t(v.integer("months")), next_request_id_++);
const auto result = dispatch_contract(r);
negotiation_->quote_id = result.quote_id;
emit('+', "insured: form " + std::string(1, char('A' + v.choice("form"))) + ", " + std::to_string(v.integer("months")) + " months");
});
add({"Contracts.Negotiate", "SetPlayerBonus", {choice("kind", kBonuses), integer("percent", 0, 200)}, "a bonus for this player (PRÄMIEN)", false},
[this](const Values& v) {
if (!negotiation_) fail("E_INTERNAL", "no negotiation");
const int kind = v.choice("kind"), percent = int(v.integer("percent"));
if (percent > bonus_max(kind)) fail("E_BAD_ARGUMENT", kBonuses[size_t(kind)] + " is at most " + std::to_string(bonus_max(kind)));
negotiation_->bonuses[size_t(kind)] = uint8_t(percent);
emit('+', kBonuses[size_t(kind)] + " = " + std::to_string(percent));
});
add({"Contracts.Negotiate", "MakeOffer", {}, "ANGEBOT MACHEN: the player decides", true},
[this, contracts, dispatch_contract](const Values&) {
if (!negotiation_) fail("E_INTERNAL", "no negotiation");
const Negotiation n = *negotiation_;
const auto r = app::ContractActions::offer(contracts(), n.row, n.player_id, n.quote_id,
n.bonuses, n.years, n.salary, n.demands, next_request_id_++);
const auto result = dispatch_contract(r);
negotiation_.reset();
close_window();
emit('+', std::string(result.accepted ? "accepted: " : "rejected: ") + result.feedback);
});
// --- Settings -------------------------------------------------------------------------
auto settings = [this] { return ui::settings_from_game(session_->state(), active_slot(), revision_, exe_); };
// A cell as the screen shows it (SettingsScreen::render): columns 1-7 are switches, the
// stored 1 is OFF, 0 is ON, 2 is an empty cell; column 8 shows raw/2, column 9 the raw
// value; values >= 200 are empty cells. Bits 6/7 mark a switch unavailable.
auto cell_text = [](const ui::SettingsState& s, int row, int column) -> std::string {
const uint8_t raw = s.display_cells ? (*s.display_cells)[size_t(row * 9 + column)] : s.cells[size_t(row * 9 + column)];
if (column < 7) {
const uint8_t value = raw & 0x3f;
if (value == 2) return " ";
return std::string(value == 1 ? "off" : "on") + ((raw & 0xc0) ? "*" : "");
}
if (raw >= 200) return " ";
return std::to_string(column == 8 ? raw / 2 : raw); // column 9 shows half the raw value (SettingsScreen)
};
auto show_settings = [this, settings, cell_text] {
const ui::SettingsState s = settings();
std::vector<std::vector<std::string>> rows;
for (int row = 0; row < 20; ++row) {
std::vector<std::string> cells = {std::string(1, char('A' + row))};
for (int column = 0; column < 9; ++column) cells.push_back(cell_text(s, row, column));
rows.push_back(cells);
}
emit_table({"", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, rows);
emit('i', "* = not available in this game; keys A1 ... T9 (08-einstellungen 3)");
};
openers_[19] = [this, show_settings] {
open_window("Settings");
show_settings();
};
add({"Settings", "ShowSettings", {detail::text("group", 0, true)}, "the switch field A1-T9", false}, [show_settings](const Values& v) {
if (v.has("group")) fail("E_ENGINE_GAP", "the named groups of 08-einstellungen 3 are not in the console yet; ShowSettings shows all");
show_settings();
});
add({"Settings", "ShowSwitch", {detail::text("key")}, "one switch", false}, [this, settings, cell_text](const Values& v) {
const auto [row, column] = switch_key(v.text("key"));
emit('+', v.text("key") + " = " + cell_text(settings(), row, column));
});
auto edit = [this, settings](int row, int column, ui::SettingsEdit operation) {
const ui::SettingsState s = settings();
std::string error;
require_engine(app::DeskSettingsActions(*session_).edit(s, row, column, operation, revision_, error), "settings", error);
};
add({"Settings", "SetSwitch", {detail::text("key"), detail::text("value")}, "set a switch (on/off or a number)", true},
[this, settings, cell_text, edit](const Values& v) {
const auto [row, column] = switch_key(v.text("key"));
Arg value;
value.text = v.text("value");
if (column < 7) {
const auto on = to_bool(value);
if (!on) fail("E_BAD_ARGUMENT", "a switch is on or off");
const std::string now = cell_text(settings(), row, column);
if (now == " ") fail("E_RULE", v.text("key") + " is an empty cell");
if ((now.rfind("on", 0) == 0) != *on) edit(row, column, ui::SettingsEdit::toggle_binary);
} else {
const auto target = to_int(value);
if (!target) fail("E_BAD_ARGUMENT", "the value is a number");
for (int step = 0; step < 200; ++step) {
const std::string now = cell_text(settings(), row, column);
if (now == " ") fail("E_RULE", v.text("key") + " is an empty cell");
const int current = std::stoi(now);
if (current == *target) break;
edit(row, column, current < *target ? ui::SettingsEdit::increment : ui::SettingsEdit::decrement);
if (std::stoi(cell_text(settings(), row, column)) == current) fail("E_BAD_ARGUMENT", "the value cannot go further");
}
}
emit('+', v.text("key") + " = " + cell_text(settings(), row, column));
});
add({"Settings", "IncreaseSwitch", {detail::text("key")}, "the plus field (columns 8, 9)", true}, [this, settings, cell_text, edit](const Values& v) {
const auto [row, column] = switch_key(v.text("key"));
if (column < 7) fail("E_BAD_ARGUMENT", "only columns 8 and 9 have values");
edit(row, column, ui::SettingsEdit::increment);
emit('+', v.text("key") + " = " + cell_text(settings(), row, column));
});
add({"Settings", "DecreaseSwitch", {detail::text("key")}, "the minus field (columns 8, 9)", true}, [this, settings, cell_text, edit](const Values& v) {
const auto [row, column] = switch_key(v.text("key"));
if (column < 7) fail("E_BAD_ARGUMENT", "only columns 8 and 9 have values");
edit(row, column, ui::SettingsEdit::decrement);
emit('+', v.text("key") + " = " + cell_text(settings(), row, column));
});
for (const char* name : {"LoadSettings", "SaveSettings", "ShowReadme"})
add({"Settings", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + ": the .EIN files are not ported yet (C4)"); });
}
} // namespace bmh::cli::console
+100
View File
@@ -0,0 +1,100 @@
// SPDX-License-Identifier: GPL-3.0-only
// Moving own home league matches (menu 7, docs/CLI_CONCEPT/06-verein.md 13, H2 p. 52): list
// the matches that can be moved, the days each one can move to, move it and take a move back.
//
// The rules are the engine's (src/game/reschedule.hpp, a port of the calendar screen
// CalendarCell in mode 2): own home league matches in the future, not on the first or the
// last two matchdays; target days free of other matches and friendlies, outside the winter
// break; the Friday before the matchday only with floodlights. Dates are written like the
// other date commands (YYYY-MM-DD).
#include <algorithm>
#include "app/desktop_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/reschedule.hpp"
#include "ui/desk_state.hpp"
namespace bmh::cli::console {
using namespace detail;
void Console::register_reschedule_commands() {
auto manager = [this] { return active_slot(); };
auto day_text = [this](int day) {
const ui::DeskDate date = ui::desk_date(session_->state().season_start + uint32_t(day), exe_);
return date_text(date.day, date.month, date.year);
};
// the movable match on the date `text`
auto find_game = [this, manager, day_text](const std::string& text) {
for (const LeagueMatchRef& m : reschedulable_matches(session_->state(), manager()))
if (day_text(m.day) == text) return m;
fail("E_RULE", "no movable home league match on " + text + " (ListRescheduleGames)");
};
openers_[7] = [this] {
open_window("Reschedule");
emit('+', "reschedule: ListRescheduleGames, ListRescheduleDates(game:date), MoveGame(game:date, to:date), ListMovedGames, UndoMove(game:date)");
};
add({"Reschedule", "ListRescheduleGames", {}, "own home league matches that can be moved", false},
[this, manager, day_text](const Values&) {
const GameState& g = session_->state();
std::vector<std::vector<std::string>> rows;
for (const LeagueMatchRef& m : reschedulable_matches(g, manager()))
rows.push_back({day_text(m.day), std::to_string(m.round + 1), utf8(g.club_name(m.away))});
if (rows.empty()) emit('i', "no home league match can be moved");
emit_table({"Date", "Matchday", "Opponent"}, rows);
});
Param game = detail::text("game");
game.display = "game:date";
Param to = detail::text("to");
to.display = "to:date";
add({"Reschedule", "ListRescheduleDates", {game}, "the days the match can be moved to", false},
[this, manager, day_text, find_game](const Values& v) {
const LeagueMatchRef m = find_game(v.text("game"));
std::vector<std::vector<std::string>> rows;
for (int day : reschedule_target_days(session_->state(), manager(), m)) rows.push_back({day_text(day), std::to_string(day)});
if (rows.empty()) emit('i', "no free day for this match");
emit_table({"Date", "SeasonDay"}, rows);
});
add({"Reschedule", "ListMovedGames", {}, "moved matches that can still be taken back (new date)", false},
[this, manager, day_text](const Values&) {
const GameState& g = session_->state();
std::vector<std::vector<std::string>> rows;
for (const LeagueMatchRef& m : moved_matches(g, manager()))
rows.push_back({day_text(m.day), std::to_string(m.round + 1), utf8(g.club_name(m.home)), utf8(g.club_name(m.away))});
if (rows.empty()) emit('i', "no moved match");
emit_table({"Date", "Matchday", "Home", "Away"}, rows);
});
add({"Reschedule", "UndoMove", {game}, "take a move back (game = the new date); the match is played on its matchday again", true},
[this, manager, day_text](const Values& v) {
const GameState& g = session_->state();
for (const LeagueMatchRef& m : moved_matches(g, manager())) {
if (day_text(m.day) != v.text("game")) continue;
app::RescheduleActions(*session_).undo_console(manager(), m.day, revision_);
emit('+', utf8(g.club_name(m.home)) + " - " + utf8(g.club_name(m.away)) + " back on matchday " + std::to_string(m.round + 1));
return;
}
fail("E_RULE", "no moved match on " + v.text("game") + " (ListMovedGames)");
});
add({"Reschedule", "MoveGame", {game, to}, "move the match to a free day", true},
[this, manager, day_text, find_game](const Values& v) {
const LeagueMatchRef m = find_game(v.text("game"));
int target = -1;
for (int day : reschedule_target_days(session_->state(), manager(), m))
if (day_text(day) == v.text("to")) target = day;
if (target < 0) fail("E_RULE", v.text("to") + " is not free for this match (ListRescheduleDates)");
switch (app::RescheduleActions(*session_).move(manager(), m, target, revision_)) {
case RescheduleStatus::moved: break;
case RescheduleStatus::no_free_slot: fail("E_RULE", "too many postponed matches this season");
case RescheduleStatus::day_full:
case RescheduleStatus::team_clash: fail("E_RULE", "that day is already full of replays");
default: fail("E_RULE", "the match cannot be moved");
}
const GameState& g = session_->state();
emit('+', utf8(g.club_name(m.home)) + " - " + utf8(g.club_name(m.away)) + " moved from " + day_text(m.day) + " to " +
day_text(target));
});
}
} // namespace bmh::cli::console
+429
View File
@@ -0,0 +1,429 @@
// SPDX-License-Identifier: GPL-3.0-only
// The squad windows of docs/CLI_CONCEPT/06-verein.md 1: Lineup (menu 3) with Lineup.Pitch,
// the player card PlayerCard (+ PlayerCard.Statistics) and the club information TeamInfo.
//
// Opening the line-up is an engine step: the original arranges the eleven through the human
// path when the screen opens (PitchScreen -> Int2, CareerSession::dispatch_lineup
// prepare_lineup); the console does the same when Open(Lineup) runs, never on a read command.
#include <algorithm>
#include "app/window_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "ui/club_info.hpp"
#include "ui/lineup.hpp"
#include "game/lineup.hpp"
#include "ui/pitch.hpp"
#include "ui/player_card.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// TEXTD indices (docs/formats/textd_inventory.csv)
constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU
constexpr int kSkillNames = 135; // skillTeamplay, Speed, Shot, Pass, Tackling, FreeKick, Corner
constexpr int kRatings = 142; // ratingLousy, Fair, Good, Great
// The squad slot flags: 0x8000 on the pitch (starting eleven), 0x4000 on the bench.
std::string slot_state(uint16_t slot) { return (slot & 0x8000) ? "pitch" : (slot & 0x4000) ? "bench" : "-"; }
// Why a player cannot play: w364 bits 16-19 hold the remaining duration, bit 20 marks a ban
// instead of an injury (Absence). The SDL line-up shows the same as a red cross / card.
std::string absence(const Player& a) {
const int duration = int(a.w364 >> 16 & 0xF);
if (duration == 0) return "-";
return std::string(a.w364 & 0x100000 ? "ban " : "injury ") + std::to_string(duration);
}
} // namespace
void Console::register_squad_commands() {
auto lineup = [this] { return prep().lineup; };
auto refs_of = [](const ui::LineupState& l) {
std::vector<PlayerRef> refs;
for (const auto& p : l.players)
if (p.player_id >= 0) refs.push_back({p.row, p.player_id, utf8(p.name)});
return refs;
};
auto player_at = [refs_of](const ui::LineupState& l, const std::string& reference) -> ui::LineupPlayer {
const auto refs = refs_of(l);
const int row = refs[resolve_player(reference, refs)].row;
return l.players[size_t(row)];
};
// DATEN-A / DATEN-B as the line-up screen draws them (src/ui/lineup.cpp, headers ClubInfo_Render_TextPointer3 / ClubInfo_Render_TextPointer4):
// A = position, KO/TE/FO/strength and this season's games, goals, assists, yellow and red
// cards (w364 >> 26, w364 bits 2-7, w368 bits 18-23, 14-17, 24-26); B = age, the seven
// skills and the career numbers: internationals (bonus & 127), league and UEFA games (board
// +7, +9), total games, goals and assists (board words +0x48, +0x4a, +0x4c).
auto show_squad = [this, lineup] {
const ui::LineupState l = lineup();
std::vector<std::vector<std::string>> rows;
for (const auto& p : l.players) {
if (p.player_id < 0) continue;
const auto& a = p.attributes;
std::vector<std::string> row{"row:" + std::to_string(p.row), "id:" + std::to_string(p.player_id), utf8(p.name)};
if (!squad_view_b_) {
for (std::string v : {text(kPositionNames + a.position()), std::to_string(a.condition()), std::to_string(a.technique()),
std::to_string(a.form()), std::to_string(a.strength()), std::to_string(a.age()),
std::to_string(a.w364 >> 26), std::to_string((a.w364 >> 2) & 63),
std::to_string((a.w368 >> 18) & 63), std::to_string((a.w368 >> 14) & 15),
std::to_string((a.w368 >> 24) & 7)})
row.push_back(v);
} else {
row.push_back(std::to_string(a.age()));
std::string skills;
for (int i = 0; i < 7; ++i) skills += std::to_string(a.skill(Player::Skill(i)));
row.push_back(skills);
const auto word = [&](size_t at) { return std::to_string(p.board[at] | p.board[at + 1] << 8); };
for (std::string v : {std::to_string(p.bonus & 127), std::to_string(p.board[7]), std::to_string(p.board[9]),
word(0x48), word(0x4a), word(0x4c)})
row.push_back(v);
}
row.push_back(slot_state(p.slot));
row.push_back(absence(a));
rows.push_back(std::move(row));
}
if (!squad_view_b_)
emit_table({"Row", "Id", "Player", "Pos", "K", "T", "F", "Str", "Age", "Gm", "Gls", "Ast", "YC", "RC", "Place", "Out"}, rows);
else
emit_table({"Row", "Id", "Player", "Age", "Skills(TSShPTaFkC 0-3)", "Int", "LgGm", "EuGm", "TotGm", "TotGls", "TotAst",
"Place", "Out"}, rows);
// The starting eleven are the first rows of the squad list; a sale or the injury swap
// moves the list up, so the reserve keeper can end up on the pitch (as in the
// original). Point it out instead of leaving it to the match.
int keepers = 0;
for (const auto& p : l.players)
if (p.player_id >= 0 && (p.slot & 0x8000) && p.attributes.position() == 0) ++keepers;
if (keepers != 1) emit('i', "warning: " + std::to_string(keepers) + " goalkeepers on the pitch");
};
// --- Lineup (06-verein 1) -------------------------------------------------------------
openers_[3] = [this, lineup, show_squad] {
const ui::LineupState l = lineup();
if (!l.entry_prepared) {
const auto r = app::LineupActions::prepare(l);
std::string error;
require_engine(app::LineupActions(*session_).lineup(r, revision_, error), "line-up", error);
}
open_window("Lineup");
show_squad();
};
add({"Lineup", "ShowSquad", {choice("view", {"A", "B"}, true)}, "the squad: values, strength, place", false},
[show_squad](const Values&) { show_squad(); });
add({"Lineup", "SetSquadView", {choice("view", {"A", "B"})}, "DATEN-A / DATEN-B", false}, [this, show_squad](const Values& v) {
squad_view_b_ = v.choice("view") == 1;
show_squad();
});
Param first = detail::text("first"), second = detail::text("second");
first.display = "first:Player";
second.display = "second:Player";
// A click on one row and then on another exchanges the two places (bench, pitch, stands).
auto swap = [this, lineup, player_at, show_squad](const std::string& a, const std::string& b) {
const ui::LineupState l = lineup();
const auto& p = player_at(l, a);
const auto& q = player_at(l, b);
if (p.row == q.row) fail("E_BAD_ARGUMENT", "two different players are needed");
const auto r = app::LineupActions::swap(l, p, q);
std::string error;
require_engine(app::LineupActions(*session_).lineup(r, revision_, error), "line-up", error);
emit('+', utf8(p.name) + " <-> " + utf8(q.name));
show_squad();
};
add({"Lineup", "SwapPlayers", {first, second}, "exchange two players' places", true},
[swap](const Values& v) { swap(v.text("first"), v.text("second")); });
Param player = detail::text("player");
player.display = "player:Player";
add({"Lineup", "OpenPlayer", {player}, "the player card (PlayerCard)", false}, [this, lineup, player_at](const Values& v) {
const auto& p = player_at(lineup(), v.text("player"));
card_row_ = p.row;
open_window("PlayerCard");
show_player_card();
});
for (const char* name : {"OpenTeamList", "ShowForeigners"})
add({"Lineup", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " has no projection yet"); });
// --- Lineup.Pitch ---------------------------------------------------------------------
add({"Lineup.Pitch", "ShowPitch", {}, "the eleven with depth/lane, formations, automatic weights", false},
[this](const Values&) { show_pitch(); });
add({"Lineup.Pitch", "SwapPitch", {first, second}, "exchange two players on the pitch / bench", true},
[this, player_at](const Values& v) {
const auto projection = prep();
if (!projection.pitch || !projection.pitch->indoor.has_value())
fail("E_ENGINE_GAP", "no pitch mode projection");
const ui::LineupState& l = projection.lineup;
const auto& p = player_at(l, v.text("first"));
const auto& q = player_at(l, v.text("second"));
if (p.row == q.row) fail("E_BAD_ARGUMENT", "two different players are needed");
const auto r = app::LineupActions::swap_pitch(projection, p, q);
std::string error;
require_engine(app::LineupActions(*session_).pitch_swap(r, revision_, error), "pitch", error);
emit('+', utf8(p.name) + " <-> " + utf8(q.name));
});
// Moving a player, the formations and the automatic weights: the requests the SDL pitch
// screen builds (src/ui/pitch.cpp click / save_formation), dispatched through
// CareerSession::dispatch_pitch (PitchScreen pitch branch, Codex's source port).
auto pitch_context = [this] {
const auto p = prep();
if (!p.pitch || !p.pitch->indoor.has_value()) fail("E_ENGINE_GAP", "no pitch mode projection");
if (!p.lineup.entry_prepared) fail("E_RULE", "the line-up entry has not been prepared");
return p;
};
auto send_pitch = [this](const ui::PitchRequest& r) {
std::string error;
require_engine(app::LineupActions(*session_).pitch(r, revision_, error), "pitch", error);
};
auto team_page_request = [this] {
const auto p=prep();
if(!p.pitch||!p.pitch->indoor.has_value()||!p.lineup.entry_prepared)
fail("E_ENGINE_GAP","no prepared Source pitch projection");
return app::LineupActions::page(p);
};
add({"Lineup", "OpenPitch", {}, "the pitch (Lineup.Pitch)", false}, [this, team_page_request, send_pitch](const Values&) {
send_pitch(team_page_request());
open_window("Lineup.Pitch");
show_pitch();
});
closers_["Lineup.Pitch"]=[this,team_page_request,send_pitch,show_squad] {
send_pitch(team_page_request());
close_window();
show_squad();
};
add({"Lineup.Pitch", "SetFormation", {integer("slot", 1, 8)}, "one of the eight formations (1-4 given, 5-8 own); the automatic line-up takes over", true},
[this, pitch_context, send_pitch](const Values& v) {
const int f = int(v.integer("slot")) - 1;
if (!(prep().pitch->formation_mask & (1 << f))) fail("E_RULE", "formation slot " + std::to_string(f + 1) + " is empty");
const auto r = app::LineupActions::formation(pitch_context(), ui::PitchRequestKind::apply_formation, f);
send_pitch(r);
show_pitch();
});
add({"Lineup.Pitch", "SaveFormation", {integer("slot", 5, 8)}, "save the current positions in an own formation slot (long press)", true},
[this, pitch_context, send_pitch](const Values& v) {
const auto p = pitch_context();
for (int row = 0; row < 11; ++row) {
const auto& pl = p.lineup.players.at(size_t(row));
if (pl.player_id < 0 || !(pl.slot & 0x8000)) fail("E_RULE", "saving a formation needs eleven nominated starters");
}
const auto r = app::LineupActions::formation(p, ui::PitchRequestKind::save_formation, int(v.integer("slot")) - 1);
send_pitch(r);
emit('+', "formation " + std::to_string(r.formation + 1) + " saved");
});
add({"Lineup.Pitch", "MovePlayer", {first, integer("depth", 0, 19), integer("lane", 0, 8)},
"place a starter freely (switches the automatic line-up off)", true},
[this, lineup, player_at, pitch_context, send_pitch](const Values& v) {
const ui::LineupState l = lineup();
const auto& p = player_at(l, v.text("first"));
if (p.row >= 11 || !(p.slot & 0x8000)) fail("E_RULE", "only a starter can be placed");
const auto r = app::LineupActions::move(pitch_context(), p, int(v.integer("depth")), int(v.integer("lane")));
send_pitch(r);
show_pitch();
});
add({"Lineup.Pitch", "SetAutoWeights", {choice("kind", {"Position", "SideAndRole", "Fatigue"}), integer("value", 0, 3)},
"an automatic line-up weight (the cup is clicked until the value); then SetFormation again", true},
[this, pitch_context, send_pitch](const Values& v) {
if (desk().options.mode == 1) fail("E_MODE_LOCKED", "no automatic weights in mode I");
const int index = v.choice("kind"), shift = 2 * index, want = int(v.integer("value"));
for (int guard = 0; guard < 4 && ((prep().pitch->automatic_weights >> shift) & 3) != want; ++guard) {
const auto r = app::LineupActions::weight(pitch_context(), index);
send_pitch(r);
}
emit('+', std::string("weight ") + v.text("kind") + " = " + std::to_string((prep().pitch->automatic_weights >> shift) & 3));
});
add({"Lineup.Pitch", "ShowAutoWeights", {}, "the three automatic line-up weights", false}, [this](const Values&) {
const auto p = prep();
if (!p.pitch) fail("E_ENGINE_GAP", "no pitch projection");
const char* names[3] = {"Position", "SideAndRole", "Fatigue"};
std::vector<std::vector<std::string>> rows;
for (int i = 0; i < 3; ++i) rows.push_back({names[i], std::to_string((p.pitch->automatic_weights >> (2 * i)) & 3)});
emit_table({"Weight", "Value"}, rows);
});
add({"Lineup.Pitch", "SetSquadView", {choice("view", {"A", "B"})}, "DATEN-A / DATEN-B", false}, [this](const Values&) { show_pitch(); });
// --- Lineup.Order: ORDER (06-verein 1.5): the four instructions of each starter ----------
auto show_orders = [this, lineup] {
const ui::LineupState l = lineup();
static const char* const kHead[5] = {"Row", "Player", "Offense", "Running", "Commitment"};
std::vector<std::vector<std::string>> rows;
for (const auto& pl : l.players) {
if (pl.player_id < 0 || !(pl.slot & 0x8000)) continue;
rows.push_back({"row:" + std::to_string(pl.row), utf8(pl.name), std::to_string(pl.board[2]), std::to_string(pl.board[3]),
std::to_string(pl.board[4]), std::to_string(pl.board[5])});
}
emit_table({kHead[0], kHead[1], kHead[2], kHead[3], kHead[4], "Fighting"}, rows);
emit('i', "values " + std::to_string(kOrderMin) + ".." + std::to_string(kOrderMax));
};
add({"Lineup.Pitch", "OpenOrder", {}, "ORDER: the instructions of the starters (Lineup.Order)", false}, [this, show_orders](const Values&) {
open_window("Lineup.Order");
show_orders();
});
add({"Lineup.Order", "ShowOrders", {}, "offense, running, commitment, fighting of every starter", false},
[show_orders](const Values&) { show_orders(); });
add({"Lineup.Order", "SetOrder", {first, choice("aspect", {"Offense", "Run", "Commitment", "Fighting"}), integer("value", kOrderMin, kOrderMax)},
"one instruction of a starter (as a click in its bar)", true},
[this, lineup, player_at, show_orders](const Values& v) {
const ui::LineupState l = lineup();
const auto& p = player_at(l, v.text("first"));
if (!app::LineupActions(*session_).order(l, p, v.choice("aspect"), int(v.integer("value")), revision_))
fail("E_RULE", "only a starter on the pitch gets instructions");
show_orders();
});
add({"Lineup.Pitch", "ShowPairs", {}, "the Hall partners stored on the tactics board", false},
[this](const Values&) { show_pairs(); });
add({"Lineup.Pitch", "PairPlayers", {first, second, integer("depth", 0, 19), integer("lane", 0, 8)},
"place the first Hall starter beside the second at the explicit target coordinates", true},
[this, player_at, pitch_context, send_pitch](const Values& v) {
const auto projection = prep();
if (!projection.pitch || projection.pitch->indoor != std::optional<bool>(true))
fail("E_RULE", "pairs are only available for a Hall match");
const auto first_player = player_at(projection.lineup, v.text("first"));
const auto second_player = player_at(projection.lineup, v.text("second"));
if (first_player.row == second_player.row)
fail("E_BAD_ARGUMENT", "two different players are needed");
if (first_player.row >= 11 || second_player.row >= 11 ||
!(first_player.slot & 0x8000) || !(second_player.slot & 0x8000))
fail("E_RULE", "only two nominated Hall starters can form a pair");
const auto r = app::LineupActions::move(pitch_context(), first_player,
int(v.integer("depth")), int(v.integer("lane")));
const auto target = app::LineupActions(*session_).pair_target(r, second_player.row);
if (target == app::LineupActions::PairTarget::invalid)
fail("E_RULE", "the target is not a valid Hall placement");
if (target != app::LineupActions::PairTarget::requested)
fail("E_RULE", "the target must form the requested pair; use a free place beside the second player");
send_pitch(r);
show_pairs();
});
for (const char* name : {"OpenTeamList", "OpenMarking", "ShowZoneCoverage", "OpenSetPieces"})
add({"Lineup.Pitch", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " has no projection/request yet"); });
// --- PlayerCard (06-verein 1.6) -------------------------------------------------------
add({"PlayerCard", "ShowPlayer", {detail::text("player", 0, true)}, "the card (another player of the squad by name)", false},
[this, lineup, player_at](const Values& v) {
if (v.has("player")) card_row_ = player_at(lineup(), v.text("player")).row;
show_player_card();
});
add({"PlayerCard", "OpenPlayer", {player}, "another player's card", false}, [this, lineup, player_at](const Values& v) {
card_row_ = player_at(lineup(), v.text("player")).row;
show_player_card();
});
add({"PlayerCard", "OpenPlayerStatistics", {}, "the development charts (own players)", false}, [this](const Values&) {
open_window("PlayerCard.Statistics");
show_player_statistics(0, true);
});
for (const char* name : {"Negotiate", "NationalSquadAdd", "NationalSquadRemove"})
add({"PlayerCard", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " comes with the transfer offers (stage 3b)"); });
const std::vector<std::string> charts = {"Value", "Form", "Strength", "Total"};
add({"PlayerCard.Statistics", "ShowPlayerStatistics", {choice("chart", charts, true), choice("mode", {"Absolute", "Relative"}, true)},
"a development chart as a series", false},
[this](const Values& v) {
if (v.has("chart")) chart_ = v.choice("chart");
if (v.has("mode")) chart_absolute_ = v.choice("mode") == 0;
show_player_statistics(chart_, chart_absolute_);
});
add({"PlayerCard.Statistics", "SetChart", {choice("chart", charts)}, "SPIELER-WERT / FORM / STÄRKE / GESAMT", false}, [this](const Values& v) {
chart_ = v.choice("chart");
show_player_statistics(chart_, chart_absolute_);
});
add({"PlayerCard.Statistics", "SetMode", {choice("mode", {"Absolute", "Relative"})}, "ABS / REL", false}, [this](const Values& v) {
chart_absolute_ = v.choice("mode") == 0;
show_player_statistics(chart_, chart_absolute_);
});
add({"PlayerCard.Statistics", "BackToPlayerInfo", {}, "back to the card", false}, [this](const Values&) {
close_window();
show_player_card();
});
}
void Console::show_player_card() {
const auto p = prep();
if (card_row_ < 0 || size_t(card_row_) >= p.player_cards.size()) fail("E_INTERNAL", "no such player card");
const ui::PlayerCardState& card = p.player_cards[size_t(card_row_)];
const auto& player = card.lineup.players.at(size_t(card.row));
const auto& a = player.attributes;
const auto le32 = [&](size_t at) {
return uint32_t(player.board[at]) | uint32_t(player.board[at + 1]) << 8 | uint32_t(player.board[at + 2]) << 16 |
uint32_t(player.board[at + 3]) << 24;
};
const auto value = ui::player_card_market_value(a, exe_);
emit_table({"Card", "Value"},
{{"name", utf8(player.name)},
{"id", "id:" + std::to_string(player.player_id)},
{"age", std::to_string(a.age())},
{"nationality", utf8(card.nationality_name)},
{"position", text(kPositionNames + a.position())},
{"place", slot_state(player.slot)},
{"out", absence(a)},
{"condition/technique/form", std::to_string(a.condition()) + "/" + std::to_string(a.technique()) + "/" + std::to_string(a.form())},
{"strength", std::to_string(a.strength())},
{"contractMonths", player.board[0xc] == 255 ? "-" : std::to_string(player.board[0xc])},
{"salary", money(le32(0x50))},
{"purchasePrice", le32(0x54) ? money(le32(0x54)) : "-"},
{"marketValue", value ? money(*value) : "?"},
{"monthsAtClub", std::to_string(player.board[0x11] + 1)}}); // "Seit N Monaten im Verein" (ClubPlayerDetail_RenderCard_ExecutableField..ClubPlayerDetail_RenderCard_ExecutableField4)
std::vector<std::vector<std::string>> skills;
for (int i = 0; i < 7; ++i) skills.push_back({text(kSkillNames + i), text(kRatings + a.skill(Player::Skill(i)))});
emit_table({"Skill", "Rating"}, skills);
if (!card.unsupported_record.empty()) emit('i', "not shown: " + card.unsupported_record);
}
void Console::show_player_statistics(int chart, bool absolute) {
const auto p = prep();
if (card_row_ < 0 || size_t(card_row_) >= p.player_cards.size()) fail("E_INTERNAL", "no such player card");
const ui::PlayerCardState& card = p.player_cards[size_t(card_row_)];
if (!card.statistics) fail("E_RULE", "statistics only for own players");
const auto points = ui::player_statistics_points(card, exe_, chart, absolute);
const char* names[4] = {"Value", "Form", "Strength", "Total"};
std::string series;
for (const auto& [month, v] : points) series += (series.empty() ? "" : " ") + std::to_string(month) + ":" + std::to_string(v);
emit('i', std::string(names[chart]) + (absolute ? " (absolute)" : " (relative)") + ": " + (series.empty() ? "-" : series));
}
void Console::show_pairs() {
const auto p = prep();
if (!p.pitch || p.pitch->indoor != std::optional<bool>(true))
fail("E_RULE", "pairs are only available for a Hall match");
std::vector<std::vector<std::string>> rows;
int pairs = 0;
for (const auto& pl : p.lineup.players) {
if (pl.row >= 11 || pl.player_id < 0 || !(pl.slot & 0x8000)) continue;
const size_t partner = pl.board[0x3f];
std::string partner_row = "-", partner_name = "-";
if (partner < 11 && partner != size_t(pl.row) && partner < p.lineup.players.size()) {
const auto& other = p.lineup.players[partner];
if (other.player_id >= 0 && (other.slot & 0x8000) && other.board[0x3f] == pl.row) {
partner_row = "row:" + std::to_string(other.row);
partner_name = utf8(other.name);
if (pl.row < other.row) ++pairs;
}
}
rows.push_back({"row:" + std::to_string(pl.row), utf8(pl.name), partner_row, partner_name});
}
emit_table({"Row", "Player", "PartnerRow", "Partner"}, rows);
emit('i', "Hall pairs: " + std::to_string(pairs));
}
void Console::show_pitch() {
const auto p = prep();
std::vector<std::vector<std::string>> rows;
for (const auto& pl : p.lineup.players) {
if (pl.player_id < 0 || !(pl.slot & 0xc000)) continue;
rows.push_back({"row:" + std::to_string(pl.row), utf8(pl.name), slot_state(pl.slot),
(pl.slot & 0x8000) ? std::to_string(int8_t(pl.board[0x41])) : "-",
(pl.slot & 0x8000) ? std::to_string(int8_t(pl.board[0x42])) : "-"});
}
emit_table({"Row", "Player", "Place", "Depth", "Lane"}, rows);
if (p.pitch) {
std::string saved;
for (int f = 0; f < 8; ++f)
if (p.pitch->formation_mask & (1 << f)) saved += (saved.empty() ? "" : " ") + std::to_string(f + 1);
emit('i', "formations available: " + (saved.empty() ? std::string("-") : saved) + "; automatic formation " +
std::to_string(p.lineup.automatic_formation));
if (p.pitch->indoor == std::optional<bool>(true)) show_pairs();
}
}
} // namespace bmh::cli::console
+517
View File
@@ -0,0 +1,517 @@
// SPDX-License-Identifier: GPL-3.0-only
// The start of a game (docs/CLI_CONCEPT/03-start.md): the options screen NewGame, the manager
// selection NewGame.Select with its confirmation, the info sequence after the last manager,
// and the file windows (load browser at the start, LoadGame/SaveGame on the desk, 04-schreibtisch 8).
#include <algorithm>
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "ui/cup_draw.hpp"
#include "ui/desk_state.hpp"
#include "ui/season_entrants.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// TEXTD indices (docs/formats/textd_inventory.csv)
constexpr int kStrengthBottomThird = 18; // strengthBottomThird "unteres Drittel"
constexpr int kErrorNotAGameScore = 814; // "Dies ist kein BUNDESLIGA MANAGER Hattrick - Spielstand!"
constexpr int kSaveConfirmOverwrite = 854; // "Möchten Sie diese Datei wirklich überschreiben?"
constexpr int kManagerConfirmAllDetailsCorrect = 907; // "Sind alle Angaben richtig?"
// The picker tabs as the console names them (03-start 3); index = ManagerScreen group.
const std::vector<std::string> kTabs = {"Bundesliga", "SecondLeague", "RegionalA", "RegionalB",
"Oberliga", "AdditionalA", "AdditionalB"};
const std::vector<std::string> kStartLeagues = {"Bundesliga", "SecondLeague", "RegionalA", "RegionalB", "Oberliga"};
// ManagerChoice::strength: 0 lower, 1 middle, 2 upper third
const std::vector<std::string> kStrengths = {"Lower", "Middle", "Upper"};
} // namespace
void Console::register_start_commands() {
// --- NewGame: the options screen (03-start 1) -----------------------------------------
add({"NewGame", "ShowOptions", {}, "show the options with their current values", false}, [this](const Values&) {
emit_table({"Option", "Value"},
{{"duration", setup_.duration == 5 ? "endless" : std::to_string(setup_.duration)},
{"difficulty", std::to_string(setup_.difficulty + 1)},
{"managers", std::to_string(setup_.managers)},
{"mode", std::to_string(setup_.mode)},
{"league", on_off(setup_.league)},
{"world", on_off(setup_.world)}});
});
add({"NewGame", "NewGame",
{integer("duration", 1, 5), integer("difficulty", 1, 10), integer("managers", 1, 4), integer("mode", 1, 3),
boolean("league"), boolean("world")},
"set all options and continue (= right mouse)", true},
[this](const Values& v) {
if (!v.boolean("league") && !v.boolean("world"))
fail("E_BAD_ARGUMENT", "league and world mode cannot both be off");
setup_.duration = int(v.integer("duration"));
setup_.difficulty = int(v.integer("difficulty")) - 1; // shown 1-10, stored 0-9
setup_.managers = int(v.integer("managers"));
setup_.mode = int(v.integer("mode"));
setup_.league = v.boolean("league");
setup_.world = v.boolean("world");
new_game_continue();
});
add({"NewGame", "SetDuration", {integer("duration", 1, 5)}, "1-4 seasons, 5 = endless", true},
[this](const Values& v) { setup_.duration = int(v.integer("duration")); emit('+', "duration set"); });
add({"NewGame", "SetDifficulty", {integer("difficulty", 1, 10)}, "number of balls", true},
[this](const Values& v) { setup_.difficulty = int(v.integer("difficulty")) - 1; emit('+', "difficulty set"); });
add({"NewGame", "SetManagers", {integer("managers", 1, 4)}, "human managers", true},
[this](const Values& v) { setup_.managers = int(v.integer("managers")); emit('+', "managers set"); });
add({"NewGame", "SetMode", {integer("mode", 1, 3)}, "range of desk functions", true},
[this](const Values& v) { setup_.mode = int(v.integer("mode")); emit('+', "mode set"); });
add({"NewGame", "SetLeagueMode", {boolean("on")}, "league mode on/off", true}, [this](const Values& v) {
if (!v.boolean("on") && !setup_.world) fail("E_RULE", "league and world mode cannot both be off");
setup_.league = v.boolean("on");
emit('+', "league mode " + on_off(setup_.league));
});
add({"NewGame", "SetWorldMode", {boolean("on")}, "world cup mode on/off", true}, [this](const Values& v) {
if (!v.boolean("on") && !setup_.league) fail("E_RULE", "league and world mode cannot both be off");
setup_.world = v.boolean("on");
emit('+', "world mode " + on_off(setup_.world));
});
add({"NewGame", "OpenLoadBrowser", {}, "open the load browser", false},
[this](const Values&) {
browse_directory_ = std::filesystem::absolute(save_directory()).lexically_normal();
selected_file_.clear();
set_window("NewGame.LoadGame", 1);
});
add({"NewGame", "LoadGame", {detail::text("filename")}, "load a saved game", true}, [this](const Values& v) {
std::filesystem::path path(v.text("filename"));
if (path.is_relative()) path = save_directory() / path;
load_game(path);
});
// --- NewGame.Select: who plays? (03-start 3) ------------------------------------------
Param tab = detail::text("league", 0, true);
tab.display = "[league:int|tab:enum]";
add({"NewGame.Select", "ListTeams", {tab}, "clubs of a picker tab (Bundesliga ... AdditionalB)", false},
[this](const Values& v) {
int group = -1;
if (v.has("league")) {
Arg a;
a.text = v.text("league");
for (size_t i = 0; i < kTabs.size(); ++i)
if (canonical(kTabs[i]) == canonical(a.text)) group = int(i);
if (group < 0)
if (const auto n = to_int(a); n && *n >= 0 && *n < ui::ManagerScreen::group_count) group = int(*n);
if (group < 0) fail("E_BAD_ARGUMENT", "league must be 0..6 or one of Bundesliga, SecondLeague, RegionalA, "
"RegionalB, Oberliga, AdditionalA, AdditionalB");
} else {
for (int g = 0; g < ui::ManagerScreen::group_count; ++g)
if (draft_.selection_club >= picker_->group_first(g) && draft_.selection_club <= picker_->group_last(g)) group = g;
if (group < 0) group = 0;
}
const std::string label = utf8(picker_->group_label(group));
emit('i', canonical(label) == canonical(kTabs[size_t(group)]) ? label : kTabs[size_t(group)] + ": " + label);
std::vector<std::vector<std::string>> rows;
for (int sel = picker_->group_first(group); sel <= picker_->group_last(group); ++sel) {
const int master = picker_->master_of(sel);
std::string taken = "-";
for (const auto& c : confirmed_)
if (c.master_club == master) taken = "P" + std::to_string(c.slot + 1);
std::string name = utf8(picker_->club_name(master));
if (master == draft_.master_club) name += " [selected]";
rows.push_back({"club:" + std::to_string(master), name, taken});
}
emit_table({"Club", "Name", "Taken"}, rows);
});
add({"NewGame.Select", "ListPortraits", {}, "the twelve portraits and who took them", false}, [this](const Values&) {
std::vector<std::vector<std::string>> rows;
for (int p = 0; p < 12; ++p) {
std::string taken = "-";
for (const auto& c : confirmed_)
if (c.portrait == p) taken = "P" + std::to_string(c.slot + 1);
rows.push_back({std::to_string(p), taken + (p == draft_.portrait ? " [selected]" : "")});
}
emit_table({"Portrait", "Taken"}, rows);
});
add({"NewGame.Select", "ListStrengths", {}, "the three club strengths", false}, [this](const Values&) {
std::vector<std::vector<std::string>> rows;
for (int s = 2; s >= 0; --s) rows.push_back({kStrengths[size_t(s)], text(kStrengthBottomThird + s)});
emit_table({"Strength", "Text"}, rows);
});
add({"NewGame.Select", "ShowSelection", {}, "the choices of this player", false}, [this](const Values&) {
emit_table({"Field", "Value"},
{{"managerName", utf8(draft_.name)},
{"club", "club:" + std::to_string(draft_.master_club) + " " + utf8(picker_->club_name(draft_.master_club))},
{"startLeague", kStartLeagues[size_t(draft_.start_league)]},
{"strength", kStrengths[size_t(draft_.strength)]},
{"portrait", std::to_string(draft_.portrait)}});
});
// The single choices; SelectTeam sets all five and confirms. Each check happens before
// anything changes, so a failed SelectTeam leaves the draft as it was.
auto set_name = [this](ui::ManagerChoice& c, const std::string& utf8) {
if (utf8.empty()) fail("E_BAD_ARGUMENT", "the name must not be empty");
std::string original;
try {
original = ui::utf8_to_original(utf8);
} catch (const std::exception&) {
fail("E_BAD_ARGUMENT", "the name has a character the game cannot show");
}
if (original.size() > 20) fail("E_BAD_ARGUMENT", "the name has more than 20 characters");
c.name = original;
};
auto set_club = [this](ui::ManagerChoice& c, const std::string& reference) {
const int master = resolve_club(reference);
for (const auto& other : confirmed_)
if (other.master_club == master)
fail("E_RULE", "the club is taken by player " + std::to_string(other.slot + 1));
for (int sel = 0; sel <= picker_->group_last(ui::ManagerScreen::group_count - 1); ++sel)
if (picker_->master_of(sel) == master) {
c.selection_club = sel;
c.master_club = master;
return;
}
fail("E_BAD_ARGUMENT", "the club cannot be chosen");
};
auto set_portrait = [this](ui::ManagerChoice& c, int portrait) {
for (const auto& other : confirmed_)
if (other.portrait == portrait) fail("E_RULE", "the portrait is taken by player " + std::to_string(other.slot + 1));
c.portrait = portrait;
};
add({"NewGame.Select", "SetManagerName", {detail::text("name", 0)}, "the manager's name (1-20 characters)", true},
[this, set_name](const Values& v) { set_name(draft_, v.text("name")); emit('+', "name: " + utf8(draft_.name)); });
Param club = detail::text("club");
club.display = "club:Club";
add({"NewGame.Select", "SetClub", {club}, "the club: club:<n> from ListTeams or \"name\"", true},
[this, set_club](const Values& v) {
set_club(draft_, v.text("club"));
emit('+', "club: " + utf8(picker_->club_name(draft_.master_club)));
});
add({"NewGame.Select", "SetStartLeague", {choice("league", kStartLeagues)}, "the league to start in", true},
[this](const Values& v) { draft_.start_league = v.choice("league"); emit('+', "start league: " + kStartLeagues[size_t(draft_.start_league)]); });
add({"NewGame.Select", "SetStrength", {choice("strength", {"Upper", "Middle", "Lower"})}, "the club's strength", true},
[this](const Values& v) { draft_.strength = 2 - v.choice("strength"); emit('+', "strength: " + kStrengths[size_t(draft_.strength)]); });
add({"NewGame.Select", "SetPortrait", {integer("portrait", 0, 11)}, "the manager's portrait", true},
[this, set_portrait](const Values& v) { set_portrait(draft_, int(v.integer("portrait"))); emit('+', "portrait: " + std::to_string(draft_.portrait)); });
add({"NewGame.Select", "SelectTeam",
{detail::text("managerName"), club, choice("startLeague", kStartLeagues), choice("strength", {"Upper", "Middle", "Lower"}),
integer("portrait", 0, 11)},
"set all five and ask for confirmation", true},
[this, set_name, set_club, set_portrait](const Values& v) {
ui::ManagerChoice c = draft_;
set_name(c, v.text("managerName"));
set_club(c, v.text("club"));
c.start_league = v.choice("startLeague");
c.strength = 2 - v.choice("strength");
set_portrait(c, int(v.integer("portrait")));
draft_ = c;
confirm_selection();
});
add({"NewGame.Select", "Confirm", {}, "show the summary and ask \"all details correct?\"", true},
[this](const Values&) { confirm_selection(); });
add({"NewGame.Select.Confirm", "ShowSummary", {}, "the choices of this player", false}, [this](const Values&) {
emit_table({"Field", "Value"},
{{"managerName", utf8(draft_.name)},
{"club", utf8(picker_->club_name(draft_.master_club))},
{"startLeague", utf8(picker_->group_label(draft_.start_league))},
{"strength", text(kStrengthBottomThird + draft_.strength)},
{"portrait", std::to_string(draft_.portrait)}});
});
}
// ---------------------------------------------------------------------------------------
// start flow
std::string Console::options_text() const {
return "duration=" + (setup_.duration == 5 ? std::string("endless") : std::to_string(setup_.duration)) +
" difficulty=" + std::to_string(setup_.difficulty + 1) + " managers=" + std::to_string(setup_.managers) +
" mode=" + std::to_string(setup_.mode) + " league=" + on_off(setup_.league) + " world=" + on_off(setup_.world);
}
void Console::new_game_continue() {
// The options are taken over with the first manager (CareerSession::confirm_manager).
set_window("NewGame.Select", 1);
emit('+', "Options set: " + options_text());
begin_selection(0);
}
// The manager dialog for `slot`: the original picker model gives the tab ranges and the
// defaults (name "Manager n", the first free club and portrait). The club order comes from
// the engine: confirming a manager can move clubs between leagues (ConfirmManager).
void Console::begin_selection(int slot) {
picker_ = std::make_unique<ui::ManagerScreen>(options_.data, slot, confirmed_, session_->selection_context(revision_));
draft_ = picker_->choice();
}
// A club reference (01-grundlagen 1.3): club:<n> / <n> (master index) or a name. Names
// compare without case (also Ä/Ö/Ü); an exact name wins, otherwise a unique part of a name
// is enough ("Bayern").
int Console::resolve_club(const std::string& reference) const {
std::string number = reference;
if (lower(number).rfind("club:", 0) == 0) number = number.substr(5);
Arg n;
n.text = number;
const int last = picker_->group_last(ui::ManagerScreen::group_count - 1);
if (const auto id = to_int(n)) {
for (int sel = 0; sel <= last; ++sel)
if (picker_->master_of(sel) == *id) return int(*id);
fail("E_BAD_ARGUMENT", "no club " + reference + " in the selection (see ListTeams)");
}
const std::string wanted = fold(reference);
std::vector<int> exact, partial;
for (int sel = 0; sel <= last; ++sel) {
const int master = picker_->master_of(sel);
const std::string name = fold(utf8(picker_->club_name(master)));
if (name == wanted) exact.push_back(master);
else if (name.find(wanted) != std::string::npos) partial.push_back(master);
}
const auto& found = exact.empty() ? partial : exact;
if (found.size() == 1) return found.front();
if (found.empty()) fail("E_BAD_ARGUMENT", "no club named \"" + reference + "\" (see ListTeams)");
std::string candidates;
for (size_t i = 0; i < found.size() && i < 8; ++i)
candidates += (i ? ", " : "") + utf8(picker_->club_name(found[i])) + " = club:" + std::to_string(found[i]);
fail("E_AMBIGUOUS", "\"" + reference + "\" fits several clubs: " + candidates);
}
void Console::confirm_selection() {
// PresentManagerDialog: the summary and "Sind alle Angaben richtig?"; No = back to the same
// player's selection, everything can be changed (H2 S. 15).
open_window("NewGame.Select.Confirm");
emit_table({"Field", "Value"},
{{"managerName", utf8(draft_.name)},
{"club", utf8(picker_->club_name(draft_.master_club))},
{"startLeague", utf8(picker_->group_label(draft_.start_league))},
{"strength", text(kStrengthBottomThird + draft_.strength)},
{"portrait", std::to_string(draft_.portrait)}});
ask(text(kManagerConfirmAllDetailsCorrect), {"Yes", "No"}, "No", [this](const std::string& answer) {
close_window();
if (answer != "Yes") {
emit('+', "selection not confirmed");
return;
}
std::string error;
if (!session_->confirm_manager(setup_, draft_, error))
fail("E_RULE", "the engine rejects the manager: " + error);
confirmed_.push_back(draft_);
emit('+', "Manager " + std::to_string(confirmed_.size()) + " confirmed: " + utf8(draft_.name) + ", " +
utf8(picker_->club_name(draft_.master_club)));
if (int(confirmed_.size()) < setup_.managers) {
set_window("NewGame.Select", int(confirmed_.size()) + 1);
begin_selection(int(confirmed_.size()));
return;
}
finish_career();
});
}
// After the last manager: the start values, the first season up to the first desk
// (CareerSession::finish), and the info windows of the intermediate sequence (03-start 4).
void Console::finish_career() {
ui::CareerInitializationResult init;
std::string error;
if (!session_->finish(init, error)) fail("E_INTERNAL", "the career cannot start: " + error);
career_ = true;
revision_ = init.desktop.revision;
picker_.reset();
// the entrants and cup draws of the intermediate sequence came through the hooks
flush_info();
enter_desktop();
}
// Installed on the session: the cup draws the engine makes inside finish() and kickoffs
// (CupDrawFromGame / Getenv). They are projected while the hook runs - the state moves
// on afterwards - and printed when the engine call returns (Info.CupDraw, 02-fenster 2).
// The projection is the SDL app's; it reads the state and draws no random numbers.
void Console::install_hooks() {
// SeasonEntrantsFromGame / CompetitionWinnerScreen: the German entrants of the European cups, at the start of
// a career (03-start 4) and at every season change. The engine pauses at this checkpoint
// inside finish() / a kickoff; the pages are projected there (Info.EuropeanEntrants).
session_->set_season_pause([this](const char* checkpoint, const GameState& state) {
if (std::string_view(checkpoint) != "the German entrants (CompetitionWinnerScreen)") return;
std::vector<std::string> lines;
for (const auto& page : ui::season_entrants_from_game(state, exe_, texts_)) {
std::string names;
for (const auto& t : page.teams) names += (names.empty() ? "" : ", ") + t.name;
lines.push_back(page.footer + ": " + names);
}
if (lines.empty()) return;
pending_info_.push_back([this, lines] {
set_window("Info.EuropeanEntrants", 0);
for (const auto& l : lines) emit('i', l);
});
});
session_->set_season_cup_draw([this](const GameState& state, const SeasonCupDrawEvent& event) {
const ui::CupDrawProjection view = ui::cup_draw_from_game(state, event, exe_, texts_);
if (!view.source_eligible) return;
const std::string title = utf8(view.footer) + ", " + utf8(view.heading);
if (event.phase == SeasonCupDrawPhase::draw && !view.group_stage) {
std::vector<std::vector<std::string>> rows;
for (size_t i = 0; i + 1 < view.clubs.size(); i += 2)
rows.push_back({utf8(view.clubs[i].original_name), utf8(view.clubs[i + 1].original_name)});
if (view.clubs.size() % 2) rows.push_back({utf8(view.clubs.back().original_name), "-"});
pending_info_.push_back([this, title, rows] {
set_window("Info.CupDraw", 0);
emit('i', title + ":");
emit_table({"Home", "Away"}, rows);
});
} else if (event.phase == SeasonCupDrawPhase::overview && view.group_stage) {
std::vector<std::vector<std::string>> rows;
for (const auto& r : view.group_rows)
rows.push_back({std::to_string(r.rank), utf8(state.club_name(r.runtime_id))});
const std::string caption = title + (view.group_caption.empty() ? "" : " " + utf8(view.group_caption));
pending_info_.push_back([this, caption, rows] {
set_window("Info.CupDraw", 0);
emit('i', caption + ":");
emit_table({"Rank", "Club"}, rows);
});
}
});
}
void Console::flush_info() {
auto items = std::move(pending_info_);
pending_info_.clear();
for (auto& f : items) f();
}
// ---------------------------------------------------------------------------------------
// file windows (03-start 2, 04-schreibtisch 8)
std::filesystem::path Console::save_directory() const {
return options_.save_directory.empty() ? options_.data : options_.save_directory;
}
// The browser's directory relative to the save directory ("." at the start), so logs and
// transcripts do not depend on where the installation lies.
std::string Console::shown_directory() const {
std::error_code ec;
const std::filesystem::path rel = std::filesystem::relative(browse_directory_, save_directory(), ec);
return ec || rel.empty() ? browse_directory_.generic_string() : rel.generic_string();
}
// A file name of the browser is a plain DOS name in the current directory: separators, drive
// colons and "." / ".." would write or read outside it (directories change only through
// ChangeDirectory / ParentDirectory, as in the original browser).
std::filesystem::path Console::browser_file(const std::string& name) const {
if (name == "." || name == ".." || name.find_first_of("/\\:") != std::string::npos)
fail("E_BAD_ARGUMENT", "not a file name: " + name + " (no directories; use ChangeDirectory)");
std::filesystem::path path = browse_directory_ / name;
if (!path.has_extension()) path += ".FBM";
return path;
}
void Console::register_file_commands() {
// The original browser shows subdirectories and the *.FBM files of the current directory;
// a click selects a file (FILENAME field), a second click loads it. The same commands
// serve the load browser of the options screen and the desk's LoadGame/SaveGame.
for (const std::string window : {"NewGame.LoadGame", "LoadGame", "SaveGame"}) {
add({window, "ListFiles", {}, "directories and saved games here", false}, [this](const Values&) {
std::vector<std::vector<std::string>> dirs, files;
std::error_code ec;
for (const auto& entry : std::filesystem::directory_iterator(browse_directory_, ec)) {
if (entry.is_directory(ec)) dirs.push_back({entry.path().filename().string(), "dir"});
else if (entry.is_regular_file(ec) && lower(entry.path().extension().string()) == ".fbm")
files.push_back({entry.path().stem().string(), "file"});
}
if (ec) fail("E_IO", "cannot read the directory " + shown_directory());
std::sort(dirs.begin(), dirs.end());
std::sort(files.begin(), files.end());
dirs.insert(dirs.end(), files.begin(), files.end());
emit('i', "directory: " + shown_directory());
emit_table({"Name", "Type"}, dirs);
});
add({window, "ChangeDirectory", {detail::text("name")}, "into a subdirectory", false}, [this](const Values& v) {
const std::filesystem::path next = browse_directory_ / v.text("name");
std::error_code ec;
if (!std::filesystem::is_directory(next, ec)) fail("E_BAD_ARGUMENT", "no directory " + v.text("name"));
browse_directory_ = next.lexically_normal();
emit('+', "directory: " + shown_directory());
});
add({window, "ParentDirectory", {}, "one level up", false}, [this](const Values&) {
browse_directory_ = browse_directory_.parent_path();
emit('+', "directory: " + shown_directory());
});
add({window, "SelectFile", {detail::text("name", 8)}, "select a file (FILENAME field, DOS name)", false},
[this](const Values& v) {
selected_file_ = v.text("name");
emit('+', "selected: " + selected_file_);
});
add({window, "FileInfo", {detail::text("name")}, "short info of a saved game", false}, [](const Values&) {
fail("E_ENGINE_GAP", "the short info of saved games is not ported yet");
});
if (window != "SaveGame") {
add({window, "Load", {detail::text("name", 0, true)}, "load the selected or named file", true}, [this](const Values& v) {
const std::string name = v.has("name") ? v.text("name") : selected_file_;
if (name.empty()) fail("E_BAD_ARGUMENT", "no file selected (SelectFile or Load(name))");
load_game(browser_file(name));
});
} else {
add({window, "Save", {detail::text("name", 8, true), boolean("overwrite", true)},
"save under the selected or given name", true},
[this](const Values& v) {
const std::string name = v.has("name") ? v.text("name") : selected_file_;
// "Leerer Name = nichts gespeichert" (04-schreibtisch 8)
if (name.empty()) {
emit('+', "nothing saved (no name)");
return;
}
save_game(browser_file(name), v.boolean("overwrite"));
});
}
}
}
void Console::load_game(const std::filesystem::path& requested) {
std::filesystem::path path = requested;
if (!path.has_extension()) path += ".FBM";
std::error_code ec;
if (!std::filesystem::is_regular_file(path, ec)) fail("E_IO", "file not found: " + path.filename().string());
std::unique_ptr<app::CareerSession> loaded;
try {
loaded = std::make_unique<app::CareerSession>(options_.data, options_.seed, path);
} catch (const std::exception&) {
fail("E_RULE", text(kErrorNotAGameScore), "errorNotAGameScore");
}
session_ = std::move(loaded);
install_hooks();
career_ = true;
revision_ = 1;
confirmed_.clear();
picker_.reset();
seen_mail_.clear();
pairings_.reset();
table_league_ = -1;
const ui::DeskState d = session_->desktop_projection(revision_);
// The messages of a loaded game are not new: count them instead of repeating them all.
size_t messages = 0;
for (size_t slot = 0; slot < session_->state().manager_teams.size(); ++slot)
for (const auto& m : ui::mailbox_state_from_game(session_->state(), int(slot), revision_).messages) {
seen_mail_[int(slot)].insert(std::to_string(m.date_counter) + "|" + m.text);
if (int(slot) == d.manager_slot) ++messages;
}
set_window("Desktop", d.manager_slot + 1);
emit('+', "Game loaded: " + path.stem().string() + " (" + utf8(d.club_name) + ", " +
date_text(d.date.day, d.date.month, d.date.year) + ", " + std::to_string(messages) + " messages in the mailbox)");
enter_desktop();
}
void Console::save_game(const std::filesystem::path& path, bool overwrite) {
std::error_code ec;
auto write = [this, path](bool allow_overwrite) {
std::string error;
if (!session_->save_game(path, active_slot(), allow_overwrite, error)) fail("E_IO", "not saved: " + error);
emit('+', "Game saved: " + path.stem().string());
};
if (std::filesystem::exists(path, ec) && !overwrite) {
ask(text(kSaveConfirmOverwrite), {"Yes", "No"}, "No",
[this, write](const std::string& answer) {
if (answer == "Yes") write(true);
else emit('+', "nothing saved");
},
"saveConfirmOverwrite");
return;
}
write(overwrite);
}
} // namespace bmh::cli::console
+306
View File
@@ -0,0 +1,306 @@
// SPDX-License-Identifier: GPL-3.0-only
// State(view): the engine projection behind a view as one structured record (Stufe 2.5 of
// docs/CLI_CONCEPT, "strukturierte Daten"). A graphical front end that talks to the console
// (mailbox --serve, socket --listen) reads its screens from here instead of parsing text:
// the same projections the SDL windows draw, serialised by the ui layer's *_json functions
// (src/ui), plus two small records the ui layer has no serialiser for (line-up, mailbox).
// Text mode prints the JSON after "state <view>:"; with --json it is the line's "data".
// Read-only: no projection here draws random numbers or changes the game.
#include <cstdint>
#include <string>
#include <vector>
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "cli/json.hpp"
#include "ui/advertising.hpp"
#include "ui/bank.hpp"
#include "ui/contracts.hpp"
#include "ui/desk_state.hpp"
#include "ui/league_table.hpp"
#include "ui/mailbox_state.hpp"
#include "ui/stadium.hpp"
#include "ui/toto.hpp"
#include "ui/training.hpp"
#include "ui/training_camp.hpp"
#include "ui/transfer_market.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
#include <algorithm>
namespace bmh::cli::console {
using namespace detail;
namespace {
const std::vector<std::string> kStateViews = {"Desk", "Table", "Lineup", "Mailbox", "Bank", "Market",
"Advertising", "Contracts", "Stadium", "Toto", "Training", "Camp"};
// One squad row as the line-up screen knows it (DATEN-A and DATEN-B together): the
// attributes of m3d.hpp, the place (slot flags 0x8000 pitch / 0x4000 bench), the absence
// (w364 bits 16-19 duration, bit 20 ban) and the contract fields of the board row.
Json lineup_record(const ui::LineupState& l) {
Json::Array players;
for (const auto& p : l.players) {
if (p.player_id < 0) continue;
const auto& a = p.attributes;
const int duration = int(a.w364 >> 16 & 0xF);
Json::Array skills;
for (int i = 0; i < 7; ++i) skills.emplace_back(a.skill(Player::Skill(i)));
const auto le32 = [&](size_t at) {
return std::int64_t(uint32_t(p.board[at]) | uint32_t(p.board[at + 1]) << 8 | uint32_t(p.board[at + 2]) << 16 |
uint32_t(p.board[at + 3]) << 24);
};
players.emplace_back(Json::Object{
{"row", p.row},
{"id", p.player_id},
{"name", utf8(p.name)},
{"position", a.position()}, // 0 goalkeeper, 1 defender, 2 midfielder, 3 forward
{"condition", a.condition()},
{"technique", a.technique()},
{"form", a.form()},
{"strength", a.strength()},
{"age", a.age()},
{"skills", Json(std::move(skills))}, // 0-3 each: teamplay, speed, shot, pass, tackling, free kick, corner
{"place", std::string((p.slot & 0x8000) ? "pitch" : (p.slot & 0x4000) ? "bench" : "out")},
{"injury", duration != 0 && !(a.w364 & 0x100000) ? duration : 0},
{"ban", duration != 0 && (a.w364 & 0x100000) ? duration : 0},
{"games", int(a.w364 >> 26)},
{"goals", int(a.w364 >> 2 & 63)},
{"assists", int(a.w368 >> 18 & 63)},
{"yellow_cards", int(a.w368 >> 14 & 15)},
{"red_cards", int(a.w368 >> 24 & 7)},
{"contract_months", p.board[0xc] == 255 ? Json(nullptr) : Json(int(p.board[0xc]))},
{"months_at_club", int(p.board[0x11]) + 1},
{"salary", le32(0x50)},
});
}
return Json(Json::Object{{"manager_slot", l.manager_slot}, {"players", Json(std::move(players))}});
}
Json mailbox_record(const ui::MailboxState& m) {
Json::Array messages;
int index = 0;
for (const auto& msg : m.messages)
messages.emplace_back(Json::Object{{"index", ++index}, {"date_counter", int(msg.date_counter)}, {"text", msg.text}});
return Json(Json::Object{{"manager_slot", m.manager_slot}, {"messages", Json(std::move(messages))}});
}
} // namespace
// --- Advice and Scoreboard (for agents that learn: docs/CLI_CONCEPT/16-playbook.md) -------
// Advice names what needs a decision now, from the engine's own data; it judges nothing
// the player could not see on his screens, it only collects it. Scoreboard compares the
// human managers. Both read only.
void Console::register_advice_commands() {
add({"*", "Advice", {}, "situations that need a decision now: form, squad, contracts, advertising, money", false},
[this](const Values& v) {
if (!career_) fail("E_NOT_IN_WINDOW", "Advice needs a running game");
own_view_only(v.player, "Advice");
const ui::DeskState d = desk();
if (d.national_team) {
emit('i', "advice: you coach the national team now; the club's matters wait until it ends");
return;
}
const GameState& g = session_->state();
const int slot = d.manager_slot;
const int team = g.manager_teams.at(size_t(slot));
int alerts = 0;
auto alert = [&](const std::string& topic, const std::string& text, Json values = nullptr) {
++alerts;
Json::Object o{{"topic", topic}, {"text", text}};
if (!std::holds_alternative<std::nullptr_t>(values.value)) o["values"] = std::move(values);
emit('i', "advice [" + topic + "] " + text, Json(std::move(o)));
};
// form: the points of the last three matchdays and the place (three points a win)
const int league = team_league(team);
if (league >= 0 && league < kLeagueCount) {
const int rounds = int(int8_t(g.league_rounds.at(size_t(league))));
const int pos = team - league_first_team(league);
const ui::LeagueTableState table = ui::league_table_from_game(g, slot, league);
int rank = 0, points = 0, games = 0;
for (const auto& r : table.rows)
if (r.runtime_team_id == team) rank = r.rank, points = r.points, games = r.games;
if (rounds >= 3) {
const LeagueTable recent = compute_league_table(g, league, rounds - 3, rounds, 3, 1);
const int recent_points = recent.points[size_t(pos)], recent_games = recent.games(pos);
if (recent_games >= 3 && recent_points <= 1)
alert("form", std::to_string(recent_points) + " points from the last " + std::to_string(recent_games) +
" league matches - line-up, tactics or training need a change",
Json(Json::Object{{"recent_points", recent_points}, {"recent_games", recent_games}}));
}
const int size = int(table.rows.size());
if (games >= 8 && size > 0 && rank > size - 4)
alert("table", "place " + std::to_string(rank) + " of " + std::to_string(size) + " after " +
std::to_string(games) + " matches - relegation zone",
Json(Json::Object{{"rank", rank}, {"points", points}, {"games", games}}));
}
// tactics: the match engine keeps a human side's attitude (item 0) fixed for the whole
// match unless the assistant controls it; 0 is the most defensive. New careers
// start at 0, and human clubs then score far less than the computer clubs (the
// original does the same: its human Bayern scored 28 goals in a season).
{
const ui::TacticsState t = prep().tactics;
if (t.values[0] == 0 && t.assistant_attitude == 0)
alert("tactics", "attitude (tactic item 0) is 0, the most defensive, for whole matches - "
"SetTactic(0, 2) (computer clubs play 2 at home, 1 away) or SetAutomation(Tactics, true)",
Json(Json::Object{{"attitude", 0}, {"assistant", false}}));
}
// squad: size, goalkeepers, absences in the eleven, weak form of starters
const ui::LineupState l = prep().lineup;
int players = 0, keepers = 0, fit_keepers = 0;
std::vector<std::string> absent, weak, expiring;
for (const auto& p : l.players) {
if (p.player_id < 0) continue;
const auto& a = p.attributes;
++players;
const bool out = (a.w364 >> 16 & 0xF) != 0;
if (a.position() == 0) ++keepers, fit_keepers += out ? 0 : 1;
const bool starter = (p.slot & 0x8000) != 0;
if (starter && out) absent.push_back(utf8(p.name));
if (starter && !out && a.form() < 45) weak.push_back(utf8(p.name) + " (form " + std::to_string(a.form()) + ")");
if (p.board[0xc] != 255 && p.board[0xc] <= 2)
expiring.push_back(utf8(p.name) + " (" + std::to_string(p.board[0xc]) + " months)");
}
auto list = [](const std::vector<std::string>& v) {
std::string s;
for (const auto& x : v) s += (s.empty() ? "" : ", ") + x;
return s;
};
if (players < 18) alert("squad", std::to_string(players) + " players - too few for injuries and bans (keep 20-24)");
if (fit_keepers < 2)
alert("squad", std::to_string(fit_keepers) + " fit goalkeeper(s) of " + std::to_string(keepers) + " - buy or loan one");
if (!absent.empty()) alert("lineup", "injured or banned in the starting eleven: " + list(absent));
if (!weak.empty()) alert("lineup", "starters in weak form: " + list(weak));
if (!expiring.empty()) alert("contracts", "contracts ending: " + list(expiring) + " - Open(Contracts), OpenNegotiation");
// advertising: expired contracts (renewal pending) and free places
const ui::AdvertisingState a = ui::advertising_from_game(g, slot, revision_);
int expired = 0, free_places = 0;
for (int s = 0; s < 16; ++s) {
if (a.offers[size_t(s)].status == bmh::AdvertisingOfferStatus::unsupported_extension) ++expired;
else if (!(s < 14 ? a.boards.at(size_t(s)) : s == 14 ? a.shirt : a.television).active) ++free_places;
}
if (expired) alert("advertising", std::to_string(expired) + " contract(s) ran out - ListAdOffers on the place renews or frees it");
if (free_places)
alert("advertising", std::to_string(free_places) + " free advertising place(s) - Open(Advertising), ListAdOffers, AcceptAdOffer");
// money: overdrawn, or beyond the credit line
const auto p = prep();
if (p.bank) {
const int64_t balance = p.bank->balance, credit = p.bank->credit_line;
if (balance < -credit)
alert("money", "the account (" + std::to_string(balance) + ") is beyond the credit line (" + std::to_string(credit) +
") - sell, cut wages or take a credit");
else if (balance < 0)
alert("money", "the account is overdrawn (" + std::to_string(balance) + "); interest is charged");
}
if (alerts == 0) emit('i', "advice: nothing urgent");
});
add({"*", "Scoreboard", {}, "all human managers: league, place, points, balance, strength of the best eleven", false},
[this](const Values&) {
if (!career_) fail("E_NOT_IN_WINDOW", "Scoreboard needs a running game");
const GameState& g = session_->state();
std::vector<std::vector<std::string>> rows;
for (size_t m = 0; m < g.manager_teams.size(); ++m) {
const int team = g.manager_teams[m];
if (team < 0 || squad_range(team).count == 0) {
rows.push_back({std::to_string(m + 1), "(national team)", "-", "-", "-", "-", "-", "-"});
continue;
}
const int league = team_league(team);
std::string league_name = "-", rank = "-", points = "-", games = "-";
if (league >= 0 && league < kLeagueCount) {
const ui::LeagueTableState t = ui::league_table_from_game(g, int(m), league);
league_name = t.league_name;
for (const auto& r : t.rows)
if (r.runtime_team_id == team)
rank = std::to_string(r.rank), points = std::to_string(r.points), games = std::to_string(r.games);
}
const size_t rec = m * 0xb0c;
const int32_t balance = int32_t(uint32_t(g.manager_records.at(rec + 0x314)) | uint32_t(g.manager_records.at(rec + 0x315)) << 8 |
uint32_t(g.manager_records.at(rec + 0x316)) << 16 | uint32_t(g.manager_records.at(rec + 0x317)) << 24);
// the strength of the best eleven (displayed strength, as the squad lists show it)
std::vector<int> strengths;
const SquadRange range = squad_range(team);
for (size_t s = range.first; s < range.first + range.count; ++s) {
const int id = g.squad_slots.at(s) & 0x0fff;
if (id != 0x0fff && size_t(id) < g.players.size()) strengths.push_back(g.players[size_t(id)].strength());
}
std::sort(strengths.rbegin(), strengths.rend());
int sum = 0, n = 0;
for (; n < 11 && n < int(strengths.size()); ++n) sum += strengths[size_t(n)];
rows.push_back({std::to_string(m + 1), utf8(g.club_name(team)), league_name, rank, points, games, std::to_string(balance),
n ? std::to_string(sum / n) : "-"});
}
emit_table({"Manager", "Club", "League", "Place", "Points", "Games", "Balance", "Best11"}, rows);
});
}
void Console::register_state_commands() {
add({"*", "State", {choice("view", kStateViews)}, "the full projection of a view as structured (JSON) data", false},
[this](const Values& v) {
if (!career_) fail("E_NOT_IN_WINDOW", "State needs a running game");
own_view_only(v.player, "State");
const std::string view = kStateViews[size_t(v.choice("view"))];
const int slot = active_slot();
Json data;
switch (v.choice("view")) {
case 0:
data = parse_json(ui::desk_json(desk()));
data.object()->insert_or_assign("engine_attached", true); // (ui::desk_json marks it false)
break;
case 1: {
const ui::DeskState d = desk();
data = parse_json(ui::league_table_json(ui::league_table_from_game(session_->state(), slot, d.league >= 0 ? d.league : 0)));
break;
}
case 2: data = lineup_record(prep().lineup); break;
case 3: data = mailbox_record(ui::mailbox_state_from_game(session_->state(), slot, revision_)); break;
case 4: {
const auto p = prep();
if (!p.bank) fail("E_MODE_LOCKED", "no bank here (national team?)");
data = parse_json(ui::bank_state_json(*p.bank));
break;
}
case 5: {
const auto p = prep();
if (!p.transfer_market) fail("E_MODE_LOCKED", "no transfer market here (national team?)");
data = parse_json(ui::transfer_market_state_json(*p.transfer_market));
break;
}
case 6: data = parse_json(ui::advertising_state_json(ui::advertising_from_game(session_->state(), slot, revision_))); break;
case 7: data = parse_json(ui::contracts_state_json(ui::contracts_from_game(session_->state(), slot, revision_))); break;
case 8: {
const auto p = prep();
if (!p.stadium) fail("E_MODE_LOCKED", "no stadium view (national team?)");
data = parse_json(ui::stadium_state_json(*p.stadium));
break;
}
case 9: {
const auto p = prep();
if (!p.toto) fail("E_MODE_LOCKED", "no Toto in this game");
data = parse_json(ui::toto_state_json(*p.toto));
break;
}
case 10: {
const auto p = prep();
if (!p.training) fail("E_MODE_LOCKED", "there is no training in mode I");
data = parse_json(ui::training_json(*p.training));
break;
}
default: {
const auto p = prep();
if (!p.training_camp) fail("E_MODE_LOCKED", "no training camp here");
data = parse_json(ui::training_camp_json(*p.training_camp));
break;
}
}
// text mode: the record after the label; --json: the same record as the line's data
if (options_.json) emit('i', "state " + view, std::move(data));
else emit('i', "state " + view + ": " + dump_json(data));
});
}
} // namespace bmh::cli::console
+194
View File
@@ -0,0 +1,194 @@
// SPDX-License-Identifier: GPL-3.0-only
// The league table and the fixtures window (docs/CLI_CONCEPT/05-information.md).
//
// LeagueTable reads the pure projection ui::league_table_from_game. Fixtures goes through the
// engine like the SDL app (CareerSession::open_league_pairings / dispatch_league_pairings):
// the original draws random numbers when the window opens and when it closes
// (pairings_runtime_draw, stir_random), so a console that only printed the schedule would
// leave the game on a different random sequence than the original.
#include "app/window_actions.hpp"
#include <algorithm>
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/schedule.hpp"
#include "ui/desk_state.hpp"
#include "ui/desktop.hpp"
#include "ui/league_table.hpp"
namespace bmh::cli::console {
using namespace detail;
void Console::register_table_commands() {
closers_["Fixtures"] = [this] { fixtures_action(LeaguePairingsAction::close); };
// ListLeagues is global (commands.csv "*"): the nine leagues with their number, as
// LeagueTable/Fixtures take them; during the manager selection the five start leagues.
add({"*", "ListLeagues", {}, "leagues with number and size", false}, [this](const Values&) {
std::vector<std::vector<std::string>> rows;
if (career_) {
for (int league = 0; league < kLeagueCount; ++league) {
const ui::LeagueTableState t = ui::league_table_from_game(session_->state(), active_slot(), league);
rows.push_back({std::to_string(league), t.league_name, std::to_string(t.rows.size())});
}
} else if (picker_) {
for (int league = 0; league < 5; ++league)
rows.push_back({std::to_string(league), utf8(picker_->group_label(league)),
std::to_string(picker_->group_last(league) - picker_->group_first(league) + 1)});
} else {
fail("E_RULE", "the leagues are known after NewGame(...)");
}
emit_table({"League", "Name", "Clubs"}, rows);
});
// --- LeagueTable ----------------------------------------------------------------------
add({"LeagueTable", "ShowTable", {integer("league", 0, kLeagueCount - 1, true)}, "the table (without league: the one shown)", false},
[this](const Values& v) {
if (v.has("league")) table_league_ = int(v.integer("league"));
show_league_table();
});
add({"LeagueTable", "SetLeague", {integer("league", 0, kLeagueCount - 1)}, "show another league", false}, [this](const Values& v) {
table_league_ = int(v.integer("league"));
show_league_table();
});
add({"LeagueTable", "OpenFixtures", {}, "the fixtures of this league", false}, [this](const Values&) { open_fixtures(); });
for (const char* name : {"ToggleEurope", "SetView", "SetCriteria", "SetRange", "SetPointsMode", "ComputerTip", "OpenStrengths"}) {
add({"LeagueTable", name, {}, "not in the console yet", false}, [name](const Values&) {
fail("E_ENGINE_GAP", std::string(name) + " of the league table is not in the console yet");
});
}
// --- Fixtures -------------------------------------------------------------------------
add({"Fixtures", "ShowFixtures", {integer("league", 0, kLeagueCount - 1, true), integer("matchday", 1, 38, true)},
"the page shown (optionally another league / matchday first)", false},
[this](const Values& v) {
if (v.has("league")) fixtures_action(LeaguePairingsAction::select_league, int(v.integer("league")));
if (v.has("matchday")) {
const int wanted = int(v.integer("matchday")) - 1;
for (int step = 0; step < 40 && pairings_ && pairings_->identity.round != wanted; ++step)
fixtures_action(LeaguePairingsAction::next);
if (pairings_ && pairings_->identity.round != wanted) fail("E_BAD_ARGUMENT", "the league has no such matchday");
}
if (!v.has("league") && !v.has("matchday")) show_fixtures();
});
add({"Fixtures", "SetLeague", {integer("league", 0, kLeagueCount - 1)}, "another league", false},
[this](const Values& v) { fixtures_action(LeaguePairingsAction::select_league, int(v.integer("league"))); });
add({"Fixtures", "SetMatchday", {integer("matchday", 1, 38)}, "go to a matchday", false}, [this](const Values& v) {
const int wanted = int(v.integer("matchday")) - 1;
// page through without printing every page on the way: only the target is shown
quiet_fixtures_ = true;
try {
for (int step = 0; step < 40 && pairings_ && pairings_->identity.round != wanted; ++step)
fixtures_action(LeaguePairingsAction::next);
} catch (...) {
quiet_fixtures_ = false;
throw;
}
quiet_fixtures_ = false;
if (pairings_ && pairings_->identity.round != wanted) fail("E_BAD_ARGUMENT", "the league has no such matchday");
if (pairings_) show_fixtures();
});
add({"Fixtures", "NextMatchday", {}, "the next matchday (arrow)", false},
[this](const Values&) { fixtures_action(LeaguePairingsAction::next); });
add({"Fixtures", "PreviousMatchday", {}, "the previous matchday (arrow)", false},
[this](const Values&) { fixtures_action(LeaguePairingsAction::previous); });
add({"Fixtures", "ShowPostponed", {}, "the postponed games", false},
[this](const Values&) { fixtures_action(LeaguePairingsAction::postponed_list); });
add({"Fixtures", "ComputerTip", {}, "the computer's forecast for this page", false},
[this](const Values&) { fixtures_action(LeaguePairingsAction::computer_tip); });
add({"Fixtures", "OpenTable", {}, "the league table", false}, [this](const Values&) {
// the table window is a pure projection; leaving the fixtures closes them first
const int league = pairings_ ? pairings_->identity.league : -1;
fixtures_action(LeaguePairingsAction::close);
open_window("LeagueTable");
table_league_ = league;
show_league_table();
});
for (const char* name : {"FindGame", "GamesOf", "Page", "OpenStrengths"}) {
add({"Fixtures", name, {}, "not in the console yet", false}, [name](const Values&) {
fail("E_ENGINE_GAP", std::string(name) + " of the fixtures is not in the console yet");
});
}
}
void Console::show_league_table() {
const ui::DeskState d = desk();
const int league = table_league_ >= 0 ? table_league_ : (d.league >= 0 ? d.league : 0);
table_league_ = league;
const ui::LeagueTableState table = ui::league_table_from_game(session_->state(), d.manager_slot, league);
emit('i', table.league_name + ", " + std::to_string(table.rounds_played) + " matchdays played");
std::vector<std::vector<std::string>> rows;
for (const auto& r : table.rows) {
std::string name = r.name;
for (size_t m = 0; m < d.manager_teams.size(); ++m)
if (d.manager_teams[m] == r.runtime_team_id) name += " [human:" + std::to_string(m + 1) + "]";
rows.push_back({std::to_string(r.rank), name, std::to_string(r.games), std::to_string(r.wins), std::to_string(r.draws),
std::to_string(r.losses), std::to_string(r.goals_for) + ":" + std::to_string(r.goals_against),
std::to_string(r.goals_for - r.goals_against), std::to_string(r.points)});
}
emit_table({"Rank", "Club", "G", "W", "D", "L", "Goals", "Diff", "Pts"}, rows);
}
void Console::open_fixtures() {
const ui::DeskState d = desk();
std::string error;
std::optional<ui::LeaguePairingsState> page;
try {
page = app::LeagueFamilyActions(*session_).open_pairings(d, revision_, error);
} catch (const std::exception& e) {
fail("E_INTERNAL", std::string("fixtures: ") + e.what());
}
if (!page) fail("E_RULE", std::string("fixtures cannot open") + (d.national_team ? " while you coach the national team" : "") + ": " + error);
pairings_ = std::move(page);
open_window("Fixtures");
show_fixtures();
}
void Console::show_fixtures() {
if (!pairings_) fail("E_INTERNAL", "no fixtures page");
const auto& p = *pairings_;
// the original pads its title parts for the screen layout
auto trim = [](std::string s) {
while (!s.empty() && s.front() == ' ') s.erase(0, 1);
while (!s.empty() && s.back() == ' ') s.pop_back();
return s;
};
std::string title = trim(utf8(p.title));
for (const std::string& part : {trim(utf8(p.subtitle)), trim(utf8(p.date))})
if (!part.empty()) title += ", " + part;
emit('i', title);
std::vector<std::vector<std::string>> rows;
for (const auto& r : p.rows) {
std::string result = utf8(r.result);
// the original note already names the leg ("2:2 Hinspiel", message LeaguePairings_FormatError_TextPointer13)
if (!r.first_leg.empty()) result += " (" + utf8(r.first_leg) + ")";
if (!r.scheduled_date.empty())
result += " " + utf8(r.scheduled_ordinal) + utf8(r.scheduled_date);
rows.push_back({utf8(r.names[0]), utf8(r.names[1]), result.empty() ? "-" : result});
}
emit_table({"Home", "Away", "Result"}, rows);
}
// One action in the fixtures window, applied by the engine on a staged copy; a rejected
// action leaves state and random generators as they were (as src/app/controller.cpp does).
void Console::fixtures_action(LeaguePairingsAction kind, int value) {
if (!pairings_) fail("E_INTERNAL", "the fixtures window is not open");
std::string error;
std::optional<app::CareerSession::LeaguePairingsDispatch> applied;
try {
applied = app::LeagueFamilyActions(*session_).pairings(pairings_->identity, kind, value, revision_, error);
} catch (const std::exception& e) {
fail("E_RULE", std::string("fixtures: ") + e.what());
}
if (!applied) fail("E_RULE", "fixtures: " + error);
if (applied->closed) {
pairings_.reset();
close_window();
emit('+', "fixtures closed");
return;
}
pairings_ = std::move(applied->page);
if (!quiet_fixtures_) show_fixtures();
}
} // namespace bmh::cli::console
+488
View File
@@ -0,0 +1,488 @@
// SPDX-License-Identifier: GPL-3.0-only
// The transfer market of docs/CLI_CONCEPT/06-verein.md 5 (menu 17): the market list, listing an
// own player for sale or loan, and the offer editor Transfer.Negotiate for a purchase or a loan.
//
// The engine calls are the SDL app's (src/app/controller.cpp serve_transfer_action /
// serve_transfer_offer): CareerSession::dispatch_transfer_market, open_transfer_offer and
// dispatch_transfer_offer through app::TransferActions. Request binding and rollback
// belong to that shared boundary, including aborted questions and acknowledgements. The
// original's notices (agreement, refusal) arrive through the sale hook and are printed as
// i lines after the call.
#include <algorithm>
#include "app/window_actions.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/desk_actions.hpp"
#include "game/human_buyer_sale.hpp"
#include "game/poach.hpp"
#include "game/schedule.hpp"
#include "ui/club_info.hpp"
#include "ui/desk_state.hpp"
#include "ui/league_table.hpp"
#include "ui/outgoing_transfer.hpp"
#include "ui/transfer_market.hpp"
namespace bmh::cli::console {
using namespace detail;
namespace {
// The editor of a market player is closed when his four bid places are taken by other clubs
// (OpenTransferEditor: editor_slot finds no free or own place; the original takes at most four bids).
// Agents read the old "this offer cannot be changed" as a fault (learning session B2-004/005).
constexpr const char* kNoBidSlot =
"four other clubs have bid for this player already - there is no room for another offer "
"(at most four bids per player); try another player or wait until he has decided";
constexpr int kPositionNames = 629; // positionGoalkeeperCaps "TOR", ABW, MIT, STU
const std::vector<std::string> kPositionKeys = {"TOR", "ABW", "MIT", "STU"};
// the ten editor fields in the order of OutgoingTransferField
const std::vector<std::string> kOfferFields = {"Fee", "Salary", "Years", "BonusGoal", "BonusPoints", "BonusAppearance",
"BonusChampion", "Bonus2to5", "Bonus6to10", "BonusAvoidRelegation"};
} // namespace
void Console::register_transfer_commands() {
auto market = [this] {
const auto p = prep();
if (!p.transfer_market) fail("E_MODE_LOCKED", "no transfer market here (national team?)");
return *p.transfer_market;
};
// the original's notices during a transfer call, printed after it
auto notices = std::make_shared<std::vector<std::string>>();
// The yes/no questions of a poaching offer (PresentManagerDialog: the selling manager, the DFB
// fee) come from inside the engine call. The console answers them from `answers`; an
// unanswered one is recorded in `pending` and stops the call (nothing is committed), the
// player is asked and the same call runs again with the answers so far.
struct Questions {
std::vector<bool> answers;
size_t next = 0;
std::optional<std::pair<int, std::string>> pending; // manager, text
};
auto questions = std::make_shared<Questions>();
auto hooks = [notices, questions] {
HumanBuyerSaleHooks h;
h.notice = [notices](const GameState&, const HumanBuyerSaleNotice& n) { notices->push_back(utf8(n.original_message)); };
h.confirm = [questions](const GameState&, int manager, const std::string& text) -> bool {
if (questions->next < questions->answers.size()) return questions->answers[questions->next++];
questions->pending = std::make_pair(manager, utf8(text));
throw std::runtime_error("question to player " + std::to_string(manager + 1));
};
return h;
};
auto flush_notices = [this, notices] {
for (const auto& n : *notices) emit('i', n);
notices->clear();
};
auto filter = std::make_shared<std::array<bool, 4>>(std::array<bool, 4>{true, true, true, true});
auto show_market = [this, market, filter](int page) {
const ui::TransferMarketState m = market();
std::vector<const ui::TransferMarketItem*> items;
for (const auto& item : m.items)
if (item.position >= 0 && item.position < 4 && (*filter)[size_t(item.position)]) items.push_back(&item);
constexpr size_t kPage = 20;
const size_t pages = std::max<size_t>(1, (items.size() + kPage - 1) / kPage);
if (page < 1 || size_t(page) > pages) fail("E_BAD_ARGUMENT", "the market has " + std::to_string(pages) + " pages");
std::vector<std::vector<std::string>> rows;
for (size_t i = (size_t(page) - 1) * kPage; i < items.size() && i < size_t(page) * kPage; ++i) {
const auto& it = *items[i];
std::string mark = it.own_listing ? "[own]" : it.own_bid_pending ? "[your bid]" : "";
rows.push_back({"id:" + std::to_string(it.player), utf8(it.name), text(kPositionNames + it.position), std::to_string(it.age),
std::to_string(it.strength), utf8(it.seller_name), money(it.asking_fee), std::to_string(it.offers), mark});
}
emit_table({"Id", "Player", "Pos", "Age", "Str", "Club", "Fee", "Offers", ""}, rows);
emit('i', "page " + std::to_string(page) + "/" + std::to_string(pages) + ", balance " + money(m.balance) + ", credit line " +
money(m.credit_line));
};
openers_[17] = [this, show_market] {
open_window("Transfer");
show_market(1);
};
add({"Transfer", "ShowMarket", {integer("page", 1, 100, true)}, "the offered players (20 per page)", false},
[show_market](const Values& v) { show_market(int(v.integer("page", 1))); });
Param positions = detail::text("positions");
positions.display = "positions:list(TOR,ABW,MIT,STU)|All";
add({"Transfer", "SetMarketFilter", {positions}, "ALLE / TOR / ABW / MIT / STU", false}, [this, filter, show_market](const Values& v) {
std::string list = v.text("positions");
if (lower(list) == "all") {
filter->fill(true);
} else {
// a single position (TOR) counts as the list [TOR]
if (list.size() >= 2 && list.front() == '[' && list.back() == ']') list = list.substr(1, list.size() - 2);
for (char& c : list) c = char(std::toupper(static_cast<unsigned char>(c)));
filter->fill(false);
size_t start = 0;
while (start <= list.size()) {
const size_t comma = list.find(',', start);
std::string item = list.substr(start, comma == std::string::npos ? std::string::npos : comma - start);
item.erase(0, item.find_first_not_of(' '));
item.erase(item.find_last_not_of(' ') + 1);
const auto it = std::find(kPositionKeys.begin(), kPositionKeys.end(), item);
if (it == kPositionKeys.end()) fail("E_BAD_ARGUMENT", "unknown position " + item);
(*filter)[size_t(it - kPositionKeys.begin())] = true;
if (comma == std::string::npos) break;
start = comma + 1;
}
}
show_market(1);
});
// own squad rows by id:/row:/name, market players by id:/name
auto squad_item = [market](const std::string& reference) {
const ui::TransferMarketState m = market();
std::vector<PlayerRef> refs;
for (const auto& s : m.squad) refs.push_back({s.row, s.player, utf8(s.name)});
return m.squad[resolve_player(reference, refs)];
};
auto market_item = [market](const std::string& reference) {
const ui::TransferMarketState m = market();
std::vector<PlayerRef> refs;
for (const auto& it : m.items) refs.push_back({it.list_entry, it.player, utf8(it.name)});
return m.items[resolve_player(reference, refs)];
};
auto list_player = [this, market, squad_item, hooks, flush_notices](const std::string& reference, bool loan) {
const ui::TransferMarketState m = market();
const ui::TransferMarketSquadItem item = squad_item(reference);
if (item.already_listed) fail("E_RULE", utf8(item.name) + " is already on the list");
const auto r = app::TransferActions::listing(m, item, loan);
std::string error;
std::optional<app::TransferActions::MarketDispatch> outcome;
try {
outcome = app::TransferActions(*session_).market(r, hooks(), revision_, error);
} catch (const std::exception& e) {
fail("E_INTERNAL", std::string("transfer: ") + e.what());
}
if (!outcome) {
require_engine(false, "transfer", error);
}
flush_notices();
emit('+', utf8(item.name) + (loan
? " steht auf der Transferliste; der Entleiher wählt 12 oder 24 Monate im Angebot"
: " is on the transfer list"));
};
Param player = detail::text("player");
player.display = "player:Player";
add({"Transfer", "SellPlayer", {player}, "VER-KAUFEN: put an own player on the list", true},
[list_player](const Values& v) { list_player(v.text("player"), false); });
add({"Transfer", "LoanOutPlayer", {player, integer("months", 12, 24, true)}, "VER-LEIHEN: offer an own player for loan", true},
[list_player](const Values& v) {
if (v.integer("months", 24) != 12 && v.integer("months", 24) != 24)
fail("E_BAD_ARGUMENT", "Leihangebote verwenden 12 oder 24 Monate");
list_player(v.text("player"), true);
});
// --- Transfer.Negotiate: the offer editor (06-verein 5.2) -----------------------------
auto show_offer = [this] {
if (!offer_editor_) fail("E_INTERNAL", "no offer editor");
const auto& e = *offer_editor_;
const auto& p = e.panel;
emit('i', utf8(p.player_name) + (p.seller_name.empty() ? std::string() : " (" + utf8(p.seller_name) + ")") + ", age " + std::to_string(p.age) + ", strength " +
std::to_string(p.strength) + (e.quote_loan ? ", loan" : ""));
std::vector<std::vector<std::string>> rows = {
{"demand", money(p.asking_fee), money(p.asking_monthly_salary), "-"},
{"quote", money(p.quoted_fee), money(p.quoted_monthly_salary), std::to_string(p.quoted_years)},
{"offer", money(e.fee), money(e.monthly_salary), std::to_string(e.duration_years)}};
emit_table({"", "Fee", "Monthly salary", "Years"}, rows);
std::vector<std::vector<std::string>> bonuses;
for (size_t i = 0; i < 7; ++i) bonuses.push_back({kOfferFields[3 + i], std::to_string(e.bonuses[i] * (i >= 3 ? 5 : 1))});
emit_table({"Bonus", "Percent"}, bonuses);
if (!e.editable) emit('i', kNoBidSlot);
};
auto offer_request = [this](ui::OutgoingTransferRequestKind kind, ui::OutgoingTransferField field, uint32_t value) {
return app::TransferActions::editor(*offer_editor_, kind, field, value);
};
auto dispatch_offer = [this, hooks, flush_notices](const ui::OutgoingTransferRequest& r,
const app::TransferOfferTeamInfoPresenter& team_info = {},
const app::TransferOfferPlayerInfoPresenter& player_info = {}) {
std::string error;
std::optional<app::CareerSession::TransferOfferEditorDispatch> result;
try {
result = loan_return_offer_active()
? dispatch_loan_return_offer(r, hooks(), error, team_info, player_info)
: app::TransferActions(*session_).offer(r, hooks(), revision_, error, team_info, player_info);
} catch (const std::exception& e) {
fail("E_INTERNAL", std::string("transfer offer: ") + e.what());
}
if (!result) {
require_engine(false, "transfer offer", error);
}
flush_notices();
return *result;
};
auto open_offer = [this, market, market_item, show_offer, dispatch_offer](
const std::string& reference, bool loan, int months = 24) {
const ui::TransferMarketState m = market();
if (loan && months != 12 && months != 24)
fail("E_BAD_ARGUMENT", "Leihangebote verwenden 12 oder 24 Monate");
if (loan && months == 12 && m.source_market_mode != 3)
fail("E_RULE", "Die Laufzeit kann nur im Original-Verhandlungsmodus III geändert werden");
const ui::TransferMarketItem item = market_item(reference);
if (item.own_listing) fail("E_RULE", "that is your own player");
const auto r = app::TransferActions::opening(m, item, loan);
std::string error;
std::optional<app::CareerSession::TransferOfferEditorDispatch> result;
try {
result = app::TransferActions(*session_).open_offer(r, revision_, error);
} catch (const std::exception& e) {
fail("E_INTERNAL", std::string("transfer offer: ") + e.what());
}
if (!result) {
require_engine(false, "transfer offer", error);
}
offer_editor_ = result->editor;
offer_submitted_ = false;
open_window("Transfer.Negotiate");
if (loan && offer_editor_->editable && offer_editor_->duration_years != months / 12) {
auto updated = *offer_editor_;
updated.duration_years = uint8_t(months / 12);
const auto action = app::TransferActions::editor(updated,
ui::OutgoingTransferRequestKind::quote_change,
ui::OutgoingTransferField::duration_years, uint32_t(months / 12));
offer_editor_ = dispatch_offer(action).editor;
}
show_offer();
};
add({"Transfer", "BuyPlayer", {player}, "VER-KAUFEN on a market player: the offer editor", true},
[open_offer](const Values& v) { open_offer(v.text("player"), false); });
add({"Transfer", "HirePlayer", {player, integer("months", 12, 24, true)}, "VER-LEIHEN on a market player: the loan offer", true},
[open_offer](const Values& v) { open_offer(v.text("player"), true, int(v.integer("months", 24))); });
add({"Transfer.Negotiate", "ShowNegotiation", {}, "demand, quote and your offer", false}, [show_offer](const Values&) { show_offer(); });
auto set_field = [this, offer_request, dispatch_offer, show_offer](int field, uint32_t value) {
if (!offer_editor_) fail("E_INTERNAL", "no offer editor");
if (!offer_editor_->editable) fail("E_RULE", kNoBidSlot);
// a refused value must not stay in the editor: every later request posts the whole row
// and the engine would reject it as differing from its single field event
const auto before = *offer_editor_;
auto& e = *offer_editor_;
// the screen stores the edited value, then asks for a fresh quote (LAB_0001bad7);
// bonuses 4-7 are entered in steps of five and stored divided by five
const auto f = static_cast<ui::OutgoingTransferField>(field);
if (field == 0) e.fee = value;
else if (field == 1) e.monthly_salary = value;
else if (field == 2) e.duration_years = uint8_t(value);
else e.bonuses[size_t(field - 3)] = uint8_t(field >= 6 ? value / 5 : value);
try {
auto result = dispatch_offer(offer_request(ui::OutgoingTransferRequestKind::quote_change, f, value));
offer_editor_ = result.editor;
} catch (...) {
offer_editor_ = before;
throw;
}
};
Param field = choice("field", kOfferFields);
add({"Transfer.Negotiate", "SetOfferField", {field, integer("value", 0, 100000000)}, "change one field (a fresh quote follows)", true},
[set_field, show_offer](const Values& v) {
set_field(v.choice("field"), uint32_t(v.integer("value")));
show_offer();
});
add({"Transfer.Negotiate", "SetOffer",
{integer("fee", 0, 100000000), integer("salary", 0, 10000000), integer("years", 1, 4), integer("bonusGoal", 0, 255),
integer("bonusPoints", 0, 255), integer("bonusAppearance", 0, 255), integer("bonusChampion", 0, 1275),
integer("bonus2to5", 0, 1275), integer("bonus6to10", 0, 1275), integer("bonusAvoidRelegation", 0, 1275)},
"all ten fields", true},
[set_field, show_offer](const Values& v) {
const char* names[10] = {"fee", "salary", "years", "bonusGoal", "bonusPoints", "bonusAppearance", "bonusChampion",
"bonus2to5", "bonus6to10", "bonusAvoidRelegation"};
for (int i = 0; i < 10; ++i) set_field(i, uint32_t(v.integer(names[i])));
show_offer();
});
// ANGEBOT; reruns itself when a poaching question was answered (see Questions)
auto submit = std::make_shared<std::function<void()>>();
*submit = [this, offer_request, dispatch_offer, questions, notices, self = std::weak_ptr<std::function<void()>>(submit)] {
if (!offer_editor_) fail("E_INTERNAL", "no offer editor");
if (!offer_editor_->editable) fail("E_RULE", kNoBidSlot);
questions->next = 0;
questions->pending.reset();
std::optional<app::CareerSession::TransferOfferEditorDispatch> answered;
try {
answered = dispatch_offer(offer_request(ui::OutgoingTransferRequestKind::submit, ui::OutgoingTransferField::fee,
offer_editor_->fee));
} catch (...) {
if (!questions->pending) throw;
notices->clear(); // the call was rolled back; its notices come again
const auto [manager, text] = *questions->pending;
const int previous = player_;
player_ = manager + 1;
ask(text, {"Yes", "No"}, "No", [this, questions, self, previous](const std::string& answer) {
player_ = previous;
questions->answers.push_back(answer == "Yes");
if (const auto again = self.lock()) (*again)();
});
return;
}
questions->answers.clear();
const auto& result = *answered;
// after a low offer the original keeps the editor open for a better one (the engine's
// owner stays); only a closed owner ends Transfer.Negotiate
if (result.editor.closed) {
offer_editor_.reset();
close_window();
} else {
offer_editor_ = result.editor;
}
const char* status = "submitted";
switch (result.action.status) {
case TransferActionStatus::accepted: status = "accepted: the player moves to your club"; break;
case TransferActionStatus::pending:
status = "pending: the player decides in one of the next weeks";
offer_submitted_ = true;
break;
case TransferActionStatus::rejected: status = "rejected"; break;
default: break;
}
emit('+', std::string("offer ") + status);
finish_loan_return_offer();
};
add({"Transfer.Negotiate", "SubmitOffer", {}, "ANGEBOT: hand in the offer", true}, [submit](const Values&) { (*submit)(); });
closers_["Transfer.Negotiate"] = [this, offer_request, dispatch_offer] {
// closing the editor (right button) ends the negotiation screen only: a bid already
// handed in stays on the list until the player decides (Handbuch S. 60)
if (offer_editor_) dispatch_offer(offer_request(ui::OutgoingTransferRequestKind::cancel, ui::OutgoingTransferField::fee, offer_editor_->fee));
offer_editor_.reset();
close_window();
emit('+', offer_submitted_ ? "negotiation closed; your offer stands until the player decides" : "offer cancelled");
offer_submitted_ = false;
finish_loan_return_offer();
};
// TEAM-INFO and SPIELER-INFO of the offer editor (OpenTransferEditor): modal screens the engine
// opens inside the editor event; the console prints them and closes them at once (the
// presenters return true), after which the editor is projected again.
add({"Transfer.Negotiate", "ShowTeamInfo", {}, "TEAM-INFO: your club's squad, as the editor shows it", false},
[this, offer_request, dispatch_offer](const Values&) {
if (!offer_editor_) fail("E_INTERNAL", "no offer editor");
auto presenter = [this](app::ClubModalServices& services, int club, const Image&) {
const ClubInfoEntry entry = services.enter_club(club);
const ui::ClubInfoProjection t = ui::club_info_from_game(services.state(), club, entry, exe_, texts_);
emit('i', utf8(t.original_club_name));
std::vector<std::vector<std::string>> rows;
for (const auto& p : t.players) {
if (p.player_id < 0) continue;
const auto& a = p.attributes;
rows.push_back({"id:" + std::to_string(p.player_id), utf8(p.original_name), text(kPositionNames + a.position()),
std::to_string(a.age()), std::to_string(a.strength())});
}
emit_table({"Id", "Player", "Pos", "Age", "Str"}, rows);
return true;
};
const auto result = dispatch_offer(
offer_request(ui::OutgoingTransferRequestKind::team_info, ui::OutgoingTransferField::fee, offer_editor_->fee), presenter);
offer_editor_ = result.editor;
});
add({"Transfer.Negotiate", "ShowPlayerInfo", {}, "SPIELER-INFO: the player's card with his market value", false},
[this, offer_request, dispatch_offer](const Values&) {
if (!offer_editor_) fail("E_INTERNAL", "no offer editor");
auto presenter = [this](app::ClubModalServices& services, const ClubPlayerDetailSelection& selection, const Image&) {
const ClubPlayerDetailRedraw card = services.redraw_player(selection);
const GameState& g = services.state();
const Player& p = g.players.at(size_t(selection.player_id));
emit_table({"Player", "Value"},
{{"name", utf8(g.player_name(selection.player_id))},
{"position", text(kPositionNames + p.position())},
{"age", std::to_string(p.age())},
{"condition", std::to_string(p.condition())},
{"technique", std::to_string(p.technique())},
{"form", std::to_string(p.form())},
{"strength", std::to_string(p.strength())},
{"marketValue", card.market_value ? money(*card.market_value) : "-"}});
return true;
};
const auto result = dispatch_offer(
offer_request(ui::OutgoingTransferRequestKind::player_info, ui::OutgoingTransferField::fee, offer_editor_->fee), {},
presenter);
offer_editor_ = result.editor;
});
// --- Transfer.Poach: ABWERBEN (06-verein 5.6, src/game/poach.hpp) ----------------------
add({"Transfer", "OpenPoach", {}, "ABWERBEN: pick a player of another club (Transfer.Poach)", false}, [this, market](const Values&) {
market();
open_window("Transfer.Poach");
emit('+', "poach: ListPoachClubs([league]), ListClubPlayers(club), PoachPlayer(player); " +
std::to_string(poach_attempts_left(session_->state(), active_slot())) + " attempts left this season");
});
add({"Transfer.Poach", "ListPoachClubs", {integer("league", 0, kLeagueCount - 1, true)}, "the clubs of a league (default: own)", false},
[this](const Values& v) {
const ui::DeskState d = desk();
const int league = v.has("league") ? int(v.integer("league")) : std::max(0, d.league);
const ui::LeagueTableState t = ui::league_table_from_game(session_->state(), d.manager_slot, league);
std::vector<std::vector<std::string>> rows;
for (const auto& r : t.rows)
if (r.runtime_team_id != d.runtime_club) rows.push_back({"club:" + std::to_string(r.runtime_team_id), r.name});
emit('i', t.league_name);
emit_table({"Club", "Name"}, rows);
});
// the squad of a club (runtime id, as ListPoachClubs prints it)
auto club_squad = [this](const std::string& reference) {
std::string number = lower(reference).rfind("club:", 0) == 0 ? reference.substr(5) : reference;
Arg a;
a.text = number;
const auto id = to_int(a);
if (!id || *id < 0 || *id >= 138) fail("E_BAD_ARGUMENT", "club is club:<n> (ListPoachClubs)");
return int(*id);
};
Param club = detail::text("club");
club.display = "club:Club";
add({"Transfer.Poach", "ListClubPlayers", {club}, "the players of the club", false}, [this, club_squad](const Values& v) {
const int team = club_squad(v.text("club"));
const GameState& g = session_->state();
const SquadRange range = squad_range(team);
std::vector<std::vector<std::string>> rows;
for (size_t s = range.first; s < range.first + range.count; ++s) {
const int p = g.squad_slots.at(s) & 0xfff;
if (p == 0xfff) continue;
const Player& pl = g.players.at(size_t(p));
rows.push_back({"id:" + std::to_string(p), utf8(g.player_name(p)), text(kPositionNames + pl.position()), std::to_string(pl.age()),
std::to_string(pl.strength(true))});
}
emit('i', utf8(g.club_name(team)));
emit_table({"Id", "Player", "Pos", "Age", "Str"}, rows);
});
add({"Transfer.Poach", "PoachPlayer", {player}, "the offer to a player of another club (decided at once)", true},
[this, show_offer](const Values& v) {
// id:<player> of ListClubPlayers: his slot in a club squad
const std::string reference = v.text("player");
Arg a;
a.text = lower(reference).rfind("id:", 0) == 0 ? reference.substr(3) : reference;
const auto id = to_int(a);
if (!id) fail("E_BAD_ARGUMENT", "player is id:<n> (ListClubPlayers)");
const GameState& g = session_->state();
int slot = -1;
for (size_t s = 0; s < 0xb70 && slot < 0; ++s)
if ((g.squad_slots.at(s) & 0xfff) == *id) slot = int(s);
if (slot < 0) fail("E_BAD_ARGUMENT", "no club player id:" + std::to_string(*id));
std::string error;
std::optional<app::CareerSession::PoachDispatch> result;
try {
result = app::TransferActions(*session_).poach(active_slot(), slot, revision_, error);
} catch (const std::exception& e) {
fail("E_INTERNAL", std::string("poach: ") + e.what());
}
if (!result) {
require_engine(false, "poach", error);
}
for (const auto& m : result->start.messages) emit('i', utf8(m));
switch (result->start.status) {
case PoachStatus::ready: break;
case PoachStatus::invalid: fail("E_RULE", "not a player of another club");
case PoachStatus::attempts_used: fail("E_RULE", "five poaching attempts this season");
case PoachStatus::transfer_ban: fail("E_RULE", "transfer ban");
default: fail("E_RULE", "the player cannot be poached");
}
offer_editor_ = result->editor->editor;
offer_submitted_ = false;
open_window("Transfer.Negotiate");
emit('+', "asking " + std::to_string(result->start.asking_percent) + " % of his value; SubmitOffer decides at once");
show_offer();
});
// the rest of the market (06-verein 5): later steps of stage 3 or engine gaps
for (const char* name : {"SetSquadView", "SetSquadSheet", "SetMarketVisible", "ShowPlayer", "OpenOffers", "OpenSearch",
"ShowTransferNews", "ShowTeamInfo"})
add({"Transfer", name, {}, "not in the console yet", false},
[name](const Values&) { fail("E_ENGINE_GAP", std::string(name) + " is not in the console yet"); });
}
} // namespace bmh::cli::console
+198
View File
@@ -0,0 +1,198 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "cli/json.hpp"
#include <charconv>
#include <limits>
namespace bmh::cli {
namespace {
void append_utf8(std::string& out, std::uint32_t cp) {
if (cp <= 0x7f) out += char(cp);
else if (cp <= 0x7ff) {
out += char(0xc0 | (cp >> 6)); out += char(0x80 | (cp & 0x3f));
} else if (cp <= 0xffff) {
out += char(0xe0 | (cp >> 12)); out += char(0x80 | ((cp >> 6) & 0x3f)); out += char(0x80 | (cp & 0x3f));
} else {
out += char(0xf0 | (cp >> 18)); out += char(0x80 | ((cp >> 12) & 0x3f));
out += char(0x80 | ((cp >> 6) & 0x3f)); out += char(0x80 | (cp & 0x3f));
}
}
class Parser {
public:
explicit Parser(std::string_view source) : source_(source) {}
Json parse() {
skip_space();
Json result = parse_value();
skip_space();
if (at_ != source_.size()) fail("trailing data");
return result;
}
private:
std::string_view source_;
std::size_t at_ = 0;
[[noreturn]] void fail(std::string_view message) const {
throw JsonError(std::string(message) + " at byte " + std::to_string(at_));
}
void skip_space() {
while (at_ < source_.size() && (source_[at_] == ' ' || source_[at_] == '\t' || source_[at_] == '\r' || source_[at_] == '\n')) ++at_;
}
bool take(char c) {
if (at_ < source_.size() && source_[at_] == c) { ++at_; return true; }
return false;
}
Json parse_value() {
if (at_ >= source_.size()) fail("expected value");
switch (source_[at_]) {
case '{': return parse_object();
case '[': return parse_array();
case '"': return Json(parse_string());
case 't': literal("true"); return Json(true);
case 'f': literal("false"); return Json(false);
case 'n': literal("null"); return Json(nullptr);
default: return Json(parse_integer());
}
}
void literal(std::string_view word) {
if (source_.substr(at_, word.size()) != word) fail("invalid literal");
at_ += word.size();
}
int hex_digit(char c) const {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
std::uint32_t hex4() {
if (source_.size() - at_ < 4) fail("short unicode escape");
std::uint32_t value = 0;
for (int i = 0; i < 4; ++i) {
const int digit = hex_digit(source_[at_++]);
if (digit < 0) fail("invalid unicode escape");
value = (value << 4) | std::uint32_t(digit);
}
return value;
}
std::string parse_string() {
if (!take('"')) fail("expected string");
std::string out;
while (at_ < source_.size()) {
const unsigned char c = static_cast<unsigned char>(source_[at_++]);
if (c == '"') return out;
if (c < 0x20) fail("control character in string");
if (c != '\\') { out += char(c); continue; }
if (at_ == source_.size()) fail("short escape");
const char escaped = source_[at_++];
switch (escaped) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'u': {
std::uint32_t cp = hex4();
if (cp >= 0xd800 && cp <= 0xdbff) {
if (source_.size() - at_ < 6 || source_[at_] != '\\' || source_[at_ + 1] != 'u') fail("missing low surrogate");
at_ += 2;
const std::uint32_t low = hex4();
if (low < 0xdc00 || low > 0xdfff) fail("invalid low surrogate");
cp = 0x10000 + ((cp - 0xd800) << 10) + (low - 0xdc00);
} else if (cp >= 0xdc00 && cp <= 0xdfff) fail("unexpected low surrogate");
append_utf8(out, cp);
break;
}
default: fail("invalid string escape");
}
}
fail("unterminated string");
}
std::int64_t parse_integer() {
const std::size_t start = at_;
take('-');
if (at_ == source_.size()) fail("invalid integer");
if (source_[at_] == '0') ++at_;
else {
if (source_[at_] < '1' || source_[at_] > '9') fail("expected integer");
while (at_ < source_.size() && source_[at_] >= '0' && source_[at_] <= '9') ++at_;
}
if (at_ < source_.size() && (source_[at_] == '.' || source_[at_] == 'e' || source_[at_] == 'E')) fail("only integer numbers are supported");
std::int64_t value{};
const auto result = std::from_chars(source_.data() + start, source_.data() + at_, value);
if (result.ec != std::errc{} || result.ptr != source_.data() + at_) fail("integer out of range");
return value;
}
Json parse_array() {
take('['); skip_space(); Json::Array values;
if (take(']')) return values;
for (;;) {
skip_space(); values.push_back(parse_value()); skip_space();
if (take(']')) return values;
if (!take(',')) fail("expected comma in array");
}
}
Json parse_object() {
take('{'); skip_space(); Json::Object values;
if (take('}')) return values;
for (;;) {
skip_space();
if (at_ >= source_.size() || source_[at_] != '"') fail("expected object key");
std::string key = parse_string(); skip_space();
if (!take(':')) fail("expected colon");
skip_space();
if (!values.emplace(std::move(key), parse_value()).second) fail("duplicate object key");
skip_space();
if (take('}')) return values;
if (!take(',')) fail("expected comma in object");
}
}
};
void quote(std::string& out, std::string_view value) {
static constexpr char hex[] = "0123456789abcdef";
out += '"';
for (unsigned char c : value) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) { out += "\\u00"; out += hex[c >> 4]; out += hex[c & 15]; }
else out += char(c);
}
}
out += '"';
}
void dump(std::string& out, const Json& json) {
if (std::holds_alternative<std::nullptr_t>(json.value)) out += "null";
else if (const auto* b = json.boolean()) out += *b ? "true" : "false";
else if (const auto* n = json.integer()) out += std::to_string(*n);
else if (const auto* s = json.string()) quote(out, *s);
else if (const auto* a = json.array()) {
out += '[';
bool first = true;
for (const auto& item : *a) { if (!first) out += ','; first = false; dump(out, item); }
out += ']';
} else {
out += '{'; bool first = true;
for (const auto& [key, item] : *json.object()) {
if (!first) out += ','; first = false; quote(out, key); out += ':'; dump(out, item);
}
out += '}';
}
}
} // namespace
Json parse_json(std::string_view source) { return Parser(source).parse(); }
std::string dump_json(const Json& value) { std::string out; dump(out, value); return out; }
} // namespace bmh::cli
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <cstdint>
#include <map>
#include <stdexcept>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
namespace bmh::cli {
struct Json {
using Array = std::vector<Json>;
using Object = std::map<std::string, Json, std::less<>>;
using Value = std::variant<std::nullptr_t, bool, std::int64_t, std::string, Array, Object>;
Value value = nullptr;
Json() = default;
Json(std::nullptr_t) : value(nullptr) {}
Json(bool v) : value(v) {}
Json(std::int64_t v) : value(v) {}
Json(int v) : value(std::int64_t(v)) {}
Json(std::string v) : value(std::move(v)) {}
Json(const char* v) : value(std::string(v)) {}
Json(Array v) : value(std::move(v)) {}
Json(Object v) : value(std::move(v)) {}
const Object* object() const { return std::get_if<Object>(&value); }
Object* object() { return std::get_if<Object>(&value); }
const Array* array() const { return std::get_if<Array>(&value); }
const std::string* string() const { return std::get_if<std::string>(&value); }
const std::int64_t* integer() const { return std::get_if<std::int64_t>(&value); }
const bool* boolean() const { return std::get_if<bool>(&value); }
};
class JsonError final : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
Json parse_json(std::string_view source);
std::string dump_json(const Json& value);
} // namespace bmh::cli
+769
View File
@@ -0,0 +1,769 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "cli/protocol.hpp"
#include "cli/console/console.hpp"
#include "cli/seat_hub.hpp"
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <cstdio>
#include <cstdlib>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <cctype>
#include <charconv>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <thread>
#include <vector>
#include "launch/archive.hpp"
#include "launch/game_data.hpp"
#include "version.hpp"
namespace {
using namespace bmh::cli;
using Object = Json::Object;
struct Arguments {
std::filesystem::path data, log, replay;
std::filesystem::path saves; // --saves: save directory of the console (default --data)
std::uint32_t seed = 1;
bool seed_set = false, json = false, help = false;
bool console = false; // --console: the console language of docs/CLI_CONCEPT
bool echo = false; // --echo: repeat each input line as "< line" (golden transcript format)
bool instant = false; // --time instant: matchdays run through (default stepped, 07-spieltag 3.2)
// --serve <dir>: the console session answers blocks dropped into a directory (agents);
// --send <dir>: hand one block to such a session and print its answer
std::filesystem::path serve, send;
int timeout_seconds = 300; // --timeout: how long --send waits for the answer
// --keep-going: a console replay reports differing blocks and goes on (re-checking a
// QA session after console texts changed)
bool keep_going = false;
int seats = 0; // --seats N: with --serve, one mailbox per human manager (several agents)
int listen_port = 0; // --listen <port>: the console on 127.0.0.1:<port> (front ends, stage 2.5)
// --resume <jsonl>: a --seats game starts by playing the blocks of an earlier session log
// again (seed, time mode and saves from its header) and goes on from there
std::filesystem::path resume;
};
std::uint32_t parse_seed(std::string_view value) {
int base = 10;
if (value.size() > 2 && value[0] == '0' && (value[1] == 'x' || value[1] == 'X')) { base = 16; value.remove_prefix(2); }
std::uint32_t seed{};
const auto result = std::from_chars(value.data(), value.data() + value.size(), seed, base);
if (result.ec != std::errc{} || result.ptr != value.data() + value.size()) throw std::runtime_error("invalid --seed");
return seed;
}
Arguments parse_args(int argc, char** argv) {
Arguments args;
const std::vector<std::string> argv8 = bmh::launch::utf8_arguments(argc, argv); // (names beyond the code page)
for (size_t i = 1; i < argv8.size(); ++i) {
const std::string_view arg(argv8[i]);
auto next = [&](std::string_view name) -> std::string {
if (i + 1 >= argv8.size()) throw std::runtime_error("missing value for " + std::string(name));
return argv8[++i];
};
if (arg == "--version") {
std::printf("OpenBMH console %s\n", bmh::kOpenBmhVersion);
std::exit(0);
}
if (arg == "--help" || arg == "-h") args.help = true;
else if (arg == "--data") args.data = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--seed") { args.seed = parse_seed(next(arg)); args.seed_set = true; }
else if (arg == "--text") args.json = false;
else if (arg == "--json") args.json = true;
else if (arg == "--log") args.log = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--replay") args.replay = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--console") args.console = true;
else if (arg == "--saves") args.saves = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--echo") args.echo = true;
else if (arg == "--keep-going") args.keep_going = true;
else if (arg == "--resume") args.resume = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--listen") {
args.listen_port = std::stoi(next(arg));
if (args.listen_port < 1 || args.listen_port > 65535) throw std::runtime_error("--listen is a port 1-65535");
}
else if (arg == "--seats") {
args.seats = std::stoi(next(arg));
if (args.seats < 1 || args.seats > 4) throw std::runtime_error("--seats is 1-4");
}
else if (arg == "--serve") args.serve = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--send") args.send = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--timeout") args.timeout_seconds = std::stoi(next(arg));
else if (arg == "--time") {
const std::string mode = next(arg);
if (mode != "stepped" && mode != "instant") throw std::runtime_error("--time is stepped or instant");
args.instant = mode == "instant";
}
else throw std::runtime_error("unknown argument: " + std::string(arg));
}
return args;
}
void print_usage() {
std::cout << "openbmh_cli --data <BMH directory> [--seed <n>] [--text|--json] [--log <jsonl>]\n"
"openbmh_cli --replay <jsonl> [--data <BMH directory>] [--text|--json]\n"
"openbmh_cli --console --data <BMH directory> [--saves <dir>] [--seed <n>] [--text|--json] [--echo]\n"
" [--log|--replay <jsonl> [--keep-going]] [--serve <dir> | --listen <port>] [--seats N]\n"
" --listen: the console on 127.0.0.1:<port>, line protocol (SEAT k with --seats; a block ends\n"
" with go., the answer with a line \".\"); --json gives structured lines, State(view) projections.\n"
" --seats N: one mailbox <dir>/seat<k> per manager; a request \"WaitTurn\" waits for k's turn.\n"
" --resume <jsonl>: with --seats, first play an earlier session log again, then go on.\n"
"openbmh_cli --send <dir> [--timeout <seconds>] (the block on stdin)\n"
" --serve: the session answers blocks dropped into <dir> (request-N.txt -> response-N.txt);\n"
" --send hands one block to it and prints the answer - for agents that work in steps.\n"
" console language (docs/CLI_CONCEPT): command lines, executed by a line \"go.\";\n"
" ListOptions shows what is possible, Help the reference, Quit ends.\n"
"Commands: help, new, load, save, status, desk, kickoff, camp.*, bank.*, stadium.*, toto.submit, quit\n"
"Text: new <master_club> <manager_name> [strength], load/save <path>, kickoff, status, desk, quit\n";
}
std::string command_line_response(const Json& response) {
if (const Json* help = response.object() ? [&]() -> const Json* {
const auto it = response.object()->find("help"); return it == response.object()->end() ? nullptr : &it->second;
}() : nullptr) {
std::string result = "Commands (JSON: one object per line):\n";
if (const auto* obj = help->object()) {
if (const auto it = obj->find("commands"); it != obj->end()) {
if (const auto* list = it->second.array()) for (const auto& command : *list) {
const auto c = command.object()->find("cmd");
const auto p = command.object()->find("params");
if (c != command.object()->end() && p != command.object()->end())
result += " " + *c->second.string() + " — " + *p->second.string() + "\n";
}
}
if (const auto it = obj->find("not_available"); it != obj->end()) {
result += "Unavailable until CareerSession adapters exist:";
if (const auto* list = it->second.array()) for (const auto& value : *list) result += " " + *value.string();
result += "\n";
}
}
return result;
}
return text_response(response);
}
Json protocol_error(std::string detail, std::uint64_t revision) {
return Json(Object{{"ok", false}, {"error", "invalid_request"}, {"detail", std::move(detail)},
{"revision", static_cast<std::int64_t>(revision)}});
}
int run_replay(Arguments args) {
std::ifstream input(args.replay);
if (!input) throw std::runtime_error("cannot_read_replay_log");
std::string line;
if (!std::getline(input, line)) throw std::runtime_error("empty_replay_log");
const Json header = parse_json(line);
if (!header.object()) throw std::runtime_error("invalid_replay_header");
const auto type = header.object()->find("type");
const auto data = header.object()->find("data");
const auto seed = header.object()->find("seed");
if (type == header.object()->end() || !type->second.string() || *type->second.string() != "openbmh_cli_log" ||
data == header.object()->end() || !data->second.string() || seed == header.object()->end() || !seed->second.integer())
throw std::runtime_error("invalid_replay_header");
const auto protocol_version = header.object()->find("protocol");
if (protocol_version == header.object()->end() || !protocol_version->second.integer() || *protocol_version->second.integer() != 1)
throw std::runtime_error("unsupported_replay_protocol");
if (args.data.empty()) args.data = bmh::launch::path_from_utf8(*data->second.string());
if (args.seed_set && args.seed != static_cast<std::uint32_t>(*seed->second.integer()))
throw std::runtime_error("replay_seed_mismatch");
args.seed = static_cast<std::uint32_t>(*seed->second.integer());
bmh::cli::Protocol protocol(args.data, args.seed);
std::size_t index = 0;
while (std::getline(input, line)) {
if (line.empty()) continue;
++index;
const Json record = parse_json(line);
if (!record.object()) throw std::runtime_error("invalid_replay_record:" + std::to_string(index));
const auto req = record.object()->find("request"), expected = record.object()->find("response");
if (req == record.object()->end() || expected == record.object()->end())
throw std::runtime_error("invalid_replay_record:" + std::to_string(index));
const Json actual = protocol.handle(req->second, true);
if (dump_json(actual) != dump_json(expected->second))
throw std::runtime_error("replay_mismatch_at_record:" + std::to_string(index));
std::cout << (args.json ? dump_json(actual) : command_line_response(actual)) << '\n';
const auto quit = actual.object()->find("quit");
if (quit != actual.object()->end() && quit->second.boolean() && *quit->second.boolean()) break;
}
return 0;
}
// --- console mode (docs/CLI_CONCEPT) ------------------------------------------------------
// Log format (JSONL): a header {"type":"openbmh_console_log","data","seed","json","time"}, then one
// entry per executed block {"input":[lines],"output":[lines]}; the first entry is the start
// output with no input. --replay feeds the inputs again (plus "go.") and stops at the first
// block whose output differs - the console draws no random numbers, so a replay is exact.
Json string_array(const std::vector<std::string>& lines) {
Json::Array a;
for (const auto& l : lines) a.emplace_back(l);
return Json(std::move(a));
}
std::vector<std::string> strings_of(const Json& value) {
std::vector<std::string> result;
if (const auto* a = value.array())
for (const auto& v : *a)
if (const auto* s = v.string()) result.push_back(*s);
return result;
}
bmh::cli::console::Options console_options(const Arguments& args) {
bmh::cli::console::Options o;
o.data = args.data;
o.save_directory = args.saves;
o.seed = args.seed;
o.json = args.json;
o.time = args.instant ? bmh::cli::console::TimeMode::instant : bmh::cli::console::TimeMode::stepped;
return o;
}
int run_console_replay(Arguments args) {
std::ifstream input(args.replay);
if (!input) throw std::runtime_error("cannot_read_replay_log");
std::string line;
if (!std::getline(input, line)) throw std::runtime_error("empty_replay_log");
const Json header = parse_json(line);
const auto* h = header.object();
if (!h || !h->count("type") || !h->at("type").string() || *h->at("type").string() != "openbmh_console_log")
throw std::runtime_error("invalid_replay_header");
if (args.data.empty()) args.data = bmh::launch::path_from_utf8(*h->at("data").string());
if (h->count("saves") && h->at("saves").string() && args.saves.empty()) args.saves = bmh::launch::path_from_utf8(*h->at("saves").string());
args.seed = static_cast<std::uint32_t>(*h->at("seed").integer());
args.json = h->count("json") && h->at("json").boolean() && *h->at("json").boolean();
// the time mode changes how far Kickoff runs; logs before the "time" field need --time
if (h->count("time") && h->at("time").string()) args.instant = *h->at("time").string() == "instant";
bmh::cli::console::Console console(console_options(args), [](const std::string& out) { std::cout << out << '\n'; });
console.start();
std::size_t index = 0, mismatches = 0;
while (std::getline(input, line)) {
if (line.empty()) continue;
const Json record = parse_json(line);
if (!record.object() || !record.object()->count("output")) throw std::runtime_error("invalid_replay_record:" + std::to_string(index));
const auto expected = strings_of(record.object()->at("output"));
if (index > 0) { // entry 0 is the start output
for (const auto& in : strings_of(record.object()->at("input"))) console.feed(in);
console.feed("go.");
}
if (console.last_output() != expected) {
if (!args.keep_going) throw std::runtime_error("replay_mismatch_at_block:" + std::to_string(index));
std::cerr << "openbmh_cli: block " << index << " differs\n";
++mismatches;
}
++index;
}
std::cerr << "openbmh_cli: replay " << (mismatches ? "done" : "ok") << ", " << index << " blocks, " << mismatches
<< " differ\n";
return mismatches ? 1 : 0;
}
int run_console(const Arguments& args) {
if (args.data.empty()) throw std::runtime_error("--data is required");
std::ofstream log;
if (!args.log.empty()) {
log.open(args.log, std::ios::binary | std::ios::trunc);
if (!log) throw std::runtime_error("cannot_open_log");
Object header{{"type", "openbmh_console_log"}, {"version", 1},
{"data", bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal())},
{"seed", static_cast<std::int64_t>(args.seed)}, {"json", args.json},
{"time", std::string(args.instant ? "instant" : "stepped")}};
if (!args.saves.empty()) header["saves"] = bmh::launch::path_to_utf8(std::filesystem::absolute(args.saves).lexically_normal());
log << dump_json(Json(std::move(header))) << '\n';
}
auto write_entry = [&](const bmh::cli::console::Console& c) {
if (!log.is_open()) return;
log << dump_json(Json(Object{{"input", string_array(c.last_block())}, {"output", string_array(c.last_output())}})) << '\n';
log.flush();
if (!log) throw std::runtime_error("log_write_failed");
};
bmh::cli::console::Console console(console_options(args), [](const std::string& out) { std::cout << out << '\n' << std::flush; });
console.start();
write_entry(console);
std::string line;
while (!console.ended() && std::getline(std::cin, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (args.echo) std::cout << "< " << line << '\n';
const bool executes = bmh::cli::console::classify_line(line) == bmh::cli::console::LineKind::go;
console.feed(line);
if (executes) write_entry(console);
}
return 0;
}
// --- the directory mailbox for agents (--serve / --send) ---------------------------------
// A session started with --serve keeps running; each block is a file request-N.txt (N = 1,
// 2, ...) whose lines are fed to the console (a final "go." is added when missing); the
// output lines go to response-N.txt, written under a temporary name and renamed, so a
// reader never sees half a file. response-0.txt holds the start output. The session ends
// with Quit or a file named "stop". --send writes the next request and waits for its
// response. Plain files work the same on Windows, Linux and macOS and need no port.
std::filesystem::path mailbox_file(const std::filesystem::path& dir, const char* kind, long n) {
return dir / (std::string(kind) + "-" + std::to_string(n) + ".txt");
}
void write_atomic(const std::filesystem::path& file, const std::vector<std::string>& lines) {
const std::filesystem::path temp = file.string() + ".tmp";
{
std::ofstream out(temp, std::ios::binary | std::ios::trunc);
for (const auto& l : lines) out << l << "\n";
if (!out) throw std::runtime_error("cannot write " + temp.string());
}
std::filesystem::rename(temp, file);
}
int run_console_serve(const Arguments& args) {
if (args.data.empty()) throw std::runtime_error("--data is required");
std::filesystem::create_directories(args.serve);
std::ofstream log;
if (!args.log.empty()) {
log.open(args.log, std::ios::binary | std::ios::trunc);
if (!log) throw std::runtime_error("cannot_open_log");
Object header{{"type", "openbmh_console_log"}, {"version", 1},
{"data", bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal())},
{"seed", static_cast<std::int64_t>(args.seed)}, {"json", args.json},
{"time", std::string(args.instant ? "instant" : "stepped")}};
if (!args.saves.empty()) header["saves"] = bmh::launch::path_to_utf8(std::filesystem::absolute(args.saves).lexically_normal());
log << dump_json(Json(std::move(header))) << '\n';
}
std::vector<std::string> out;
bmh::cli::console::Console console(console_options(args), [&out](const std::string& line) { out.push_back(line); });
console.start();
if (log.is_open())
log << dump_json(Json(Object{{"input", string_array(console.last_block())}, {"output", string_array(console.last_output())}})) << '\n' << std::flush;
write_atomic(mailbox_file(args.serve, "response", 0), out);
for (long n = 1; !console.ended();) {
std::error_code ec;
if (std::filesystem::exists(args.serve / "stop", ec)) break;
const auto request = mailbox_file(args.serve, "request", n);
if (!std::filesystem::exists(request, ec)) {
std::this_thread::sleep_for(std::chrono::milliseconds(20));
continue;
}
std::vector<std::string> lines;
{
std::ifstream in(request, std::ios::binary);
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
lines.push_back(line);
}
}
std::filesystem::remove(request, ec);
while (!lines.empty() && lines.back().find_first_not_of(" \t") == std::string::npos) lines.pop_back();
if (lines.empty() || bmh::cli::console::classify_line(lines.back()) != bmh::cli::console::LineKind::go) lines.push_back("go.");
out.clear();
for (const auto& l : lines) {
const bool executes = bmh::cli::console::classify_line(l) == bmh::cli::console::LineKind::go;
console.feed(l);
if (executes && log.is_open())
log << dump_json(Json(Object{{"input", string_array(console.last_block())}, {"output", string_array(console.last_output())}})) << '\n' << std::flush;
if (console.ended()) break;
}
write_atomic(mailbox_file(args.serve, "response", n), out);
++n;
}
return 0;
}
// --- several agents in one game (--serve <dir> --seats N) ---------------------------------
// Every human manager k gets a mailbox <dir>/seat<k> that works like the single one
// (request-N.txt -> response-N.txt, response-0.txt = start output). What a seat may do and
// what it sees (its own manager only, the meanwhile part, WaitTurn) is the seat hub's
// (src/cli/seat_hub.hpp), shared with --listen. The log holds the blocks as executed (with
// @k), so --replay plays the game again.
namespace {
std::vector<std::string> read_request(const std::filesystem::path& file) {
std::vector<std::string> lines;
{
std::ifstream in(file, std::ios::binary);
for (std::string line; std::getline(in, line);) {
if (!line.empty() && line.back() == '\r') line.pop_back();
lines.push_back(line);
}
}
std::error_code ec;
std::filesystem::remove(file, ec);
while (!lines.empty() && lines.back().find_first_not_of(" \t") == std::string::npos) lines.pop_back();
return lines;
}
std::string trimmed(const std::string& s) {
const size_t a = s.find_first_not_of(" \t");
if (a == std::string::npos) return {};
return s.substr(a, s.find_last_not_of(" \t") - a + 1);
}
} // namespace
// The session log of a hub game: the header, then every executed block (as --log).
std::function<void(const bmh::cli::console::Console&)> hub_log(std::ofstream& log, const Arguments& args) {
if (!args.log.empty()) {
log.open(args.log, std::ios::binary | std::ios::trunc);
if (!log) throw std::runtime_error("cannot_open_log");
Object header{{"type", "openbmh_console_log"}, {"version", 1},
{"data", bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal())},
{"seed", static_cast<std::int64_t>(args.seed)}, {"json", args.json},
{"time", std::string(args.instant ? "instant" : "stepped")}, {"seats", args.seats}};
if (!args.saves.empty()) header["saves"] = bmh::launch::path_to_utf8(std::filesystem::absolute(args.saves).lexically_normal());
log << dump_json(Json(std::move(header))) << '\n';
}
return [&log](const bmh::cli::console::Console& console) {
if (log.is_open())
log << dump_json(Json(Object{{"input", string_array(console.last_block())}, {"output", string_array(console.last_output())}}))
<< '\n' << std::flush;
};
}
// --serve <dir> --seats N: the seat hub (src/cli/seat_hub.hpp) behind one mailbox per seat.
int run_console_seats(Arguments args) {
// --resume: the earlier log's header decides seed, time mode and saves (as --replay)
std::ifstream resume;
if (!args.resume.empty()) {
resume.open(args.resume, std::ios::binary);
std::string line;
if (!resume || !std::getline(resume, line)) throw std::runtime_error("cannot_read_resume_log");
const Json header = parse_json(line);
const auto* h = header.object();
if (!h || !h->count("type") || !h->at("type").string() || *h->at("type").string() != "openbmh_console_log")
throw std::runtime_error("invalid_resume_header");
args.seed = static_cast<std::uint32_t>(*h->at("seed").integer());
if (h->count("time") && h->at("time").string()) args.instant = *h->at("time").string() == "instant";
if (h->count("saves") && h->at("saves").string() && args.saves.empty()) args.saves = bmh::launch::path_from_utf8(*h->at("saves").string());
if (args.resume == args.log) throw std::runtime_error("--resume and --log must be different files");
}
if (args.data.empty()) throw std::runtime_error("--data is required");
std::ofstream log;
bmh::cli::SeatHub hub(console_options(args), args.seats, hub_log(log, args));
if (resume.is_open()) {
std::size_t index = 0, differ = 0;
for (std::string line; std::getline(resume, line);) {
if (line.empty()) continue;
const Json record = parse_json(line);
if (!record.object() || !record.object()->count("output")) throw std::runtime_error("invalid_resume_record");
if (index++ == 0) continue; // the start output
if (!hub.replay(strings_of(record.object()->at("input")), strings_of(record.object()->at("output")))) ++differ;
}
std::cerr << "openbmh_cli: resumed " << index << " blocks, " << differ << " differ\n";
}
struct Seat {
std::filesystem::path dir;
long next = 1; // the request number expected next
long waiting = 0; // a held WaitTurn request (its number), 0 = none
};
std::vector<Seat> seats(size_t(args.seats));
for (size_t k = 0; k < seats.size(); ++k) {
seats[k].dir = args.serve / ("seat" + std::to_string(k + 1));
std::filesystem::create_directories(seats[k].dir);
write_atomic(mailbox_file(seats[k].dir, "response", 0), hub.start_output());
}
auto deliver = [&](int seat, long n, const std::vector<std::string>& lines) {
write_atomic(mailbox_file(seats[size_t(seat - 1)].dir, "response", n), lines);
std::error_code gone;
std::filesystem::remove(mailbox_file(seats[size_t(seat - 1)].dir, "request", n), gone); // (a held WaitTurn)
};
auto release = [&] {
for (auto& [seat, lines] : hub.release()) {
deliver(seat, seats[size_t(seat - 1)].waiting, lines);
seats[size_t(seat - 1)].waiting = 0;
}
};
std::error_code ec;
while (!hub.ended() && !std::filesystem::exists(args.serve / "stop", ec)) {
bool worked = false;
for (size_t k = 0; k < seats.size() && !hub.ended(); ++k) {
Seat& seat = seats[k];
if (seat.waiting) continue; // one request at a time per seat
const auto request = mailbox_file(seat.dir, "request", seat.next);
if (!std::filesystem::exists(request, ec)) continue;
worked = true;
const long n = seat.next++;
auto answer = hub.submit(int(k) + 1, read_request(request));
if (answer) {
deliver(int(k) + 1, n, *answer);
} else {
// the request file stays until the answer: --send numbers the next request
// after the highest request or response it finds
write_atomic(request, {"WaitTurn"});
seat.waiting = n;
}
release();
}
if (!worked) std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
release(); // the session is over: every held WaitTurn gets its answer
return 0;
}
// --- the socket access for front ends (--listen <port>, stage 2.5) -----------------------
// A TCP server on 127.0.0.1 (local connections only) in front of the seat hub. Line based,
// UTF-8, "\n" or "\r\n":
// - On connecting with --seats N the client names its manager: "SEAT <k>"; without --seats it
// is seat 1 at once. The server answers with the start output (Window/Player lines).
// - Every block of command lines up to "go." is executed; the answer is its output lines and
// then a line holding only "." (output lines are never just "."). With --json each output
// line is one JSON object (class, window, player, text, data - see State(view)).
// - A block holding only "WaitTurn" is answered when the seat is on turn (SeatHub).
// - A seat is one connection at a time; a client that goes away loses a held WaitTurn.
// The session ends with Quit; the log (--log) replays it like any other.
#ifdef _WIN32
using socket_t = SOCKET;
constexpr socket_t kNoSocket = INVALID_SOCKET;
void close_socket(socket_t s) { closesocket(s); }
#else
using socket_t = int;
constexpr socket_t kNoSocket = -1;
void close_socket(socket_t s) { close(s); }
#endif
int run_console_listen(const Arguments& args) {
if (args.data.empty()) throw std::runtime_error("--data is required");
#ifdef _WIN32
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) throw std::runtime_error("cannot start Winsock");
#endif
const int seat_count = args.seats > 0 ? args.seats : 1;
std::ofstream log;
Arguments hub_args = args;
hub_args.seats = seat_count;
bmh::cli::SeatHub hub(console_options(args), seat_count, hub_log(log, hub_args));
socket_t server = socket(AF_INET, SOCK_STREAM, 0);
if (server == kNoSocket) throw std::runtime_error("cannot open a socket");
int yes = 1;
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&yes), sizeof yes);
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_port = htons(static_cast<unsigned short>(args.listen_port));
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // local connections only
if (bind(server, reinterpret_cast<sockaddr*>(&address), sizeof address) != 0 || listen(server, 8) != 0)
throw std::runtime_error("cannot listen on 127.0.0.1:" + std::to_string(args.listen_port));
std::cerr << "openbmh_cli: listening on 127.0.0.1:" << args.listen_port << " (" << seat_count << " seat"
<< (seat_count > 1 ? "s" : "") << ")\n";
struct Client {
socket_t socket = kNoSocket;
std::string input; // received, not yet a full line
int seat = 0; // 0 = not seated yet
std::vector<std::string> block; // command lines up to "go."
bool held = false; // a WaitTurn is held for it
};
std::vector<Client> clients;
auto send_lines = [](Client& c, const std::vector<std::string>& lines) {
std::string text;
for (const auto& l : lines) text += l + "\n";
text += ".\n";
size_t sent = 0;
while (sent < text.size()) {
const int n = int(send(c.socket, text.data() + sent, int(text.size() - sent), 0));
if (n <= 0) return;
sent += size_t(n);
}
};
auto seat_taken = [&](int seat) {
for (const auto& c : clients) if (c.seat == seat) return true;
return false;
};
auto release = [&] {
for (auto& [seat, lines] : hub.release())
for (auto& c : clients)
if (c.seat == seat && c.held) {
send_lines(c, lines);
c.held = false;
}
};
auto on_line = [&](Client& c, std::string line) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (c.seat == 0) {
int seat = seat_count == 1 ? 1 : 0;
if (seat == 0 && line.rfind("SEAT ", 0) == 0) seat = std::atoi(line.c_str() + 5);
if (seat < 1 || seat > seat_count) {
send_lines(c, {"! E_BAD_ARGUMENT: first line SEAT <1-" + std::to_string(seat_count) + ">"});
return;
}
if (seat_taken(seat)) {
send_lines(c, {"! E_BAD_ARGUMENT: seat " + std::to_string(seat) + " is connected already"});
return;
}
c.seat = seat;
send_lines(c, hub.start_output());
return;
}
if (c.held) {
send_lines(c, {"! E_BAD_ARGUMENT: a WaitTurn is pending for this seat"});
return;
}
c.block.push_back(line);
if (bmh::cli::console::classify_line(line) != bmh::cli::console::LineKind::go) return;
auto answer = hub.submit(c.seat, std::move(c.block));
c.block.clear();
if (answer) send_lines(c, *answer);
else c.held = true;
release();
};
while (!hub.ended()) {
fd_set readable;
FD_ZERO(&readable);
FD_SET(server, &readable);
socket_t top = server;
for (const auto& c : clients) {
FD_SET(c.socket, &readable);
if (c.socket > top) top = c.socket;
}
timeval wait{0, 100000};
if (select(int(top + 1), &readable, nullptr, nullptr, &wait) < 0) break;
if (FD_ISSET(server, &readable)) {
const socket_t s = accept(server, nullptr, nullptr);
if (s != kNoSocket) {
clients.push_back(Client{s});
if (seat_count == 1 && !seat_taken(1)) { // one seat: no SEAT line needed
clients.back().seat = 1;
send_lines(clients.back(), hub.start_output());
} else if (seat_count == 1) {
send_lines(clients.back(), {"! E_BAD_ARGUMENT: seat 1 is connected already"});
}
}
}
for (size_t i = 0; i < clients.size() && !hub.ended();) {
Client& c = clients[i];
if (!FD_ISSET(c.socket, &readable)) { ++i; continue; }
char buffer[4096];
const int n = int(recv(c.socket, buffer, sizeof buffer, 0));
if (n <= 0) { // gone
if (c.held) hub.forget(c.seat);
close_socket(c.socket);
clients.erase(clients.begin() + std::ptrdiff_t(i));
continue;
}
c.input.append(buffer, size_t(n));
for (size_t nl; (nl = c.input.find('\n')) != std::string::npos;) {
std::string line = c.input.substr(0, nl);
c.input.erase(0, nl + 1);
on_line(c, std::move(line));
}
++i;
}
}
release(); // the session ended: held WaitTurns get their answer
for (auto& c : clients) close_socket(c.socket);
close_socket(server);
#ifdef _WIN32
WSACleanup();
#endif
return 0;
}
int run_send(const Arguments& args) {
// the next number: one above the highest request or response there
long n = 0;
std::error_code ec;
for (const auto& e : std::filesystem::directory_iterator(args.send, ec)) {
const std::string name = e.path().filename().string();
for (const char* prefix : {"request-", "response-"}) {
const std::string p = prefix;
if (name.rfind(p, 0) == 0 && name.size() > p.size() + 4 && name.compare(name.size() - 4, 4, ".txt") == 0)
n = std::max(n, std::atol(name.substr(p.size(), name.size() - p.size() - 4).c_str()));
}
}
if (ec) throw std::runtime_error("no session directory: " + args.send.string());
++n;
std::vector<std::string> lines;
for (std::string line; std::getline(std::cin, line);) lines.push_back(line);
write_atomic(mailbox_file(args.send, "request", n), lines);
const auto response = mailbox_file(args.send, "response", n);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(args.timeout_seconds);
while (!std::filesystem::exists(response, ec)) {
if (std::chrono::steady_clock::now() > deadline) {
std::cerr << "openbmh_cli: no answer from the session in " << args.timeout_seconds << " s\n";
return 3;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
std::ifstream in(response, std::ios::binary);
std::cout << in.rdbuf();
return 0;
}
} // namespace
int main(int argc, char** argv) {
try {
Arguments args = parse_args(argc, argv);
if (args.help) { print_usage(); return 0; }
if (!args.send.empty()) return run_send(args);
// --data may also name BMH.EXE or a ZIP/7z archive with one game (src/launch); an
// archive is unpacked into the per-user cache and its copy is used
if (!args.data.empty()) {
const auto game = bmh::launch::resolve_game(args.data, bmh::launch::default_cache_directory());
if (!game.error.empty() || !game.check.playable)
throw std::runtime_error("the game cannot be used:\n" + bmh::launch::describe(game));
args.data = game.check.directory;
}
if (args.console) {
if (!args.log.empty() && !args.replay.empty()) throw std::runtime_error("--log and --replay cannot be combined");
if (args.listen_port) return run_console_listen(args);
if (!args.serve.empty()) return args.seats > 0 ? run_console_seats(args) : run_console_serve(args);
return args.replay.empty() ? run_console(args) : run_console_replay(std::move(args));
}
if (!args.replay.empty()) {
if (!args.log.empty()) throw std::runtime_error("--log and --replay cannot be combined");
return run_replay(std::move(args));
}
if (args.data.empty()) throw std::runtime_error("--data is required unless --replay supplies it");
std::ofstream log;
if (!args.log.empty()) {
log.open(args.log, std::ios::binary | std::ios::trunc);
if (!log) throw std::runtime_error("cannot_open_log");
const auto abs_data = bmh::launch::path_to_utf8(std::filesystem::absolute(args.data).lexically_normal());
log << dump_json(Json(Object{{"type", "openbmh_cli_log"}, {"protocol", 1},
{"data", abs_data}, {"seed", static_cast<std::int64_t>(args.seed)}})) << '\n';
}
Protocol protocol(args.data, args.seed);
std::string line;
while (std::getline(std::cin, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
Json request;
Json response;
try {
request = args.json ? parse_json(line) : text_request(line, &protocol);
response = protocol.handle(request);
} catch (const std::exception& error) {
request = Json(Object{{"cmd", "__protocol_error"}, {"detail", error.what()}});
response = protocol_error(error.what(), protocol.revision());
}
if (log.is_open()) {
log << dump_json(Json(Object{{"request", request}, {"response", response}})) << '\n';
log.flush();
if (!log) throw std::runtime_error("log_write_failed");
}
std::cout << (args.json ? dump_json(response) : command_line_response(response)) << '\n';
if (const auto* object = response.object()) {
const auto it = object->find("quit");
if (it != object->end() && it->second.boolean() && *it->second.boolean()) break;
}
}
return 0;
} catch (const std::exception& error) {
std::cerr << "openbmh_cli: " << error.what() << '\n';
return 2;
}
}
+744
View File
@@ -0,0 +1,744 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "cli/protocol.hpp"
#include <algorithm>
#include <array>
#include <charconv>
#include <iomanip>
#include <limits>
#include <sstream>
#include <string_view>
#include "app/career_session.hpp"
#include "formats/m3d.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
#include "ui/bank.hpp"
#include "ui/desktop.hpp"
#include "ui/league_table.hpp"
#include "ui/manager.hpp"
#include "ui/mailbox_state.hpp"
#include "ui/stadium.hpp"
#include "ui/toto.hpp"
#include "ui/training.hpp"
#include "ui/training_camp.hpp"
#include "ui/tactics.hpp"
namespace bmh::cli {
namespace {
using Object = Json::Object;
using Array = Json::Array;
const Json* find(const Json& value, std::string_view key) {
const auto* object = value.object();
if (!object) return nullptr;
const auto it = object->find(key);
return it == object->end() ? nullptr : &it->second;
}
std::string string(const Json& value, std::string_view name) {
const auto* v = value.string();
if (!v) throw JsonError("field_must_be_string:" + std::string(name));
return *v;
}
std::int64_t integer(const Json& value, std::string_view name) {
const auto* v = value.integer();
if (!v) throw JsonError("field_must_be_integer:" + std::string(name));
return *v;
}
bool boolean(const Json& value, std::string_view name) {
const auto* v = value.boolean();
if (!v) throw JsonError("field_must_be_boolean:" + std::string(name));
return *v;
}
const Json& required(const Json& value, std::string_view key) {
const auto* found = find(value, key);
if (!found) throw JsonError("missing_field:" + std::string(key));
return *found;
}
std::int64_t optional_integer(const Json& value, std::string_view key, std::int64_t fallback) {
const auto* found = find(value, key);
return found ? integer(*found, key) : fallback;
}
std::string optional_string(const Json& value, std::string_view key, std::string fallback = {}) {
const auto* found = find(value, key);
return found ? string(*found, key) : std::move(fallback);
}
bool optional_boolean(const Json& value, std::string_view key, bool fallback) {
const auto* found = find(value, key);
return found ? boolean(*found, key) : fallback;
}
int bounded_int(std::int64_t value, std::string_view field, int low, int high) {
if (value < low || value > high) throw JsonError("out_of_range:" + std::string(field));
return static_cast<int>(value);
}
std::uint64_t bounded_u64(std::int64_t value, std::string_view field) {
if (value < 0) throw JsonError("out_of_range:" + std::string(field));
return static_cast<std::uint64_t>(value);
}
void check_keys(const Json& value, std::initializer_list<std::string_view> allowed) {
const auto* object = value.object();
if (!object) throw JsonError("request_must_be_object");
for (const auto& [key, unused] : *object) {
(void)unused;
if (std::find(allowed.begin(), allowed.end(), key) == allowed.end())
throw JsonError("unknown_field:" + key);
}
}
void check_command_keys(const Json& value, std::string_view cmd) {
std::vector<std::string_view> allowed;
if (cmd == "__protocol_error") allowed = {"cmd", "detail"};
else if (cmd == "new") allowed = {"cmd", "options", "managers"};
else if (cmd == "load") allowed = {"cmd", "path"};
else if (cmd == "save") allowed = {"cmd", "manager", "revision", "path", "overwrite"};
else if (cmd == "kickoff") allowed = {"cmd", "manager", "revision"};
else if (cmd == "table") allowed = {"cmd", "manager", "league"};
else if (cmd == "mail") allowed = {"cmd", "manager"};
else if (cmd == "tactics.set") allowed = {"cmd", "manager", "revision", "index", "value"};
else if (cmd == "training.initialize") allowed = {"cmd", "manager", "revision"};
else if (cmd == "training.type" || cmd == "training.area" || cmd == "training.auto")
allowed = {"cmd", "manager", "revision", "index", "value"};
else if (cmd == "training.intensity") allowed = {"cmd", "manager", "revision", "row", "value"};
else if (cmd == "training.focus") allowed = {"cmd", "manager", "revision", "row"};
else if (cmd == "camp.focus") allowed = {"cmd", "manager", "revision", "focus"};
else if (cmd == "camp.book") allowed = {"cmd", "manager", "revision", "resort"};
else if (cmd == "bank.deposit" || cmd == "bank.withdraw") allowed = {"cmd", "manager", "revision", "amount"};
else if (cmd == "bank.shares.buy" || cmd == "bank.shares.sell" || cmd == "bank.tip")
allowed = {"cmd", "manager", "revision", "asset", "count"};
else if (cmd == "bank.fund.buy" || cmd == "bank.fund.sell")
allowed = {"cmd", "manager", "revision", "asset", "count"};
else if (cmd == "stadium.open") allowed = {"cmd", "manager", "revision"};
else if (cmd == "stadium.offer") allowed = {"cmd", "manager", "revision", "object"};
else if (cmd == "stadium.build" || cmd == "stadium.decline")
allowed = {"cmd", "manager", "revision", "object", "price"};
else if (cmd == "toto.submit") allowed = {"cmd", "manager", "revision", "stake", "tips"};
else allowed = {"cmd"};
const auto* object = value.object();
for (const auto& [key, unused] : *object) {
(void)unused;
if (std::find(allowed.begin(), allowed.end(), key) == allowed.end())
throw JsonError("unknown_field_for_command:" + key);
}
}
Json raw_json(std::string value) { return parse_json(value); }
Json failed(std::string code, std::uint64_t revision, std::string detail = {}) {
Object out{{"ok", false}, {"error", std::move(code)}, {"revision", Json(static_cast<std::int64_t>(revision))}};
if (!detail.empty()) out.emplace("detail", std::move(detail));
return out;
}
Json successful(std::uint64_t revision, Object extra = {}) {
extra.emplace("ok", true);
extra.emplace("revision", Json(static_cast<std::int64_t>(revision)));
return extra;
}
Json state_response(const ui::DeskState& desk, std::string_view view, Json state) {
return Object{{"view", std::string(view)}, {"state", std::move(state)}};
}
Json tactics_state(const ui::TacticsState& state) {
Array values, depth, lane;
for (auto value : state.values) values.emplace_back(int(value));
for (auto value : state.depth) depth.emplace_back(int(value));
for (auto value : state.lane) lane.emplace_back(int(value));
return Object{{"manager_slot", state.manager_slot}, {"runtime_club", state.runtime_club},
{"revision", static_cast<std::int64_t>(state.revision)}, {"source", state.source},
{"club_name", ui::original_to_utf8(state.club_name)},
{"assistant_attitude", int(state.assistant_attitude)}, {"live_scene_option", state.live_scene_option},
{"values", std::move(values)}, {"depth", std::move(depth)}, {"lane", std::move(lane)}};
}
// The desk projection as JSON. ui::desk_json marks it "engine_attached":false (the SDL flow
// sets the flag once a career is attached); every protocol desk comes from the engine.
Json desk_state_json(const ui::DeskState& desk) {
Json result = raw_json(ui::desk_json(desk));
result.object()->insert_or_assign("engine_attached", true);
return result;
}
Json training_state(const ui::TrainingState& state) {
Json result = raw_json(ui::training_json(state));
result.object()->insert_or_assign("engine_attached", true);
return result;
}
Json result_state(const app::CareerSession& session) {
const auto& results = session.completed_matchday_results();
if (!results) return Object{{"valid", false}, {"groups", Array{}}};
Array groups;
for (const auto& group : results->groups) {
Array matches;
for (const auto& match : group.matches) {
const char* status = "unknown";
switch (match.status) {
case ui::MatchResultStatus::played: status = "played"; break;
case ui::MatchResultStatus::postponed: status = "postponed"; break;
case ui::MatchResultStatus::not_played: status = "not_played"; break;
case ui::MatchResultStatus::unknown: break;
}
Object entry{{"home", match.home}, {"away", match.away}, {"status", status},
{"home_goals", match.home_goals ? Json(*match.home_goals) : Json(nullptr)},
{"away_goals", match.away_goals ? Json(*match.away_goals) : Json(nullptr)}};
// cup: "regular", "extra_time" or "penalties" (the score then includes the shoot-out)
if (group.cup) entry["decided"] = std::string(match.decided == 2 ? "penalties" : match.decided == 1 ? "extra_time" : "regular");
matches.emplace_back(std::move(entry));
}
Object g{{"competition", group.competition}, {"cup", group.cup}, {"matches", std::move(matches)}};
if (group.league_id) g["league_id"] = *group.league_id;
if (group.cup_id) g["cup_id"] = *group.cup_id;
groups.emplace_back(std::move(g));
}
return Object{{"valid", true}, {"date", static_cast<std::int64_t>(results->date)},
{"date_label", results->date_label}, {"calendar_entry", int(results->calendar_entry)},
// CurrentMatchday: a random number drawn per matchday (draw_matchday_number), not the
// matchday of a league (issue #6) - hence its own name
{"matchday_draw", int(results->matchday)}, {"groups", std::move(groups)}};
}
Json mailbox_state_json(const ui::MailboxState& state) {
Array messages;
for (const auto& message : state.messages) {
Array recipients;
for (int manager : message.recipient_managers) recipients.emplace_back(manager);
messages.emplace_back(Object{{"slot_snapshot_id", int(message.entry_index)},
{"recipient_mask", static_cast<std::int64_t>(message.recipient_mask)},
{"keep_mask", static_cast<std::int64_t>(message.kept_by_mask)},
{"recipient_managers", std::move(recipients)},
{"general_broadcast", message.general_broadcast},
{"kept_for_manager", message.kept_for_manager},
{"date_counter", int(message.date_counter)}, {"kind", "unclassified"}, {"text", message.text}});
}
return Object{{"manager_slot", state.manager_slot}, {"messages", std::move(messages)}};
}
Json league_table_state(const app::CareerSession& session, int manager, int league) {
const auto table = bmh::compute_league_table(session.state(), league, 0,
bmh::league_matchdays(league), 7, 1);
std::array<int, 20> order{};
for (int club = 0; club < table.size; ++club) order[club] = club;
std::sort(order.begin(), order.begin() + table.size, [&](int lhs, int rhs) {
return table.rank(lhs) < table.rank(rhs);
});
Array rows;
const int first_team = bmh::league_first_team(league);
for (int index = 0; index < table.size; ++index) {
const int club = order[index];
const int runtime_team = first_team + club;
const int games = table.games(club);
const int draws = games - table.wins[club] - table.defeats[club];
rows.emplace_back(Object{{"rank", table.rank(club) + 1},
{"club_identity_key", session.state().club_ids[runtime_team]}, {"runtime_team_id", runtime_team},
{"name", ui::original_to_utf8(session.state().club_name(runtime_team))},
{"games", games}, {"wins", table.wins[club]}, {"draws", draws},
{"losses", table.defeats[club]}, {"goals_for", table.goals_for[club]},
{"goals_against", table.goals_against[club]},
{"goal_difference", int(table.goals_for[club]) - int(table.goals_against[club])},
{"points", int(table.points[club])}, {"previous_rank", table.previous_rank(club) + 1}});
}
return Object{{"manager_slot", manager}, {"league_id", league},
// the original league name path of the table screen (issue #5: not TEXTD Prediction_TablePrediction_TextPointer + 4n,
// which starts one entry early with a referee text)
{"league_name", ui::league_table_from_game(session.state(), manager, league).league_name},
{"points_mode", 1},
{"rows", std::move(rows)}};
}
void put_envelope(const Json& request, int& manager, std::uint64_t& revision) {
manager = bounded_int(integer(required(request, "manager"), "manager"), "manager", 0, 3);
revision = bounded_u64(integer(required(request, "revision"), "revision"), "revision");
}
std::string command_name(const Json& request) {
return string(required(request, "cmd"), "cmd");
}
ui::DeskState current_desk(app::CareerSession& session, std::uint64_t revision) {
return session.desktop_projection(revision);
}
Object completed_status(const app::CareerSession& session, std::uint64_t revision) {
const auto& state = session.state();
return {{"phase", "career_complete"}, {"active", false},
{"revision", static_cast<std::int64_t>(revision)},
{"date", static_cast<std::int64_t>(state.date)}, {"season", state.season},
{"duration", int(state.memory.u8(::bmh::layout::CareerDuration))}};
}
Json action_state(app::CareerSession& session, std::uint64_t revision,
std::string_view family, int manager) {
const auto prep = session.preparation_projection(revision);
if (family == "bank" && prep.bank) return state_response(prep.desktop, family, raw_json(ui::bank_state_json(*prep.bank)));
if (family == "camp" && prep.training_camp) return state_response(prep.desktop, family, raw_json(ui::training_camp_json(*prep.training_camp)));
if (family == "stadium" && prep.stadium) return state_response(prep.desktop, family, raw_json(ui::stadium_state_json(*prep.stadium)));
if (family == "toto" && prep.toto) return state_response(prep.desktop, family, raw_json(ui::toto_state_json(*prep.toto)));
(void)manager;
return state_response(prep.desktop, "desk", desk_state_json(prep.desktop));
}
ui::SetupOptions parse_options(const Json& value) {
check_keys(value, {"duration", "difficulty", "managers", "mode", "league", "world"});
ui::SetupOptions options;
options.duration = bounded_int(optional_integer(value, "duration", options.duration), "duration", 0, 5);
options.difficulty = bounded_int(optional_integer(value, "difficulty", options.difficulty), "difficulty", 0, 9);
options.managers = bounded_int(optional_integer(value, "managers", 1), "managers", 1, 1);
options.mode = bounded_int(optional_integer(value, "mode", options.mode), "mode", 0, 3);
options.league = optional_boolean(value, "league", options.league);
options.world = optional_boolean(value, "world", options.world);
return options;
}
ui::ManagerChoice parse_manager(const Json& value) {
check_keys(value, {"name", "master_club", "start_league", "strength", "portrait"});
ui::ManagerChoice choice;
choice.slot = 0;
choice.name = ui::utf8_to_original(string(required(value, "name"), "name"));
if (choice.name.empty() || choice.name.size() > 0x19) throw JsonError("invalid_manager_name_length");
choice.master_club = bounded_int(integer(required(value, "master_club"), "master_club"), "master_club", 0, 4095);
choice.start_league = bounded_int(optional_integer(value, "start_league", 0), "start_league", 0, 4);
choice.strength = bounded_int(optional_integer(value, "strength", 1), "strength", 0, 2);
choice.portrait = bounded_int(optional_integer(value, "portrait", 0), "portrait", 0, 11);
return choice;
}
} // namespace
Protocol::Protocol(std::filesystem::path data, std::uint32_t seed)
: data_(std::move(data)), seed_(seed) {}
Protocol::~Protocol() = default;
bool Protocol::active() const noexcept { return session_ && !session_->career_complete(); }
Json Protocol::help() {
return Object{
{"protocol", 1},
{"commands", Array{
Object{{"cmd", "new"}, {"params", "options:{duration,difficulty,mode,league,world,managers:1}; managers:[{name,master_club,start_league?,strength?,portrait?}]"}},
Object{{"cmd", "load"}, {"params", "path"}},
Object{{"cmd", "save"}, {"params", "manager,revision,path,overwrite?"}},
Object{{"cmd", "status"}, {"params", "none"}},
Object{{"cmd", "desk"}, {"params", "none"}},
Object{{"cmd", "kickoff"}, {"params", "manager,revision"}},
Object{{"cmd", "results|tactics"}, {"params", "none"}},
Object{{"cmd", "mail"}, {"params", "manager:0..3 (required; read-only owned mailbox projection)"}},
Object{{"cmd", "table"}, {"params", "manager,league:0..8 (read-only; current league text and game point rule)"}},
Object{{"cmd", "tactics.set"}, {"params", "manager,revision,index:0..7,value (original table range)"}},
Object{{"cmd", "training"}, {"params", "none (read-only current training projection)"}},
Object{{"cmd", "training.initialize"}, {"params", "manager,revision"}},
Object{{"cmd", "training.type"}, {"params", "manager,revision,index:0..3,value:1..3"}},
Object{{"cmd", "training.area"}, {"params", "manager,revision,index:0..8,value:1..3"}},
Object{{"cmd", "training.intensity"}, {"params", "manager,revision,row,value:1..3"}},
Object{{"cmd", "training.focus"}, {"params", "manager,revision,row (cycle focus)"}},
Object{{"cmd", "training.auto"}, {"params", "manager,revision,index:0..4,value:0|1"}},
Object{{"cmd", "camp.focus"}, {"params", "manager,revision,focus:[4 values]"}},
Object{{"cmd", "camp.book"}, {"params", "manager,revision,resort:0..7"}},
Object{{"cmd", "bank.deposit|bank.withdraw"}, {"params", "manager,revision,amount"}},
Object{{"cmd", "bank.shares.buy|bank.shares.sell|bank.tip"}, {"params", "manager,revision,asset,count?"}},
Object{{"cmd", "bank.fund.buy|bank.fund.sell"}, {"params", "manager,revision,asset,count"}},
Object{{"cmd", "stadium.open|stadium.offer|stadium.build"}, {"params", "manager,revision,object?,price?"}},
Object{{"cmd", "toto.submit"}, {"params", "manager,revision,stake,tips:[11 values]"}},
Object{{"cmd", "quit"}, {"params", "none"}},
}},
{"not_available", Array{"squad", "player", "calendar", "finances", "lineup.auto", "match.start", "match.step", "match.sub", "match.tactics", "match.finish"}},
{"note", "Unavailable commands are rejected: CareerSession has no matching projection or dispatch API yet."}
};
}
Json Protocol::handle(const Json& request, bool replay) {
try {
check_keys(request, {"cmd", "detail", "manager", "revision", "league", "path", "overwrite", "options", "managers", "amount", "asset", "count", "focus", "resort", "object", "price", "stake", "tips", "index", "value", "row"});
const std::string cmd = command_name(request);
check_command_keys(request, cmd);
if (cmd == "__protocol_error")
return failed("invalid_request", revision_, optional_string(request, "detail", "invalid protocol input"));
if (cmd == "help") return successful(revision_, {{"help", help()}});
if (cmd == "quit") return successful(revision_, {{"quit", true}});
if (cmd == "new") {
if (active()) return failed("career_already_active", revision_);
const auto options_value = find(request, "options") ? *find(request, "options") : Json(Object{});
const auto options = parse_options(options_value);
const Json& managers_value = required(request, "managers");
const auto* managers = managers_value.array();
if (!managers || managers->size() != 1) return failed("stage1_requires_one_manager", revision_);
const auto choice = parse_manager(managers->front());
const auto database = load_database(data_ / "M3D.MAN");
if (choice.master_club >= int(database.club_names.size()))
return failed("invalid_master_club", revision_);
auto candidate = std::make_unique<app::CareerSession>(data_, seed_);
std::string error;
if (!candidate->confirm_manager(options, choice, error)) return failed(error.empty() ? "manager_rejected" : error, revision_);
ui::CareerInitializationResult init;
if (!candidate->finish(init, error)) return failed(error.empty() ? "career_start_failed" : error, revision_);
revision_ = init.desktop.revision;
session_ = std::move(candidate);
return successful(revision_, {{"events", Array{Json(Object{{"event", "career_started"}, {"manager", 0}})}},
{"state", desk_state_json(init.desktop)}});
}
if (cmd == "load") {
const std::filesystem::path path(string(required(request, "path"), "path"));
auto candidate = std::make_unique<app::CareerSession>(data_, seed_, path);
const std::uint64_t next_revision = revision_ + 1;
auto desk = candidate->desktop_projection(next_revision);
session_ = std::move(candidate);
revision_ = next_revision;
return successful(revision_, {{"events", Array{Json(Object{{"event", "career_loaded"}})}},
{"state", desk_state_json(desk)}});
}
// Source's terminal career has no following desk. Keep its owned state
// available for status; reject career commands before any projection,
// envelope parsing, file write or dispatch can occur.
if (session_ && session_->career_complete()) {
if (cmd == "status")
return successful(revision_, {{"status", completed_status(*session_, revision_)}});
return failed("career_complete", revision_);
}
if (cmd == "status" || cmd == "desk") {
if (!session_) return failed("no_active_career", revision_);
const auto desk = current_desk(*session_, revision_);
Object status{{"manager", desk.manager_slot}, {"revision", static_cast<std::int64_t>(revision_)},
{"day", desk.date.day}, {"month", desk.date.month}, {"year", desk.date.year},
{"club", ui::original_to_utf8(desk.club_name)}, {"balance", desk.balance}, {"runtime_club", desk.runtime_club},
{"source", desk.source}};
return successful(revision_, {{"state", desk_state_json(desk)}, {"status", Json(std::move(status))}});
}
if (cmd == "results" || cmd == "tactics") {
if (!session_) return failed("no_active_career", revision_);
return successful(revision_, {{"state", cmd == "results" ? result_state(*session_) :
tactics_state(session_->preparation_projection(revision_).tactics)}});
}
if (cmd == "mail") {
if (!session_) return failed("no_active_career", revision_);
const int manager = bounded_int(integer(required(request, "manager"), "manager"), "manager", 0, 3);
if (size_t(manager) >= session_->state().manager_teams.size())
return failed("invalid_manager_slot", revision_);
const auto state = ui::mailbox_state_from_game(session_->state(), manager);
return successful(revision_, {{"state", mailbox_state_json(state)}});
}
if (cmd == "table") {
if (!session_) return failed("no_active_career", revision_);
const int manager = bounded_int(integer(required(request, "manager"), "manager"), "manager", 0, 3);
const auto raw_league = integer(required(request, "league"), "league");
if (raw_league < 0 || raw_league >= bmh::kLeagueCount)
return failed("invalid_league", revision_);
const auto desk = current_desk(*session_, revision_);
if (manager != desk.manager_slot) return failed("stale_manager_or_revision", revision_);
return successful(revision_, {{"state", league_table_state(*session_, manager, int(raw_league))}});
}
if (cmd == "training") {
if (!session_) return failed("no_active_career", revision_);
const auto prep = session_->preparation_projection(revision_);
if (!prep.training) return failed("training_projection_unavailable", revision_);
return successful(revision_, {{"state", training_state(*prep.training)}});
}
if (cmd == "training.initialize" || cmd == "training.type" || cmd == "training.area" ||
cmd == "training.intensity" || cmd == "training.focus" || cmd == "training.auto") {
if (!session_) return failed("no_active_career", revision_);
int manager = -1;
std::uint64_t request_revision = 0;
put_envelope(request, manager, request_revision);
const auto prep = session_->preparation_projection(revision_);
if (!prep.training) return failed("training_projection_unavailable", revision_);
const auto& current = *prep.training;
if (request_revision != revision_ || manager != current.manager_slot)
return failed("stale_manager_or_revision", revision_);
ui::TrainingRequest action;
action.manager_slot = current.manager_slot;
action.runtime_club = current.runtime_club;
action.revision = request_revision;
action.desired_types = current.types;
action.desired_areas = current.areas;
action.desired_automation = current.automation;
if (cmd == "training.initialize") {
action.kind = ui::TrainingRequestKind::initialize;
action.desired_automation = 0x9f;
} else if (cmd == "training.type") {
action.kind = ui::TrainingRequestKind::set_type;
action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 3);
action.value = bounded_int(integer(required(request, "value"), "value"), "value", 1, 3);
action.desired_types[size_t(action.index)] = uint8_t(action.value);
action.desired_automation &= uint8_t(~2);
} else if (cmd == "training.area") {
action.kind = ui::TrainingRequestKind::set_area;
action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 8);
action.value = bounded_int(integer(required(request, "value"), "value"), "value", 1, 3);
action.desired_areas[size_t(action.index)] = uint8_t(action.value);
action.desired_automation &= uint8_t(~4);
} else if (cmd == "training.intensity" || cmd == "training.focus") {
action.kind = cmd == "training.intensity" ? ui::TrainingRequestKind::set_player_intensity :
ui::TrainingRequestKind::set_player_focus;
action.index = bounded_int(integer(required(request, "row"), "row"), "row", 0, current.squad_capacity - 1);
const auto player = std::find_if(current.players.begin(), current.players.end(), [&](const auto& p) {
return p.row == action.index;
});
if (player == current.players.end()) return failed("training_row_unavailable", revision_);
action.player_id = player->player_id;
if (cmd == "training.intensity") {
action.value = bounded_int(integer(required(request, "value"), "value"), "value", 1, 3);
action.desired_automation &= uint8_t(~8);
} else action.value = (int(player->focus) + 1) % 8;
} else {
action.kind = ui::TrainingRequestKind::set_automation;
action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 4);
action.value = bounded_int(integer(required(request, "value"), "value"), "value", 0, 1);
const uint8_t mask = uint8_t(1u << action.index);
action.desired_automation = uint8_t((current.automation & ~mask) |
(action.value ? mask : 0));
}
std::string error;
if (!session_->dispatch_training(action, revision_, error))
return failed(error.empty() ? "action_rejected" : error, revision_, error);
const auto updated = session_->preparation_projection(revision_).training;
if (!updated) return failed("training_projection_unavailable", revision_);
return successful(revision_, {{"state", training_state(*updated)},
{"events", Array{Json(Object{{"event", "action_applied"}, {"command", cmd}})}}});
}
if (cmd == "tactics.set") {
if (!session_) return failed("no_active_career", revision_);
ui::TacticsRequest action;
put_envelope(request, action.manager_slot, action.revision);
action.runtime_club = current_desk(*session_, revision_).runtime_club;
action.kind = ui::TacticsRequestKind::set_tactic;
action.index = bounded_int(integer(required(request, "index"), "index"), "index", 0, 7);
action.desired_value = bounded_int(integer(required(request, "value"), "value"), "value", 0, 11);
if (action.index == 0) action.desired_assistant_attitude = 0;
std::string error;
if (!session_->dispatch_tactics(action, revision_, error))
return failed("action_rejected", revision_, error);
return successful(revision_, {{"state", tactics_state(session_->preparation_projection(revision_).tactics)},
{"events", Array{Json(Object{{"event", "action_applied"}, {"command", cmd}})}}});
}
if (cmd == "save") {
if (!session_) return failed("no_active_career", revision_);
int manager; std::uint64_t request_revision; put_envelope(request, manager, request_revision);
const auto desk = current_desk(*session_, revision_);
if (request_revision != revision_ || manager != desk.manager_slot)
return failed("stale_manager_or_revision", revision_);
const bool overwrite = replay || optional_boolean(request, "overwrite", false);
std::string error;
if (!session_->save_game(string(required(request, "path"), "path"), manager, overwrite, error))
return failed(error.empty() ? "save_rejected" : error, revision_);
return successful(revision_, {{"events", Array{Json(Object{{"event", "career_saved"}})}}});
}
if (cmd == "kickoff") {
if (!session_) return failed("no_active_career", revision_);
int manager; std::uint64_t request_revision; put_envelope(request, manager, request_revision);
ui::DeskRequest req; req.kind = ui::DeskRequestKind::advance_turn; req.manager_slot = manager; req.revision = request_revision;
std::string error;
const auto advanced = session_->dispatch_kickoff(req, revision_, error);
if (advanced.kind == TurnDeskKind::Failed || advanced.kind == TurnDeskKind::WaitingAtDesk)
return failed(error.empty() ? advanced.reason : error, revision_);
if (advanced.kind == TurnDeskKind::CareerComplete) {
return successful(revision_, {{"events", Array{Json(Object{
{"event", "career_complete"}, {"date", static_cast<std::int64_t>(advanced.date)},
{"season", session_->state().season}, {"duration", int(session_->state().memory.u8(::bmh::layout::CareerDuration))}})}},
{"status", completed_status(*session_, revision_)}});
}
Array events;
for (const auto& event : advanced.audio_events) {
std::string kind = event.kind == TurnAudioKind::kickoff_whistle ? "kickoff_whistle" :
event.kind == TurnAudioKind::goal ? "goal" : "full_time_whistle";
Object item{{"event", "audio"}, {"session_id", static_cast<std::int64_t>(event.session_id)},
{"event_id", static_cast<std::int64_t>(event.event_id)}, {"kind", std::move(kind)}};
if (event.original_id) item.emplace("original_id", int(*event.original_id));
events.emplace_back(std::move(item));
}
events.emplace_back(Object{{"event", "desk"}, {"manager", advanced.manager_slot},
{"date", static_cast<std::int64_t>(advanced.date)},
{"kind", advanced.kind == TurnDeskKind::SeasonEndDesk ? "season_end" : "next_desk"}});
const auto desk = current_desk(*session_, revision_);
return successful(revision_, {{"events", Json(std::move(events))}, {"state", desk_state_json(desk)},
{"results", result_state(*session_)}});
}
if (cmd.rfind("camp.", 0) == 0 || cmd.rfind("bank.", 0) == 0 ||
cmd.rfind("stadium.", 0) == 0 || cmd == "toto.submit") {
if (!session_) return failed("no_active_career", revision_);
int manager; std::uint64_t request_revision; put_envelope(request, manager, request_revision);
const auto desk = current_desk(*session_, revision_);
const int runtime_club = desk.runtime_club;
std::string error;
bool accepted = false;
std::string family;
if (cmd == "camp.focus" || cmd == "camp.book") {
family = "camp";
ui::TrainingCampRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision;
const auto prep = session_->preparation_projection(revision_);
if (!prep.training_camp) return failed("training_camp_projection_unavailable", revision_);
req.focus = prep.training_camp->focus;
if (cmd == "camp.focus") {
req.kind = ui::TrainingCampRequestKind::set_focus;
const Json& value = required(request, "focus"); const auto* values = value.array();
if (!values || values->size() != 4) return failed("invalid_focus", revision_);
for (size_t i = 0; i < 4; ++i) req.focus[i] = static_cast<uint8_t>(bounded_int(integer(values->at(i), "focus"), "focus", 0, 255));
} else {
req.kind = ui::TrainingCampRequestKind::book;
req.resort = bounded_int(integer(required(request, "resort"), "resort"), "resort", 0, 7);
}
accepted = session_->dispatch_training_camp(req, revision_, error);
} else if (cmd.rfind("bank.", 0) == 0) {
family = "bank";
ui::BankRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision;
if (cmd == "bank.deposit" || cmd == "bank.withdraw") {
req.kind = ui::BankRequestKind::move_to_deposit;
const auto amount = integer(required(request, "amount"), "amount");
if (amount <= 0 || amount > std::numeric_limits<std::int32_t>::max()) return failed("invalid_amount", revision_);
req.amount = static_cast<std::int32_t>(cmd == "bank.deposit" ? amount : -amount);
} else if (cmd == "bank.shares.buy" || cmd == "bank.shares.sell" || cmd == "bank.tip") {
req.kind = cmd == "bank.shares.buy" ? ui::BankRequestKind::buy_shares :
cmd == "bank.shares.sell" ? ui::BankRequestKind::sell_shares : ui::BankRequestKind::stock_tip;
req.asset_index = bounded_int(integer(required(request, "asset"), "asset"), "asset", 0, 11);
req.count = bounded_int(optional_integer(request, "count", 0), "count", 0, 9999);
} else if (cmd == "bank.fund.buy" || cmd == "bank.fund.sell") {
req.kind = cmd == "bank.fund.buy" ? ui::BankRequestKind::buy_fund : ui::BankRequestKind::sell_fund;
req.asset_index = bounded_int(integer(required(request, "asset"), "asset"), "asset", 0, 5);
req.count = bounded_int(integer(required(request, "count"), "count"), "count", 1, 10);
} else return failed("unsupported_command", revision_);
accepted = session_->dispatch_bank(req, revision_, error);
} else if (cmd.rfind("stadium.", 0) == 0) {
family = "stadium";
ui::StadiumRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision;
if (cmd == "stadium.open") req.kind = ui::StadiumRequestKind::open;
else if (cmd == "stadium.offer") { req.kind = ui::StadiumRequestKind::quote_periphery; req.object = bounded_int(integer(required(request, "object"), "object"), "object", 0, 13); }
else if (cmd == "stadium.build") { req.kind = ui::StadiumRequestKind::build_periphery; req.object = bounded_int(integer(required(request, "object"), "object"), "object", 0, 13); req.price = bounded_int(integer(required(request, "price"), "price"), "price", 1, std::numeric_limits<int>::max()); }
else if (cmd == "stadium.decline") { req.kind = ui::StadiumRequestKind::decline_periphery; req.object = bounded_int(integer(required(request, "object"), "object"), "object", 0, 13); req.price = bounded_int(integer(required(request, "price"), "price"), "price", 1, std::numeric_limits<int>::max()); }
else return failed("unsupported_command", revision_);
accepted = session_->dispatch_stadium(req, revision_, error);
} else if (cmd == "toto.submit") {
family = "toto";
ui::TotoRequest req; req.manager_slot = manager; req.runtime_club = runtime_club; req.revision = request_revision;
req.stake = bounded_int(integer(required(request, "stake"), "stake"), "stake", 0, std::numeric_limits<int>::max());
const Json& value = required(request, "tips"); const auto* tips = value.array();
if (!tips || tips->size() != req.tips.size()) return failed("invalid_tips", revision_);
for (size_t i = 0; i < req.tips.size(); ++i) req.tips[i] = static_cast<uint8_t>(bounded_int(integer(tips->at(i), "tips"), "tips", 0, 2));
req.kind = ui::TotoRequestKind::submit;
accepted = session_->dispatch_toto(req, revision_, error);
}
if (!accepted) return failed(error.empty() ? "action_rejected" : error, revision_);
return successful(revision_, {{"events", Array{Json(Object{{"event", "action_applied"}, {"command", cmd}})}},
{"state", action_state(*session_, revision_, family, manager).object()->at("state")}});
}
if (cmd == "squad" || cmd == "player" || cmd == "calendar" || cmd == "finances" ||
cmd == "lineup.auto" || cmd.rfind("match.", 0) == 0)
return failed("career_session_api_unavailable", revision_, "This command has no CareerSession projection/dispatch adapter in E10 stage 1.");
return failed("unsupported_command", revision_);
} catch (const JsonError& e) {
return failed("invalid_request", revision_, e.what());
} catch (const std::exception& e) {
return failed("operation_failed", revision_, e.what());
}
}
Json text_request(std::string_view line, const Protocol* protocol) {
std::istringstream input{std::string(line)};
std::string cmd;
input >> cmd;
if (cmd.empty()) throw JsonError("empty_command");
Object req{{"cmd", cmd}};
std::string path, name;
auto envelope = [&] {
if (!protocol || !protocol->active()) throw JsonError("no_active_career");
req.emplace("manager", 0);
req.emplace("revision", static_cast<std::int64_t>(protocol->revision()));
};
if (cmd == "new") {
int master = -1, strength = 1;
if (!(input >> master >> std::quoted(name))) throw JsonError("usage:new <master_club> <manager_name> [strength]");
if (input >> strength) { /* optional */ }
req.emplace("options", Json(Object{{"managers", 1}}));
req.emplace("managers", Json(Array{Json(Object{{"master_club", master}, {"name", name}, {"strength", strength}})}));
} else if (cmd == "load" || cmd == "save") {
if (!(input >> std::quoted(path))) throw JsonError("usage:" + cmd + " <path>");
req.emplace("path", path);
if (cmd == "save") envelope();
} else if (cmd == "kickoff") envelope();
else if (cmd == "tactics.set") {
int index = -1, value = -1;
if (!(input >> index >> value)) throw JsonError("usage:tactics.set <index> <value>");
req.emplace("index", index); req.emplace("value", value); envelope();
}
else if (cmd == "training") {
} else if (cmd == "training.initialize") envelope();
else if (cmd == "training.type" || cmd == "training.area" || cmd == "training.auto") {
int index = -1, value = -1;
if (!(input >> index >> value)) throw JsonError("usage:" + cmd + " <index> <value>");
req.emplace("index", index); req.emplace("value", value); envelope();
} else if (cmd == "training.intensity") {
int row = -1, value = -1;
if (!(input >> row >> value)) throw JsonError("usage:training.intensity <row> <value>");
req.emplace("row", row); req.emplace("value", value); envelope();
} else if (cmd == "training.focus") {
int row = -1;
if (!(input >> row)) throw JsonError("usage:training.focus <row>");
req.emplace("row", row); envelope();
} else if (cmd == "table") {
int manager = -1, league = -1;
if (!(input >> manager >> league)) throw JsonError("usage:table <manager> <league>");
if (!protocol || !protocol->active()) throw JsonError("no_active_career");
req.emplace("manager", manager);
req.emplace("league", league);
} else if (cmd == "mail") {
int manager = -1;
if (!(input >> manager)) throw JsonError("usage:mail <manager:0..3>");
if (!protocol || !protocol->active()) throw JsonError("no_active_career");
req.emplace("manager", manager);
}
else if (cmd == "bank.deposit" || cmd == "bank.withdraw") {
std::int64_t amount;
if (!(input >> amount)) throw JsonError("usage:" + cmd + " <amount>");
req.emplace("amount", amount); envelope();
} else if (cmd == "bank.shares.buy" || cmd == "bank.shares.sell" || cmd == "bank.tip") {
int asset = -1, count = 0;
if (!(input >> asset)) throw JsonError("usage:" + cmd + " <asset> [count]");
if (cmd != "bank.tip" && !(input >> count)) throw JsonError("usage:" + cmd + " <asset> <count>");
req.emplace("asset", asset); req.emplace("count", count); envelope();
} else if (cmd == "bank.fund.buy" || cmd == "bank.fund.sell") {
int asset = -1, count = 0;
if (!(input >> asset >> count)) throw JsonError("usage:" + cmd + " <asset> <count>");
req.emplace("asset", asset); req.emplace("count", count); envelope();
} else if (cmd == "camp.book") {
int resort = -1; if (!(input >> resort)) throw JsonError("usage:camp.book <resort>");
req.emplace("resort", resort); envelope();
} else if (cmd == "help" || cmd == "status" || cmd == "desk" || cmd == "quit" || cmd == "tactics" || cmd == "results") {
} else throw JsonError("unsupported_text_command:" + cmd);
std::string extra;
if (input >> extra) throw JsonError("too_many_arguments");
return req;
}
std::string text_response(const Json& response) {
const auto* ok = find(response, "ok");
const auto* ok_value = ok ? ok->boolean() : nullptr;
if (ok_value && !*ok_value) {
std::string out = "ERROR " + optional_string(response, "error", "unknown_error");
if (const auto* detail = find(response, "detail"); detail && detail->string()) out += ": " + *detail->string();
return out;
}
std::string out = "OK revision " + std::to_string(optional_integer(response, "revision", 0));
if (const auto* status = find(response, "status"); status && status->object()) {
if (optional_string(*status, "phase", "") == "career_complete")
return out + " | career complete | date " + std::to_string(optional_integer(*status, "date", 0));
out += " | " + optional_string(*status, "club", "club ?");
out += " | date " + std::to_string(optional_integer(*status, "day", 0)) + "." +
std::to_string(optional_integer(*status, "month", 0)) + "." + std::to_string(optional_integer(*status, "year", 0));
out += " | balance " + std::to_string(optional_integer(*status, "balance", 0));
} else if (const auto* state = find(response, "state")) out += " | " + dump_json(*state);
return out;
}
} // namespace bmh::cli
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "cli/json.hpp"
#include <filesystem>
#include <memory>
#include <string>
namespace bmh::app { class CareerSession; }
namespace bmh::cli {
class Protocol {
public:
Protocol(std::filesystem::path data, std::uint32_t seed);
~Protocol();
Json handle(const Json& request, bool replay = false);
bool active() const noexcept;
std::uint64_t revision() const noexcept { return revision_; }
static Json help();
private:
std::filesystem::path data_;
std::uint32_t seed_;
std::uint64_t revision_ = 0;
std::unique_ptr<app::CareerSession> session_;
};
Json text_request(std::string_view line, const Protocol* protocol);
std::string text_response(const Json& response);
} // namespace bmh::cli
+287
View File
@@ -0,0 +1,287 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "cli/seat_hub.hpp"
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include "cli/console/parser.hpp"
#include "cli/json.hpp"
namespace bmh::cli {
namespace {
std::string trimmed(const std::string& s) {
const size_t a = s.find_first_not_of(" \t");
if (a == std::string::npos) return {};
return s.substr(a, s.find_last_not_of(" \t") - a + 1);
}
bool is_wait_turn(const std::string& command) {
const std::string key = console::canonical(command);
return key == "waitturn" || key == "waitturn()";
}
const char* json_class(char cls) { // as Console::emit names them
switch (cls) {
case '#': return "status";
case '!': return "error";
default: return "info";
}
}
} // namespace
SeatHub::SeatHub(console::Options options, int seats, std::function<void(const console::Console&)> on_block)
: options_(options),
console_(options, [](const std::string&) {}),
seats_(size_t(seats < 1 ? 1 : seats)),
on_block_(std::move(on_block)),
asked_(4) {
console_.set_line_observer([this](const console::Console::LineInfo& line) { lines_.push_back(line); });
console_.start();
for (const auto& l : lines_) start_.push_back(l.line);
lines_.clear();
if (on_block_) on_block_(console_);
}
std::string SeatHub::format(char cls, const std::string& text) const {
if (!options_.json) return std::string(1, cls) + " " + text;
return dump_json(Json(Json::Object{{"class", json_class(cls)}, {"text", text}}));
}
// A line concerns a seat when it belongs to its manager or to all; chat lines name their
// addressee ("[P1 -> P2] ...", "[P1 -> All] ...").
bool SeatHub::concerns(const console::Console::LineInfo& line, int seat) const {
if (line.cls == 'c') {
const size_t arrow = line.text.find(" -> ");
const size_t end = line.text.find(']', arrow == std::string::npos ? 0 : arrow);
if (arrow == std::string::npos || end == std::string::npos) return true;
const std::string target = line.text.substr(arrow + 4, end - arrow - 4);
return target == "All" || target == "P" + std::to_string(seat);
}
return line.player == 0 || line.player == seat;
}
bool SeatHub::on_turn(int seat) const {
if (console_.ended()) return true;
if (const int q = console_.question_player()) return q == seat;
return console_.active_player() == seat || console_.active_player() == 0;
}
std::vector<std::string> SeatHub::answer(Seat& seat, std::vector<std::string> own) {
std::vector<std::string> response;
if (!seat.feed.empty()) {
response.push_back(format('i', "--- meanwhile ---"));
response.insert(response.end(), seat.feed.begin(), seat.feed.end());
response.push_back(format('i', "--- end of meanwhile ---"));
}
response.insert(response.end(), own.begin(), own.end());
seat.feed.clear();
return response;
}
std::optional<std::vector<std::string>> SeatHub::submit(int seat, std::vector<std::string> lines) {
using console::classify_line;
using console::LineKind;
if (seat < 1 || seat > int(seats_.size())) return std::vector<std::string>{format('!', "E_BAD_ARGUMENT: no seat " + std::to_string(seat))};
Seat& me = seats_[size_t(seat - 1)];
while (!lines.empty() && trimmed(lines.back()).empty()) lines.pop_back();
std::vector<std::string> commands;
for (const auto& l : lines)
if (classify_line(l) == LineKind::command) commands.push_back(trimmed(l));
const bool multi = seats_.size() > 1;
if (commands.size() == 1 && is_wait_turn(commands[0])) {
me.waiting = true;
if (!multi) { // one client: always its turn
auto now = release();
if (!now.empty()) return now.front().second;
}
return std::nullopt;
}
for (const auto& c : commands)
if (is_wait_turn(c))
return answer(me, {format('!', "E_BAD_ARGUMENT: WaitTurn must be a block of its own (nothing else in it)")});
// A live match runs for everybody (player All): the clock moves only when every seat has
// sent its Run or Step - after its own interventions (tactics, substitutions, moves). The
// earliest stop asked for is taken (Step(n) before Run(Halftime) before Run); every seat
// then gets the output. Without this the first Run would play the day to the end and the
// other managers would miss their half time.
// A block that ends with the Run (interventions first, then "Run") runs its other lines
// now and holds only the Run - otherwise its Run would play past the barrier (learning
// session run 1: the other seats then waited for a match day that was over).
if (multi && console_.window() == "Match" && !commands.empty()) {
// Only the last command of a block may move the clock: a Run/Step in the middle
// ("Step(3)", "SetTactic(..)", "Run(Halftime)", "ShowMatchStats") would run past the
// barrier for everybody (learning session run 2, block 715).
for (size_t i = 0; i + 1 < commands.size(); ++i) {
std::string m = commands[i];
if (!m.empty() && m[0] == '@') m = trimmed(m.substr(m.find_first_not_of("@0123456789")));
const std::string key = console::canonical(m.substr(0, m.find('(')));
if (key == "run" || key == "step")
return answer(me, {format('!', "E_BAD_ARGUMENT: in a live match only the last command of a block may be "
"Run or Step (the clock waits for every manager) - nothing was executed")});
}
std::string c = commands.back();
if (!c.empty() && c[0] == '@') c = trimmed(c.substr(c.find_first_not_of("@0123456789")));
const std::string name = console::canonical(c.substr(0, c.find('(')));
if ((name == "run" || name == "step") && !me.run.empty())
return answer(me, {format('!', "E_BAD_ARGUMENT: your " + me.run + " is already waiting for the other managers")});
if ((name == "run" || name == "step") && commands.size() > 1) {
std::vector<std::string> before;
for (const auto& l : lines) {
if (classify_line(l) == LineKind::command && trimmed(l) == commands.back()) break;
before.push_back(l);
}
before.push_back("go.");
// (the earlier lines are checked as any block: an @n of another seat is refused)
auto first = submit(seat, before);
if (first) me.held = std::move(*first);
if (console_.window() != "Match") { // (cannot happen: interventions do not end the day)
std::vector<std::string> out = std::move(me.held);
me.held.clear();
out.push_back(format('i', "the match day is over - " + c + " was not needed"));
return out;
}
commands = {commands.back()};
}
if (name == "run" || name == "step") {
me.run = c;
for (const auto& s : seats_)
if (s.run.empty()) return std::nullopt; // wait for the others
int step = 0;
bool halftime = false;
for (const auto& s : seats_) {
const std::string key = console::canonical(s.run);
if (key.rfind("step", 0) == 0) {
const size_t open = s.run.find('(');
const int n = open == std::string::npos ? 1 : std::max(1, std::atoi(s.run.c_str() + open + 1));
step = step == 0 ? n : std::min(step, n);
}
if (key.find("halftime") != std::string::npos) halftime = true;
}
const std::string chosen = step ? "Step(" + std::to_string(step) + ")" : halftime ? "Run(Halftime)" : "Run";
std::vector<std::string> own = run_block(seat, {"@" + std::to_string(seat) + " " + chosen, "go."});
for (size_t j = 0; j < seats_.size(); ++j) {
Seat& s = seats_[j];
s.run.clear();
std::vector<std::string> mine = std::move(s.held);
s.held.clear();
if (int(j) + 1 == seat) mine.insert(mine.end(), own.begin(), own.end());
ready_.emplace_back(int(j) + 1, answer(s, std::move(mine)));
}
return std::nullopt; // every seat's answer comes out of release()
}
}
// every command line acts for this seat's manager (one seat: the active player, as at the
// console)
if (multi) {
std::string refused;
for (auto& l : lines) {
if (classify_line(l) != LineKind::command) continue;
const std::string t = trimmed(l);
if (t.front() == '@') {
size_t i = 1;
while (i < t.size() && std::isdigit(static_cast<unsigned char>(t[i]))) ++i;
if (t.substr(1, i - 1) != std::to_string(seat)) refused = t;
l = t;
} else {
l = "@" + std::to_string(seat) + " " + t;
}
}
if (!refused.empty())
return answer(me, {format('!', "E_NOT_YOUR_TURN: you are player " + std::to_string(seat) + " (" + refused + ")")});
}
if (lines.empty() || classify_line(lines.back()) != LineKind::go) lines.push_back("go.");
return answer(me, run_block(seat, std::move(lines)));
}
// Executes one block for a seat and splits its output (see submit).
std::vector<std::string> SeatHub::run_block(int seat, std::vector<std::string> lines) {
using console::classify_line;
using console::LineKind;
const bool multi = seats_.size() > 1;
std::vector<std::string> own;
const bool sender_on_turn = !multi || on_turn(seat); // (also true for the answer to his question)
for (const auto& l : lines) {
lines_.clear();
const bool executes = classify_line(l) == LineKind::go;
console_.feed(l);
if (executes && on_block_) on_block_(console_);
// Errors and listings ('!', '>') and the sender's own chat answer the sender only;
// another manager's lines (his desk after the turn passed) go to that seat only. A seat
// that was not on turn can change nothing for the others: it gets all of its output,
// the others only its chat.
for (const auto& line : lines_) {
if (line.cls == '?' && line.player >= 1 && line.player <= 4) asked_[size_t(line.player - 1)] = line.line;
if (!multi) {
own.push_back(line.line);
continue;
}
const bool chat = line.cls == 'c';
const bool reply = line.cls == '!' || line.cls == '>' ||
(chat && line.text.rfind("[P" + std::to_string(seat) + " ", 0) == 0);
if (!sender_on_turn || reply || line.cls == '#' || concerns(line, seat)) own.push_back(line.line);
if (reply && !chat) continue;
if (!sender_on_turn && !chat) continue;
for (size_t j = 0; j < seats_.size(); ++j)
if (int(j) + 1 != seat && concerns(line, int(j) + 1)) seats_[j].feed.push_back(line.line);
}
if (console_.ended()) break;
}
lines_.clear();
return own;
}
void SeatHub::drop_stale_runs() {
if (console_.window() == "Match" && !console_.ended()) return;
for (size_t j = 0; j < seats_.size(); ++j) {
Seat& s = seats_[j];
if (s.run.empty()) continue;
std::vector<std::string> mine = std::move(s.held);
s.held.clear();
mine.push_back(format('i', "the match day is over - your " + s.run + " was not needed"));
s.run.clear();
ready_.emplace_back(int(j) + 1, answer(s, std::move(mine)));
}
}
std::vector<std::pair<int, std::vector<std::string>>> SeatHub::release() {
drop_stale_runs();
std::vector<std::pair<int, std::vector<std::string>>> out;
// the answers of a live-match Run every seat agreed on come first
out.swap(ready_);
for (size_t k = 0; k < seats_.size(); ++k) {
Seat& seat = seats_[k];
const int number = int(k) + 1;
if (!seat.waiting || !(seats_.size() == 1 || on_turn(number))) continue;
const int active = console_.active_player();
std::vector<std::string> status{format('#', "Window: " + console_.window()),
format('#', "Player: " + (active ? std::to_string(active) : std::string("All")))};
if (console_.ended()) status.push_back(format('#', "Session ended"));
// a question for this seat may have been asked in its own last answer: repeat it, so a
// client does not mistake the turn for a free one (GoBack would decline it)
if (console_.question_player() == number && !asked_[k].empty()) status.push_back(asked_[k]);
out.emplace_back(number, answer(seat, std::move(status)));
seat.waiting = false;
}
return out;
}
bool SeatHub::replay(const std::vector<std::string>& block, const std::vector<std::string>& expected) {
for (const auto& l : block) console_.feed(l);
console_.feed("go.");
if (on_block_) on_block_(console_);
lines_.clear();
return console_.last_output() == expected;
}
void SeatHub::forget(int seat) {
if (seat >= 1 && seat <= int(seats_.size())) seats_[size_t(seat - 1)].waiting = false;
}
} // namespace bmh::cli
+84
View File
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// SeatHub: one console game shared by several clients (agents, a graphical front end), each
// client one human manager ("seat"). The transports - the mailbox directories of --serve and
// the TCP connections of --listen (src/cli/main.cpp) - only move blocks of lines; the hub
// decides what each seat may do and sees:
// - A seat's command lines run as "@k <line>": a client acts only as its own manager (a line
// with another @n is refused). Whoever is not on turn may only use the commands of every
// window (Status, Help, Chat, Answer, State ...); the console says E_NOT_YOUR_TURN.
// - An answer starts with what happened in the other seats' blocks since this seat's last
// answer and concerns it - lines of player All or k, chat to all or to Pk - between two
// "--- meanwhile ---" info lines. Errors and listings stay with their sender; another
// manager's desk lines go to that manager only.
// - A block that holds only "WaitTurn" is held until manager k is on turn, a question for
// him is open, a live match runs (player All) or the session ends; its answer is the
// meanwhile part, the window and player status and an open question for him again.
// Lines are routed by Console::LineInfo (class, player, text), so the text and the JSON
// format (--json) behave the same. With one seat the hub is a plain pass-through.
// - During a live match (stepped time, window Match, player All) a Run or Step is held until
// every seat has sent one; the earliest stop is played and every seat gets the output.
// A block that ends with Run/Step (e.g. "Substitute(..)" then "Run") runs its other lines
// at once and holds the Run. Should the match day end while runs are held (it cannot, as
// every Run goes through the barrier, but a held seat must never wait for ever), the held
// seats are answered with what their lines did and a note.
#include <functional>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "cli/console/console.hpp"
namespace bmh::cli {
class SeatHub {
public:
// `seats`: number of clients (1-4). `on_block`: called after every executed block (the
// console's last_block / last_output), for the session log.
SeatHub(console::Options options, int seats, std::function<void(const console::Console&)> on_block);
// The start output (Window/Player lines), for each newly connected seat.
const std::vector<std::string>& start_output() const { return start_; }
int seats() const { return int(seats_.size()); }
bool ended() const { return console_.ended(); }
// One block from seat `seat` (1-based). Returns its answer, or nothing when the block is a
// WaitTurn that is held; release() hands such answers out later.
std::optional<std::vector<std::string>> submit(int seat, std::vector<std::string> lines);
// Held WaitTurns that can be answered now (after a block of another seat, or at the end).
std::vector<std::pair<int, std::vector<std::string>>> release();
// A held WaitTurn of a seat whose client went away is dropped.
void forget(int seat);
// Feeds one executed block of an earlier session log again (--resume): the console draws
// no random numbers, so the game reaches the same state. Returns false when the output
// differs from `expected`.
bool replay(const std::vector<std::string>& block, const std::vector<std::string>& expected);
private:
struct Seat {
bool waiting = false; // a WaitTurn is held
std::vector<std::string> feed; // other seats' lines that concern this seat
std::string run; // its Run/Step during a live match, held until all have sent one
std::vector<std::string> held; // the output of the lines before that Run in its block
};
void drop_stale_runs(); // held runs of a match day that is over are answered
std::string format(char cls, const std::string& text) const; // a line of the hub itself
bool concerns(const console::Console::LineInfo& line, int seat) const;
bool on_turn(int seat) const;
std::vector<std::string> answer(Seat& seat, std::vector<std::string> own);
std::vector<std::string> run_block(int seat, std::vector<std::string> lines);
console::Options options_;
console::Console console_;
std::vector<Seat> seats_;
std::vector<std::string> start_;
std::function<void(const console::Console&)> on_block_;
// the lines of the block being executed, with their meaning
std::vector<console::Console::LineInfo> lines_;
std::vector<std::string> asked_; // the last question line per player (index player-1)
std::vector<std::pair<int, std::vector<std::string>>> ready_; // answers of an agreed live-match Run
};
} // namespace bmh::cli