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/action_handler.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/action_handler.dart')
| -rw-r--r-- | server/lib/core/action_handler.dart | 179 |
1 files changed, 179 insertions, 0 deletions
diff --git a/server/lib/core/action_handler.dart b/server/lib/core/action_handler.dart new file mode 100644 index 0000000..2c73bb1 --- /dev/null +++ b/server/lib/core/action_handler.dart @@ -0,0 +1,179 @@ +import 'package:logging/logging.dart'; + +import 'game_event.dart'; +import 'state/game_state.dart'; + +final _log = Logger('ActionHandler'); + +/// Executes commands and maintains undo/redo history. +/// +/// Server port of the reference app's `ActionHandler`: the `ValueNotifier`s +/// are plain fields, and the server/client branching is gone — this process +/// is always the server, so every action runs locally, saves, and notifies +/// the (Phase 2) broadcast hook [onAction]. +class ActionHandler { + int commandIndex = -1; + final List<Command?> _commands = []; + final List<String> _commandDescriptions = []; + final List<GameSaveState?> _gameSaveStates = []; + + List<Command?> get commands => List.unmodifiable(_commands); + List<String> get commandDescriptions => + List.unmodifiable(_commandDescriptions); + List<GameSaveState?> get gameSaveStates => List.unmodifiable(_gameSaveStates); + + /// The event produced by the most recent state transition. + /// + /// Set before [commandIndex] changes so that listeners can read the + /// correct event during their rebuild. + GameEvent lastEvent = const NoEvent(); + + final int maxUndo = 250; + + final GameState _gameState; + + /// Set by the network layer (Phase 2); null in tests. + /// + /// Invoked after every action/undo/redo with the new command index, the + /// action's `describe()` string, and the serialized [GameEvent] — the + /// pieces the reference app put into its `{i, d, e, s}` envelope. + void Function(int index, String description, String eventJson)? onAction; + + ActionHandler({required GameState gameState}) : _gameState = gameState; + + /// Resets all command/description/save-state history to a clean slate, + /// keeping only the most recent save state as the baseline. + void resetCommandHistory() { + _commands.clear(); + _commandDescriptions.clear(); + if (_gameSaveStates.length > 1) { + _gameSaveStates.removeRange(0, _gameSaveStates.length - 1); + } + } + + /// Clears only the local commands list. + void clearLocalCommands() { + _commands.clear(); + } + + /// Inserts a description received from the network at [index]. + void insertReceivedDescription(int index, String description) { + _commandDescriptions.insert(index, description); + } + + /// Appends a save-state snapshot. Called by [GameState.save] and [GameState.load]. + void addSaveState(GameSaveState state) { + _gameSaveStates.add(state); + } + + void updateAllUI() { + _gameState.notifyListeners(); + _gameState.notifyAllMonsterInstances(); + } + + Command getCurrent() { + final cmd = _commands[commandIndex]; + if (cmd == null) throw StateError('No command at index $commandIndex'); + return cmd; + } + + void undo() { + if (commandIndex >= 0) { + // Guard against out-of-bounds access: in the server multiplayer path + // updateStateFromMessage sets commandIndex directly then calls save() + // once, which can leave commandIndex >= gameSaveStates.length. + final saveState = commandIndex < _gameSaveStates.length + ? _gameSaveStates[commandIndex] + : null; + if (saveState != null) { + saveState.load(_gameState); + saveState.saveToDisk(_gameState); + updateAllUI(); + _sendState('undo'); + } + lastEvent = const NoEvent(); + commandIndex--; + } + } + + void redo() { + if (commandIndex < _commandDescriptions.length - 1) { + lastEvent = const NoEvent(); + commandIndex++; + final nextIdx = commandIndex + 1; + final nextState = (nextIdx < _gameSaveStates.length) + ? _gameSaveStates[nextIdx] + : null; + if (nextState == null) return; // save state evicted by maxUndo + nextState.load(_gameState); + nextState.saveToDisk(_gameState); + //also run generic update ui function + updateAllUI(); + } + _sendState('redo'); + } + + /// Broadcasts the current command index + description after an undo/redo, + /// mirroring the reference app's server-side `StateEnvelope` send. + void _sendState(String action) { + final idx = commandIndex; + if (idx >= 0 && idx < _commandDescriptions.length) { + _log.info( + 'server sends, $action index: $idx, description:${_commandDescriptions[idx]}', + ); + onAction?.call( + idx, + _commandDescriptions[idx], + const NoEvent().toJsonString(), + ); + } + } + + void action(Command command) { + command.execute(); + if (_commands.length > commandIndex) { + _commands.insert(commandIndex + 1, command); + _commandDescriptions.insert(commandIndex + 1, command.describe()); + } else { + _commands.add(command); + _commandDescriptions.add(command.describe()); + } + + // Set event before commandIndex changes so listener callbacks see the + // correct value. + lastEvent = command.event; + commandIndex++; + + //remove possible redo list + if (_commands.length - 1 > commandIndex) { + _commands.removeRange(commandIndex + 1, _commands.length); + _commandDescriptions.removeRange( + commandIndex + 1, + _commandDescriptions.length, + ); + } + if (_gameSaveStates.length > commandIndex + 1) { + //remove future game states + _gameSaveStates.removeRange(commandIndex + 1, _gameSaveStates.length); + } + + _gameState.save(); //save after each action + + //send last game state if connected + String description = command.describe(); + String eventJson = command.event.toJsonString(); + _log.info('server sends, index: $commandIndex, description:$description'); + onAction?.call(commandIndex, description, eventJson); + + //TODO: this is breaking if command index is not in sync with commands. and in connected state. + //really need to go over this again: do we really need to save commands at all, or are save states + descriptions enough also for offline? + if (commandIndex >= maxUndo) { + if (_commands.length > commandIndex) { + _commands[commandIndex - maxUndo] = null; + } + if (_gameSaveStates.length > commandIndex - maxUndo) { + _gameSaveStates[commandIndex - maxUndo] = null; + } + } + } +} |
