summaryrefslogtreecommitdiff
path: root/server/lib/core/action_handler.dart
blob: 8bf6655e9b3be001e6900dd0aa47ba7e3a8afd29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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();
      }
      lastEvent = const NoEvent();
      // The broadcast travels the undone action's description (as the
      // reference's undo envelope does) but the *post-decrement* index: the
      // reference reports the pre-decrement index because its clients keep
      // local state and reconcile it; our stateless web clients take the
      // wire index at face value, so it must equal the state position.
      final undoneDescription = commandIndex < _commandDescriptions.length
          ? _commandDescriptions[commandIndex]
          : '';
      commandIndex--;
      if (saveState != null) _sendState('undo', description: undoneDescription);
    }
  }

  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.
  /// [description] overrides the one at the current index (the undo path
  /// sends the undone action's name; the redo path sends the redone one).
  void _sendState(String action, {String? description}) {
    final idx = commandIndex;
    // idx -1 is the baseline (empty history). The reference skips the send
    // there because its clients keep local state; the stateless web clients
    // only ever see what the server pushes, so the baseline goes out too.
    if (idx >= -1 && idx < _commandDescriptions.length) {
      final desc = description ?? (idx >= 0 ? _commandDescriptions[idx] : '');
      _log.info('server sends, $action index: $idx, description:$desc');
      onAction?.call(idx, desc, 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
    final String description = command.describe();
    final 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;
      }
    }
  }
}