diff options
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; + } + } + } +} |
