diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-12 00:28:50 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-12 00:28:50 +0100 |
| commit | 808294adad3f378ad8d66b698acf8df7f49c2302 (patch) | |
| tree | cfd11a1395a8ad482311969f86abbbad97e7e0b4 /server/lib/core/commands/command_registry.dart | |
| parent | f6955e34489c79f6d5b764cb6a39b1387366b433 (diff) | |
Phase 1: headless game engine on the server (M1)
Complete mechanical port of the reference app's game engine to
server/lib/core/ so later phases are UI-only:
- models/ (7), state/ (GameState + 18 part files), methods/ (7),
game_methods, 79 command files, enums, card_stack, stat_calculator,
action_handler (index, 250-deep history, save-per-action, undo/redo),
disk-based game_data, l10n, translation_service, service_locator
- ValueNotifier/ChangeNotifier removed in favor of plain fields with a
minimal GameState listener hook for the Phase 2 broadcast layer;
shared_preferences replaced by the SaveStore abstraction
(InMemory for tests, File-backed for bin/main.dart)
- command registry: 82 entries mapping wire names to constructors with
arg validation; live-object args (loot/ability cards, figure lists)
travel as id/name/nr and resolve against live state, enums by name,
injected singletons never serialize
- line_builder ported to Phase 1 scope: stat_applier + minimal
LineBuilder (isElement, tokens); widget rendering deferred to Phase 4
- ported test suite: 81 test files, 562 tests green (command tests 1:1
with the reference, resource tests, registry smoke tests)
- new headless integration test drives a full round: scenario setup,
characters + standee, secret-initiative gate, draw, every figure's
turn (incl. undo/redo), next round, round 2, round 3
- PORTING.md: the conventions contract used for the port
- bin/main.dart boots the engine (file save store, assets/data) before
serving; pubspec gains built_collection, collection, get_it, intl
- dart format drift on pre-existing net/test files from the current
formatter (whitespace only)
dart analyze warning-free; dart test 562/562.
Diffstat (limited to 'server/lib/core/commands/command_registry.dart')
| -rw-r--r-- | server/lib/core/commands/command_registry.dart | 1109 |
1 files changed, 1109 insertions, 0 deletions
diff --git a/server/lib/core/commands/command_registry.dart b/server/lib/core/commands/command_registry.dart new file mode 100644 index 0000000..9a05b97 --- /dev/null +++ b/server/lib/core/commands/command_registry.dart @@ -0,0 +1,1109 @@ +/// Command registry: wire name → command construction. +/// +/// The Phase 2 network layer receives `{name, args}` messages from clients +/// and calls [buildCommand] to turn them into a [Command] for the +/// `ActionHandler`. [commandName] is the reverse lookup (runtime type → +/// wire name), used by describe/tests. +/// +/// Conventions (PORTING.md §9): +/// +/// * Wire names are the class name minus the `Command` suffix in +/// lower-camel case (acronym runs lower-cased in full): `DrawCommand` → +/// `draw`, `AddMonsterCommand` → `addMonster`, `ChangeHealthCommand` → +/// `changeHealth`, `AMDCassandraSpecialCommand` → `amdCassandraSpecial`. +/// The wire name comes from the class name, never the file name (the file +/// `remove__special_loot_card_command.dart` holds `RemoveSpecialLootCardCommand` +/// → `removeSpecialLootCard`). +/// * Args are a JSON `Map<String, dynamic>`. The wire keys are the +/// constructor parameter names — positional parameters in positional +/// order, leading underscores stripped — e.g. `AddPerkCommand(characterId, +/// index)` takes `{'characterId': ..., 'index': ...}`. +/// * Optional parameters may be omitted or given as JSON `null`. +/// * `GameState`, `Settings` and `GameData` are never wire args — they are +/// injected from the service locator (see [buildCommand]). +/// * Enums travel as name strings (`'chill'`, `'fire'`, `'elite'`, ...). +/// Complex object args are resolved against the live game state (see the +/// per-entry doc comments in [_registry]). +/// +/// Any failure — unknown command, missing required arg, wrong JSON type, +/// unknown enum value, unresolvable object reference — is reported as +/// [CommandRegistryError] with a human-readable message naming the command +/// and the arg. Failures thrown by a command's own constructor (e.g. +/// `AddCharacterCommand` for an unknown character id) are wrapped the same +/// way so the network layer only ever sees [CommandRegistryError]. +library; + +import 'package:x_haven_server/core/commands/activate_monster_type_command.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_condition_command.dart'; +import 'package:x_haven_server/core/commands/add_cs_party_card_command.dart'; +import 'package:x_haven_server/core/commands/add_faction_card_command.dart'; +import 'package:x_haven_server/core/commands/add_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_note_row_command.dart'; +import 'package:x_haven_server/core/commands/add_perk_command.dart'; +import 'package:x_haven_server/core/commands/add_special_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/amd_add_minus_one_command.dart'; +import 'package:x_haven_server/core/commands/amd_cassandra_special_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue1_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue2_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_imbue_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_minus_1_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_minus_2_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_plus_0_command.dart'; +import 'package:x_haven_server/core/commands/amd_reveal_command.dart'; +import 'package:x_haven_server/core/commands/bad_omen_command.dart'; +import 'package:x_haven_server/core/commands/change_name_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_bless_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_curse_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_empower_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_enfeeble_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_max_health_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_xp_command.dart'; +import 'package:x_haven_server/core/commands/clear_unlocked_classes_command.dart'; +import 'package:x_haven_server/core/commands/corrosive_spew_command.dart'; +import 'package:x_haven_server/core/commands/donate_cs_sanctuary_command.dart'; +import 'package:x_haven_server/core/commands/draw_ability_card_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/draw_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/commands/enhance_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/hide_ally_deck_command.dart'; +import 'package:x_haven_server/core/commands/ice_wraith_change_form_command.dart'; +import 'package:x_haven_server/core/commands/imbue_element_command.dart'; +import 'package:x_haven_server/core/commands/load_character_save_command.dart'; +import 'package:x_haven_server/core/commands/load_save_command.dart'; +import 'package:x_haven_server/core/commands/next_round_command.dart'; +import 'package:x_haven_server/core/commands/remove__special_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/remove_amd_card_command.dart'; +import 'package:x_haven_server/core/commands/remove_card_command.dart'; +import 'package:x_haven_server/core/commands/remove_character_command.dart'; +import 'package:x_haven_server/core/commands/remove_condition_command.dart'; +import 'package:x_haven_server/core/commands/remove_cs_party_card_command.dart'; +import 'package:x_haven_server/core/commands/remove_cs_sanctuary_donation_command.dart'; +import 'package:x_haven_server/core/commands/remove_monster_command.dart'; +import 'package:x_haven_server/core/commands/remove_note_row_command.dart'; +import 'package:x_haven_server/core/commands/reorder_ability_list_command.dart'; +import 'package:x_haven_server/core/commands/reorder_list_command.dart'; +import 'package:x_haven_server/core/commands/reorder_modifier_list_command.dart'; +import 'package:x_haven_server/core/commands/return_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/return_modifier_card_command.dart'; +import 'package:x_haven_server/core/commands/return_removed_amd_card_command.dart'; +import 'package:x_haven_server/core/commands/set_ally_deck_in_og_gloom_command.dart'; +import 'package:x_haven_server/core/commands/set_as_summon_command.dart'; +import 'package:x_haven_server/core/commands/set_auto_level_adjust_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_character_level_command.dart'; +import 'package:x_haven_server/core/commands/set_difficulty_command.dart'; +import 'package:x_haven_server/core/commands/set_figure_note_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/commands/set_loot_owner_command.dart'; +import 'package:x_haven_server/core/commands/set_note_row_color_command.dart'; +import 'package:x_haven_server/core/commands/set_note_row_link_command.dart'; +import 'package:x_haven_server/core/commands/set_note_row_text_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/commands/set_solo_command.dart'; +import 'package:x_haven_server/core/commands/show_ally_deck_command.dart'; +import 'package:x_haven_server/core/commands/shuffle_ability_card_command.dart'; +import 'package:x_haven_server/core/commands/shuffle_amd_card_command.dart'; +import 'package:x_haven_server/core/commands/shuffle_drawn_ability_card_command.dart'; +import 'package:x_haven_server/core/commands/track_standees_command.dart'; +import 'package:x_haven_server/core/commands/turn_done_command.dart'; +import 'package:x_haven_server/core/commands/unlock_special_command.dart'; +import 'package:x_haven_server/core/commands/use_element_command.dart'; +import 'package:x_haven_server/core/commands/use_fh_perks_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/models/monster_ability.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +/// One entry: wire name, arg parsing/validation, and command construction. +class CommandDescriptor { + const CommandDescriptor(this.name, this.construct); + final String name; // e.g. 'draw', 'addMonster', 'changeHealth' + final Command Function(GameState gameState, Map<String, dynamic> args) + construct; +} + +/// Thrown for unknown command names or invalid/missing args. +class CommandRegistryError implements Exception { + CommandRegistryError(this.message); + final String message; + @override + String toString() => 'CommandRegistryError: $message'; +} + +/// Builds a [Command] from a wire name + JSON arg map. +/// +/// Throws [CommandRegistryError] with a human-readable message on unknown +/// names, invalid/missing args, or command-construction failure. +Command buildCommand( + String name, + Map<String, dynamic> args, + GameState gameState, +) { + final descriptor = _registry[name]; + if (descriptor == null) { + throw CommandRegistryError( + 'Unknown command "$name". ' + 'Known commands: ${_registry.keys.join(', ')}', + ); + } + try { + return descriptor.construct(gameState, args); + } on StateError catch (error, stackTrace) { + Error.throwWithStackTrace( + CommandRegistryError('Command "$name": ${error.message}'), + stackTrace, + ); + } on ArgumentError catch (error, stackTrace) { + Error.throwWithStackTrace( + CommandRegistryError( + 'Command "$name": ${error.message ?? 'invalid arguments'}', + ), + stackTrace, + ); + } +} + +/// Reverse lookup (for describe/tests): wire name of [command]'s runtime +/// type. +/// +/// Throws [CommandRegistryError] if [command]'s type is not registered. +String commandName(Command command) { + final name = _nameByType[command.runtimeType]; + if (name == null) { + throw CommandRegistryError( + 'No wire name registered for ${command.runtimeType}', + ); + } + return name; +} + +/// All registered commands, wire name → [CommandDescriptor]. +final Map<String, CommandDescriptor> _registry = { + 'activateMonsterType': CommandDescriptor( + 'activateMonsterType', + (gs, args) => ActivateMonsterTypeCommand( + _str('activateMonsterType', 'name', args), + _bool('activateMonsterType', 'activate', args), + gameState: gs, + ), + ), + 'addCharacter': CommandDescriptor( + 'addCharacter', + (gs, args) => AddCharacterCommand( + _str('addCharacter', 'id', args), + _str('addCharacter', 'edition', args), + _strOr('addCharacter', 'display', args), + _int('addCharacter', 'level', args), + ), + ), + 'addCondition': CommandDescriptor( + 'addCondition', + (gs, args) => AddConditionCommand( + _condition('addCondition', 'condition', args), + _str('addCondition', 'figureId', args), + _strOr('addCondition', 'ownerId', args), + gameState: gs, + ), + ), + 'addCSPartyCard': CommandDescriptor( + 'addCSPartyCard', + (gs, args) => AddCSPartyCardCommand( + _str('addCSPartyCard', 'characterId', args), + _int('addCSPartyCard', 'type', args), + gameState: gs, + ), + ), + 'addFactionCard': CommandDescriptor( + 'addFactionCard', + (gs, args) => AddFactionCardCommand( + _str('addFactionCard', 'characterId', args), + _str('addFactionCard', 'cardId', args), + _bool('addFactionCard', 'add', args), + gameState: gs, + ), + ), + 'addLootCard': CommandDescriptor( + 'addLootCard', + (gs, args) => AddLootCardCommand( + _str('addLootCard', 'resourceType', args), + gameState: gs, + ), + ), + 'addMonster': CommandDescriptor( + 'addMonster', + (gs, args) => AddMonsterCommand( + _str('addMonster', 'name', args), + _intOr('addMonster', 'level', args), + _bool('addMonster', 'isAlly', args), + gameState: gs, + ), + ), + // `noteRow` is a JSON object `{id, text, color, linkedId, standeeNr}`; + // `id` is a client-generated unique string. + 'addNoteRow': CommandDescriptor( + 'addNoteRow', + (gs, args) => + AddNoteRowCommand(_noteRow('addNoteRow', args), gameState: gs), + ), + 'addPerk': CommandDescriptor( + 'addPerk', + (gs, args) => AddPerkCommand( + _str('addPerk', 'characterId', args), + _int('addPerk', 'index', args), + ), + ), + 'addSpecialLootCard': CommandDescriptor( + 'addSpecialLootCard', + (gs, args) => AddSpecialLootCardCommand( + _int('addSpecialLootCard', 'nr', args), + gameState: gs, + ), + ), + // `summon` is an optional JSON object + // `{standeeNr, name, health, move, attack, range, gfx}`; absent/null → null. + 'addStandee': CommandDescriptor( + 'addStandee', + (gs, args) => AddStandeeCommand( + _int('addStandee', 'nr', args), + _summonData('addStandee', args), + _str('addStandee', 'ownerId', args), + _monsterType('addStandee', 'type', args), + _bool('addStandee', 'addAsSummon', args), + gameState: gs, + ), + ), + 'amdAddMinusOne': CommandDescriptor( + 'amdAddMinusOne', + (gs, args) => AmdAddMinusOneCommand( + _str('amdAddMinusOne', 'name', args), + gameState: gs, + ), + ), + 'amdCassandraSpecial': CommandDescriptor( + 'amdCassandraSpecial', + (gs, args) => AMDCassandraSpecialCommand( + _str('amdCassandraSpecial', 'deckId', args), + _bool('amdCassandraSpecial', 'on', args), + gameState: gs, + ), + ), + 'amdImbue1': CommandDescriptor( + 'amdImbue1', + (gs, args) => AMDImbue1Command(gameState: gs), + ), + 'amdImbue2': CommandDescriptor( + 'amdImbue2', + (gs, args) => AMDImbue2Command(gameState: gs), + ), + 'amdRemoveImbue': CommandDescriptor( + 'amdRemoveImbue', + (gs, args) => AMDRemoveImbueCommand(gameState: gs), + ), + 'amdRemoveMinus1': CommandDescriptor( + 'amdRemoveMinus1', + (gs, args) => AMDRemoveMinus1Command( + _str('amdRemoveMinus1', 'name', args), + gameState: gs, + ), + ), + 'amdRemoveMinus2': CommandDescriptor( + 'amdRemoveMinus2', + (gs, args) => AMDRemoveMinus2Command( + _bool('amdRemoveMinus2', 'allies', args), + gameState: gs, + ), + ), + 'amdRemovePlus0': CommandDescriptor( + 'amdRemovePlus0', + (gs, args) => AmdRemovePlus0Command( + _str('amdRemovePlus0', 'name', args), + _bool('amdRemovePlus0', 'remove', args), + gameState: gs, + ), + ), + 'amdReveal': CommandDescriptor( + 'amdReveal', + (gs, args) => AMDRevealCommand( + amount: _int('amdReveal', 'amount', args), + name: _str('amdReveal', 'name', args), + gameState: gs, + ), + ), + 'badOmen': CommandDescriptor( + 'badOmen', + (gs, args) => + BadOmenCommand(_bool('badOmen', 'allies', args), gameState: gs), + ), + 'changeBless': CommandDescriptor( + 'changeBless', + (gs, args) => ChangeBlessCommand( + _int('changeBless', 'change', args), + _str('changeBless', 'figureId', args), + _strOr('changeBless', 'ownerId', args), + gameState: gs, + ), + ), + 'changeCurse': CommandDescriptor( + 'changeCurse', + (gs, args) => ChangeCurseCommand( + _int('changeCurse', 'change', args), + _str('changeCurse', 'figureId', args), + _strOr('changeCurse', 'ownerId', args), + gameState: gs, + ), + ), + 'changeEmpower': CommandDescriptor( + 'changeEmpower', + (gs, args) => ChangeEmpowerCommand( + _int('changeEmpower', 'change', args), + _str('changeEmpower', 'gfx', args), + _str('changeEmpower', 'figureId', args), + _strOr('changeEmpower', 'ownerId', args), + gameState: gs, + ), + ), + 'changeEnfeeble': CommandDescriptor( + 'changeEnfeeble', + (gs, args) => ChangeEnfeebleCommand( + _int('changeEnfeeble', 'change', args), + _str('changeEnfeeble', 'gfx', args), + _str('changeEnfeeble', 'figureId', args), + _strOr('changeEnfeeble', 'ownerId', args), + gameState: gs, + ), + ), + 'changeHealth': CommandDescriptor( + 'changeHealth', + (gs, args) => ChangeHealthCommand( + _int('changeHealth', 'change', args), + _str('changeHealth', 'figureId', args), + _strOr('changeHealth', 'ownerId', args), + gameState: gs, + ), + ), + 'changeMaxHealth': CommandDescriptor( + 'changeMaxHealth', + (gs, args) => ChangeMaxHealthCommand( + _int('changeMaxHealth', 'change', args), + _str('changeMaxHealth', 'figureId', args), + _strOr('changeMaxHealth', 'ownerId', args), + gameState: gs, + ), + ), + 'changeName': CommandDescriptor( + 'changeName', + (gs, args) => ChangeNameCommand( + _str('changeName', 'name', args), + _str('changeName', 'characterId', args), + gameState: gs, + ), + ), + 'changeXP': CommandDescriptor( + 'changeXP', + (gs, args) => ChangeXPCommand( + _int('changeXP', 'change', args), + _str('changeXP', 'figureId', args), + _strOr('changeXP', 'ownerId', args), + gameState: gs, + ), + ), + 'clearUnlockedClasses': CommandDescriptor( + 'clearUnlockedClasses', + (gs, args) => ClearUnlockedClassesCommand(), + ), + 'corrosiveSpew': CommandDescriptor( + 'corrosiveSpew', + (gs, args) => CorrosiveSpewCommand(gameState: gs), + ), + 'donateCSSanctuary': CommandDescriptor( + 'donateCSSanctuary', + (gs, args) => DonateCSSanctuaryCommand( + _str('donateCSSanctuary', 'characterId', args), + gameState: gs, + ), + ), + 'draw': CommandDescriptor('draw', (gs, args) => DrawCommand(gameState: gs)), + 'drawAbilityCard': CommandDescriptor( + 'drawAbilityCard', + (gs, args) => + DrawAbilityCardCommand(_str('drawAbilityCard', 'ownerId', args)), + ), + 'drawLootCard': CommandDescriptor( + 'drawLootCard', + (gs, args) => DrawLootCardCommand(gameState: gs), + ), + 'drawModifierCard': CommandDescriptor( + 'drawModifierCard', + (gs, args) => DrawModifierCardCommand( + _str('drawModifierCard', 'name', args), + gameState: gs, + ), + ), + 'enhanceLootCard': CommandDescriptor( + 'enhanceLootCard', + (gs, args) => EnhanceLootCardCommand( + _int('enhanceLootCard', 'id', args), + _int('enhanceLootCard', 'value', args), + _str('enhanceLootCard', 'resourceType', args), + gameState: gs, + ), + ), + 'hideAllyDeck': CommandDescriptor( + 'hideAllyDeck', + (gs, args) => HideAllyDeckCommand(), + ), + 'iceWraithChangeForm': CommandDescriptor( + 'iceWraithChangeForm', + (gs, args) => IceWraithChangeFormCommand( + _bool('iceWraithChangeForm', 'isElite', args), + _strOr('iceWraithChangeForm', 'ownerId', args), + _str('iceWraithChangeForm', 'figureId', args), + gameState: gs, + ), + ), + 'imbueElement': CommandDescriptor( + 'imbueElement', + (gs, args) => ImbueElementCommand( + _elements('imbueElement', 'element', args), + _bool('imbueElement', 'half', args), + gameState: gs, + ), + ), + 'loadCharacterSave': CommandDescriptor( + 'loadCharacterSave', + (gs, args) => LoadCharacterSaveCommand( + _str('loadCharacterSave', 'saveName', args), + _str('loadCharacterSave', 'saveData', args), + gameState: gs, + ), + ), + 'loadSave': CommandDescriptor( + 'loadSave', + (gs, args) => LoadSaveCommand( + _str('loadSave', 'saveName', args), + _str('loadSave', 'saveData', args), + gameState: gs, + ), + ), + // GameData and Settings are injected, never wire args. + 'nextRound': CommandDescriptor( + 'nextRound', + (gs, args) => NextRoundCommand( + gameState: gs, + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ), + ), + 'removeAMDCard': CommandDescriptor( + 'removeAMDCard', + (gs, args) => RemoveAMDCardCommand( + index: _int('removeAMDCard', 'index', args), + name: _str('removeAMDCard', 'name', args), + fromDrawPile: _boolOr('removeAMDCard', 'fromDrawPile', args, false), + gameState: gs, + ), + ), + // `deck` + `nr` resolve the live card model from the current ability decks + // (draw pile, then discard pile), mirroring the command's own execute(). + 'removeCard': CommandDescriptor( + 'removeCard', + (gs, args) => RemoveCardCommand( + _abilityCard( + gs, + 'removeCard', + _str('removeCard', 'deck', args), + _int('removeCard', 'nr', args), + ), + gameState: gs, + ), + ), + // The reference constructor takes `List<Character> names`; the wire takes + // `ids` (List<String>) and resolves the live Character objects by id. An + // empty result is not an error (the reference tolerates no-ops). + 'removeCharacter': CommandDescriptor( + 'removeCharacter', + (gs, args) => RemoveCharacterCommand( + _characters(gs, _strList('removeCharacter', 'ids', args)), + gameState: gs, + ), + ), + 'removeCondition': CommandDescriptor( + 'removeCondition', + (gs, args) => RemoveConditionCommand( + _condition('removeCondition', 'condition', args), + _str('removeCondition', 'figureId', args), + _strOr('removeCondition', 'ownerId', args), + gameState: gs, + ), + ), + 'removeCSPartyCard': CommandDescriptor( + 'removeCSPartyCard', + (gs, args) => RemoveCSPartyCardCommand( + _str('removeCSPartyCard', 'characterId', args), + gameState: gs, + ), + ), + 'removeCSSanctuaryDonation': CommandDescriptor( + 'removeCSSanctuaryDonation', + (gs, args) => RemoveCSSanctuaryDonationCommand( + _str('removeCSSanctuaryDonation', 'characterId', args), + gameState: gs, + ), + ), + // The reference constructor takes `List<Monster> names`; the wire takes + // `ids` (List<String>) and resolves the live Monster objects by id. An + // empty result is not an error (the reference tolerates no-ops). + 'removeMonster': CommandDescriptor( + 'removeMonster', + (gs, args) => RemoveMonsterCommand( + _monsters(gs, _strList('removeMonster', 'ids', args)), + gameState: gs, + ), + ), + 'removeNoteRow': CommandDescriptor( + 'removeNoteRow', + (gs, args) => RemoveNoteRowCommand( + _str('removeNoteRow', 'noteId', args), + gameState: gs, + ), + ), + 'removeSpecialLootCard': CommandDescriptor( + 'removeSpecialLootCard', + (gs, args) => RemoveSpecialLootCardCommand( + _int('removeSpecialLootCard', 'nr', args), + gameState: gs, + ), + ), + 'reorderAbilityList': CommandDescriptor( + 'reorderAbilityList', + (gs, args) => ReorderAbilityListCommand( + _str('reorderAbilityList', 'deck', args), + _int('reorderAbilityList', 'newIndex', args), + _int('reorderAbilityList', 'oldIndex', args), + gameState: gs, + ), + ), + 'reorderList': CommandDescriptor( + 'reorderList', + (gs, args) => ReorderListCommand( + _int('reorderList', 'newIndex', args), + _int('reorderList', 'oldIndex', args), + gameState: gs, + ), + ), + 'reorderModifierList': CommandDescriptor( + 'reorderModifierList', + (gs, args) => ReorderModifierListCommand( + _int('reorderModifierList', 'newIndex', args), + _int('reorderModifierList', 'oldIndex', args), + _str('reorderModifierList', 'name', args), + gameState: gs, + ), + ), + 'returnLootCard': CommandDescriptor( + 'returnLootCard', + (gs, args) => ReturnLootCardCommand( + _bool('returnLootCard', 'top', args), + gameState: gs, + ), + ), + 'returnModifierCard': CommandDescriptor( + 'returnModifierCard', + (gs, args) => + ReturnModifierCardCommand(_str('returnModifierCard', 'name', args)), + ), + 'returnRemovedAMDCard': CommandDescriptor( + 'returnRemovedAMDCard', + (gs, args) => ReturnRemovedAMDCardCommand( + index: _int('returnRemovedAMDCard', 'index', args), + name: _str('returnRemovedAMDCard', 'name', args), + toDrawPile: _boolOr('returnRemovedAMDCard', 'toDrawPile', args, false), + gameState: gs, + ), + ), + 'setAllyDeckInOgGloom': CommandDescriptor( + 'setAllyDeckInOgGloom', + (gs, args) => SetAllyDeckInOgGloomCommand( + _bool('setAllyDeckInOgGloom', 'set', args), + gameState: gs, + ), + ), + 'setAsSummon': CommandDescriptor( + 'setAsSummon', + (gs, args) => SetAsSummonCommand( + _bool('setAsSummon', 'summoned', args), + _str('setAsSummon', 'figureId', args), + _strOr('setAsSummon', 'ownerId', args), + gameState: gs, + ), + ), + 'setAutoLevelAdjust': CommandDescriptor( + 'setAutoLevelAdjust', + (gs, args) => SetAutoLevelAdjustCommand( + _bool('setAutoLevelAdjust', 'on', args), + gameState: gs, + ), + ), + 'setCampaign': CommandDescriptor( + 'setCampaign', + (gs, args) => SetCampaignCommand(_str('setCampaign', 'campaign', args)), + ), + 'setCharacterLevel': CommandDescriptor( + 'setCharacterLevel', + (gs, args) => SetCharacterLevelCommand( + _int('setCharacterLevel', 'level', args), + _str('setCharacterLevel', 'characterId', args), + ), + ), + 'setDifficulty': CommandDescriptor( + 'setDifficulty', + (gs, args) => SetDifficultyCommand( + _int('setDifficulty', 'difficulty', args), + gameState: gs, + ), + ), + 'setFigureNote': CommandDescriptor( + 'setFigureNote', + (gs, args) => SetFigureNoteCommand( + _str('setFigureNote', 'note', args), + _str('setFigureNote', 'figureId', args), + gameState: gs, + ), + ), + 'setInit': CommandDescriptor( + 'setInit', + (gs, args) => SetInitCommand( + _str('setInit', 'characterId', args), + _int('setInit', 'init', args), + gameState: gs, + ), + ), + 'setLevel': CommandDescriptor( + 'setLevel', + (gs, args) => SetLevelCommand( + _int('setLevel', 'level', args), + _strOr('setLevel', 'monsterId', args), + ), + ), + // `cardId` resolves the live [LootCard] from the loot deck (draw pile, + // discard pile, and the material/herb pools). + 'setLootOwner': CommandDescriptor( + 'setLootOwner', + (gs, args) => SetLootOwnerCommand( + _str('setLootOwner', 'ownerId', args), + _lootCard(gs, 'setLootOwner', _int('setLootOwner', 'cardId', args)), + ), + ), + 'setNoteRowColor': CommandDescriptor( + 'setNoteRowColor', + (gs, args) => SetNoteRowColorCommand( + _int('setNoteRowColor', 'color', args), + _str('setNoteRowColor', 'noteId', args), + gameState: gs, + ), + ), + 'setNoteRowLink': CommandDescriptor( + 'setNoteRowLink', + (gs, args) => SetNoteRowLinkCommand( + _str('setNoteRowLink', 'noteId', args), + _str('setNoteRowLink', 'linkedId', args), + _int('setNoteRowLink', 'standeeNr', args), + gameState: gs, + ), + ), + 'setNoteRowText': CommandDescriptor( + 'setNoteRowText', + (gs, args) => SetNoteRowTextCommand( + _str('setNoteRowText', 'text', args), + _str('setNoteRowText', 'noteId', args), + gameState: gs, + ), + ), + 'setScenario': CommandDescriptor( + 'setScenario', + (gs, args) => SetScenarioCommand( + _str('setScenario', 'scenario', args), + _bool('setScenario', 'section', args), + gameState: gs, + ), + ), + 'setSolo': CommandDescriptor( + 'setSolo', + (gs, args) => SetSoloCommand(_bool('setSolo', 'solo', args)), + ), + 'showAllyDeck': CommandDescriptor( + 'showAllyDeck', + (gs, args) => ShowAllyDeckCommand(), + ), + 'shuffleAbilityCard': CommandDescriptor( + 'shuffleAbilityCard', + (gs, args) => + ShuffleAbilityCardCommand(_str('shuffleAbilityCard', 'ownerId', args)), + ), + 'shuffleAMDCard': CommandDescriptor( + 'shuffleAMDCard', + (gs, args) => ShuffleAMDCardCommand( + _str('shuffleAMDCard', 'name', args), + gameState: gs, + ), + ), + 'shuffleDrawnAbilityCard': CommandDescriptor( + 'shuffleDrawnAbilityCard', + (gs, args) => ShuffleDrawnAbilityCardCommand( + _str('shuffleDrawnAbilityCard', 'deck', args), + ), + ), + // Settings is injected, never a wire arg. + 'trackStandees': CommandDescriptor( + 'trackStandees', + (gs, args) => TrackStandeesCommand( + _bool('trackStandees', 'track', args), + gameState: gs, + settings: getIt<Settings>(), + ), + ), + 'turnDone': CommandDescriptor( + 'turnDone', + (gs, args) => TurnDoneCommand(_str('turnDone', 'id', args), gameState: gs), + ), + 'unlockSpecial': CommandDescriptor( + 'unlockSpecial', + (gs, args) => + UnlockSpecialCommand(_str('unlockSpecial', 'id', args), gameState: gs), + ), + 'useElement': CommandDescriptor( + 'useElement', + (gs, args) => UseElementCommand( + _elements('useElement', 'element', args), + gameState: gs, + ), + ), + 'useFHPerks': CommandDescriptor( + 'useFHPerks', + (gs, args) => UseFHPerksCommand(_str('useFHPerks', 'characterId', args)), + ), +}; + +/// Wire name of each registered command's runtime type, for [commandName]. +final Map<Type, String> _nameByType = { + ActivateMonsterTypeCommand: 'activateMonsterType', + AddCharacterCommand: 'addCharacter', + AddConditionCommand: 'addCondition', + AddCSPartyCardCommand: 'addCSPartyCard', + AddFactionCardCommand: 'addFactionCard', + AddLootCardCommand: 'addLootCard', + AddMonsterCommand: 'addMonster', + AddNoteRowCommand: 'addNoteRow', + AddPerkCommand: 'addPerk', + AddSpecialLootCardCommand: 'addSpecialLootCard', + AddStandeeCommand: 'addStandee', + AmdAddMinusOneCommand: 'amdAddMinusOne', + AMDCassandraSpecialCommand: 'amdCassandraSpecial', + AMDImbue1Command: 'amdImbue1', + AMDImbue2Command: 'amdImbue2', + AMDRemoveImbueCommand: 'amdRemoveImbue', + AMDRemoveMinus1Command: 'amdRemoveMinus1', + AMDRemoveMinus2Command: 'amdRemoveMinus2', + AmdRemovePlus0Command: 'amdRemovePlus0', + AMDRevealCommand: 'amdReveal', + BadOmenCommand: 'badOmen', + ChangeBlessCommand: 'changeBless', + ChangeCurseCommand: 'changeCurse', + ChangeEmpowerCommand: 'changeEmpower', + ChangeEnfeebleCommand: 'changeEnfeeble', + ChangeHealthCommand: 'changeHealth', + ChangeMaxHealthCommand: 'changeMaxHealth', + ChangeNameCommand: 'changeName', + ChangeXPCommand: 'changeXP', + ClearUnlockedClassesCommand: 'clearUnlockedClasses', + CorrosiveSpewCommand: 'corrosiveSpew', + DonateCSSanctuaryCommand: 'donateCSSanctuary', + DrawAbilityCardCommand: 'drawAbilityCard', + DrawCommand: 'draw', + DrawLootCardCommand: 'drawLootCard', + DrawModifierCardCommand: 'drawModifierCard', + EnhanceLootCardCommand: 'enhanceLootCard', + HideAllyDeckCommand: 'hideAllyDeck', + IceWraithChangeFormCommand: 'iceWraithChangeForm', + ImbueElementCommand: 'imbueElement', + LoadCharacterSaveCommand: 'loadCharacterSave', + LoadSaveCommand: 'loadSave', + NextRoundCommand: 'nextRound', + RemoveAMDCardCommand: 'removeAMDCard', + RemoveCardCommand: 'removeCard', + RemoveCharacterCommand: 'removeCharacter', + RemoveConditionCommand: 'removeCondition', + RemoveCSPartyCardCommand: 'removeCSPartyCard', + RemoveCSSanctuaryDonationCommand: 'removeCSSanctuaryDonation', + RemoveMonsterCommand: 'removeMonster', + RemoveNoteRowCommand: 'removeNoteRow', + RemoveSpecialLootCardCommand: 'removeSpecialLootCard', + ReorderAbilityListCommand: 'reorderAbilityList', + ReorderListCommand: 'reorderList', + ReorderModifierListCommand: 'reorderModifierList', + ReturnLootCardCommand: 'returnLootCard', + ReturnModifierCardCommand: 'returnModifierCard', + ReturnRemovedAMDCardCommand: 'returnRemovedAMDCard', + SetAllyDeckInOgGloomCommand: 'setAllyDeckInOgGloom', + SetAsSummonCommand: 'setAsSummon', + SetAutoLevelAdjustCommand: 'setAutoLevelAdjust', + SetCampaignCommand: 'setCampaign', + SetCharacterLevelCommand: 'setCharacterLevel', + SetDifficultyCommand: 'setDifficulty', + SetFigureNoteCommand: 'setFigureNote', + SetInitCommand: 'setInit', + SetLevelCommand: 'setLevel', + SetLootOwnerCommand: 'setLootOwner', + SetNoteRowColorCommand: 'setNoteRowColor', + SetNoteRowLinkCommand: 'setNoteRowLink', + SetNoteRowTextCommand: 'setNoteRowText', + SetScenarioCommand: 'setScenario', + SetSoloCommand: 'setSolo', + ShowAllyDeckCommand: 'showAllyDeck', + ShuffleAbilityCardCommand: 'shuffleAbilityCard', + ShuffleAMDCardCommand: 'shuffleAMDCard', + ShuffleDrawnAbilityCardCommand: 'shuffleDrawnAbilityCard', + TrackStandeesCommand: 'trackStandees', + TurnDoneCommand: 'turnDone', + UnlockSpecialCommand: 'unlockSpecial', + UseElementCommand: 'useElement', + UseFHPerksCommand: 'useFHPerks', +}; + +// --- arg helpers ----------------------------------------------------------- +// +// Every helper throws [CommandRegistryError] with a message naming the +// command and the offending arg. An arg that is missing or JSON `null` is +// treated as "not provided" for optional parameters. + +Object _requiredArg(String command, String key, Map<String, dynamic> args) { + if (!args.containsKey(key)) { + throw CommandRegistryError( + 'Command "$command" is missing required argument "$key"', + ); + } + return args[key]!; +} + +Object? _optionalArg(String command, String key, Map<String, dynamic> args) { + if (!args.containsKey(key)) return null; + return args[key]; +} + +Never _typeError(String command, String key, String expected, Object actual) { + throw CommandRegistryError( + 'Command "$command" argument "$key" must be $expected, ' + 'got ${actual.runtimeType}', + ); +} + +String _str(String command, String key, Map<String, dynamic> args) { + final value = _requiredArg(command, key, args); + if (value is! String) _typeError(command, key, 'a String', value); + return value; +} + +String? _strOr(String command, String key, Map<String, dynamic> args) { + final value = _optionalArg(command, key, args); + if (value == null) return null; + if (value is! String) _typeError(command, key, 'a String', value); + return value; +} + +int _int(String command, String key, Map<String, dynamic> args) { + final value = _requiredArg(command, key, args); + if (value is! int) _typeError(command, key, 'an int', value); + return value; +} + +int? _intOr(String command, String key, Map<String, dynamic> args) { + final value = _optionalArg(command, key, args); + if (value == null) return null; + if (value is! int) _typeError(command, key, 'an int', value); + return value; +} + +bool _bool(String command, String key, Map<String, dynamic> args) { + final value = _requiredArg(command, key, args); + if (value is! bool) _typeError(command, key, 'a bool', value); + return value; +} + +bool _boolOr( + String command, + String key, + Map<String, dynamic> args, + bool defaultValue, +) { + final value = _optionalArg(command, key, args); + if (value == null) return defaultValue; + if (value is! bool) _typeError(command, key, 'a bool', value); + return value; +} + +List<String> _strList(String command, String key, Map<String, dynamic> args) { + final value = _requiredArg(command, key, args); + if (value is! List) _typeError(command, key, 'a List', value); + final result = <String>[]; + int i = 0; + for (final item in value) { + if (item is! String) _typeError(command, '$key[$i]', 'a String', item); + result.add(item); + i++; + } + return result; +} + +Map<String, dynamic> _map( + String command, + String key, + Map<String, dynamic> args, +) { + final value = _requiredArg(command, key, args); + if (value is! Map) _typeError(command, key, 'a JSON object', value); + return Map<String, dynamic>.from(value); +} + +Map<String, dynamic>? _mapOr( + String command, + String key, + Map<String, dynamic> args, +) { + final value = _optionalArg(command, key, args); + if (value == null) return null; + if (value is! Map) _typeError(command, key, 'a JSON object', value); + return Map<String, dynamic>.from(value); +} + +/// Resolves an enum wire arg (a name string) to a value of [values]. +T _enumValue<T extends Enum>( + String command, + String key, + Map<String, dynamic> args, + List<T> values, +) { + final name = _str(command, key, args); + for (final value in values) { + if (value.name == name) return value; + } + throw CommandRegistryError( + 'Command "$command" argument "$key" has invalid value "$name"; ' + 'expected one of: ${values.map((e) => e.name).join(', ')}', + ); +} + +Condition _condition(String command, String key, Map<String, dynamic> args) => + _enumValue(command, key, args, Condition.values); + +Elements _elements(String command, String key, Map<String, dynamic> args) => + _enumValue(command, key, args, Elements.values); + +MonsterType _monsterType( + String command, + String key, + Map<String, dynamic> args, +) => _enumValue(command, key, args, MonsterType.values); + +/// Resolves the optional `summon` arg into a [SummonData]. +SummonData? _summonData(String command, Map<String, dynamic> args) { + final value = _mapOr(command, 'summon', args); + if (value == null) return null; + return SummonData( + _int(command, 'summon.standeeNr', value), + _str(command, 'summon.name', value), + _int(command, 'summon.health', value), + _int(command, 'summon.move', value), + _int(command, 'summon.attack', value), + _int(command, 'summon.range', value), + _str(command, 'summon.gfx', value), + ); +} + +/// Resolves the `noteRow` arg into a [NoteRow]. All five keys +/// `{id, text, color, linkedId, standeeNr}` are required; `id` is a +/// client-generated unique string. +NoteRow _noteRow(String command, Map<String, dynamic> args) { + final value = _map(command, 'noteRow', args); + _str(command, 'noteRow.id', value); + _str(command, 'noteRow.text', value); + _int(command, 'noteRow.color', value); + _str(command, 'noteRow.linkedId', value); + _int(command, 'noteRow.standeeNr', value); + return NoteRow.fromJson(value); +} + +/// Finds the live [LootCard] with [cardId] in the loot deck: the draw pile, +/// the discard pile, and the material/herb pools (pool cards are the same +/// instances that enter the deck, so this covers every live card). +LootCard _lootCard(GameState gameState, String command, int cardId) { + final deck = gameState.lootDeck; + final all = <LootCard>[ + ...deck.drawPileContents, + ...deck.discardPileContents, + ...deck.coinPool, + ...deck.lumberPool, + ...deck.hidePool, + ...deck.metalPool, + ...deck.corpsecapPool, + ...deck.arrowvinePool, + ...deck.flamefruitPool, + ...deck.axenutPool, + ...deck.rockrootPool, + ...deck.snowthistlePool, + ]; + for (final card in all) { + if (card.id == cardId) return card; + } + throw CommandRegistryError( + 'Command "$command": no loot card with id $cardId in the loot deck', + ); +} + +/// Finds the live ability card with [nr] in the ability deck named +/// [deckName] (draw pile, then discard pile) — the same lookup the command's +/// own execute() does. +MonsterAbilityCardModel _abilityCard( + GameState gameState, + String command, + String deckName, + int nr, +) { + for (final deck in gameState.currentAbilityDecks) { + if (deck.name != deckName) continue; + for (final card in deck.drawPileContents) { + if (card.nr == nr) return card; + } + for (final card in deck.discardPileContents) { + if (card.nr == nr) return card; + } + } + throw CommandRegistryError( + 'Command "$command": no ability card with nr $nr in deck "$deckName"', + ); +} + +/// Resolves wire `ids` (character ids) to the live [Character] objects in the +/// current list. An empty result is not an error. +List<Character> _characters(GameState gameState, List<String> ids) { + return gameState.currentList + .where((item) => item is Character && ids.contains(item.id)) + .cast<Character>() + .toList(); +} + +/// Resolves wire `ids` (monster ids) to the live [Monster] objects in the +/// current list. An empty result is not an error. +List<Monster> _monsters(GameState gameState, List<String> ids) { + return gameState.currentList + .where((item) => item is Monster && ids.contains(item.id)) + .cast<Monster>() + .toList(); +} |
