summaryrefslogtreecommitdiff
path: root/server/lib/core/state/game_state.dart
blob: fc2521e5854b2bc020b167f21e74a749a2c9f4b6 (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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import 'dart:collection';
import 'dart:convert';
import 'dart:math';

import 'package:built_collection/built_collection.dart';
import 'package:collection/collection.dart';
import 'package:logging/logging.dart';

import 'package:x_haven_server/core/models/character_class.dart';
import 'package:x_haven_server/core/models/monster.dart';
import 'package:x_haven_server/core/models/monster_ability.dart';
import 'package:x_haven_server/core/models/room.dart';
import 'package:x_haven_server/core/models/scenario.dart';

import '../action_handler.dart';
import '../card_stack.dart';
import '../commands/add_standee_command.dart';
import '../enums.dart';
import '../game_data.dart';
import '../game_event.dart';
import '../game_methods.dart';
import '../save_store.dart';
import '../service_locator.dart';
import '../settings.dart';
import '../stat_calculator.dart';

part "../methods/character_methods.dart";
part "../methods/deck_methods.dart";
part "../methods/element_methods.dart";
part "../methods/game_util_methods.dart";
part "../methods/monster_methods.dart";
part "../methods/round_methods.dart";
part "../methods/scenario_methods.dart";
part "character.dart";
part "character_state.dart";
part "figure_state.dart";
part "game_save_state.dart";
part "list_item_data.dart";
part "loot_deck_state.dart";
part "modifier_deck.dart";
part "monster.dart";
part "note_row.dart";
part "monster_ability_state.dart";
part "monster_instance.dart";
part "sanctuary_deck.dart";

// ignore_for_file: library_private_types_in_public_api

/// Central game state holder.
///
/// Server port of the reference app's `GameState`: the `ValueNotifier`s are
/// plain fields (state is pushed to clients over the network in Phase 2
/// instead of notifying local listeners), but the structure, part-file
/// layout, `_StateModifier` token, and serialization are unchanged.
class GameState {
  late final ActionHandler _actionHandler;

  //state
  String _currentCampaign = "Jaws of the Lion";
  int _round = 1;
  int _totalRounds = 1;
  RoundState _roundState = RoundState.chooseInitiative;
  int _level = 1;
  bool _solo = false;
  bool _autoScenarioLevel = false;
  bool _allyDeckInOGGloom = true;
  int _difficulty = 1;
  String _scenario = "";
  String _toastMessage = "";
  bool _showAllyDeck = false;
  List<RoomMonsterData>? pendingAutoAddDialog = null;

  List<String> _scenarioSectionsAdded = [];
  List<SpecialRule> _scenarioSpecialRules = [];
  int _scenarioSectionsVersion = 0;
  List<ListItemData> _currentList = []; //has both monsters and characters
  final List<MonsterAbilityState> _currentAbilityDecks =
      <MonsterAbilityState>[];
  final Map<Elements, ElementState> _elementState = HashMap();
  Set<String> _unlockedClasses = {};
  int _unlockedClassesVersion = 0;

  LootDeck _lootDeck = LootDeck.empty(); //loot deck for current scenario
  final ModifierDeck _modifierDeck = ModifierDeck("");
  final ModifierDeck _modifierDeckAllies = ModifierDeck("allies");
  SanctuaryDeck _sanctuaryDeck = SanctuaryDeck();

  String get currentCampaign => _currentCampaign;
  int get round => _round;
  int get totalRounds => _totalRounds;
  RoundState get roundState => _roundState;
  int get level => _level;
  bool get solo => _solo;
  bool get autoScenarioLevel => _autoScenarioLevel;
  bool get allyDeckInOGGloom => _allyDeckInOGGloom;
  int get difficulty => _difficulty;
  String get toastMessage => _toastMessage;
  String get scenario => _scenario;

  /// Direct set for tests (mirrors the reference app's writable
  /// `ValueNotifier<String>` scenario, which its tests wrote to in order to
  /// bypass `SetScenarioCommand`'s side effects).
  set scenario(String value) => _scenario = value;
  bool get showAllyDeck => _showAllyDeck;
  int get scenarioSectionsVersion => _scenarioSectionsVersion;

  BuiltList<String> get scenarioSectionsAdded =>
      BuiltList.of(_scenarioSectionsAdded);
  BuiltList<SpecialRule> get scenarioSpecialRules =>
      BuiltList.of(_scenarioSpecialRules);
  BuiltList<ListItemData> get currentList => BuiltList.of(_currentList);
  BuiltList<MonsterAbilityState> get currentAbilityDecks =>
      BuiltList.of(_currentAbilityDecks);
  BuiltMap<Elements, ElementState> get elementState =>
      BuiltMap.of(_elementState);

  ElementState elementStateFor(Elements element) => _elementState[element]!;
  BuiltSet<String> get unlockedClasses => BuiltSet.of(_unlockedClasses);
  int get unlockedClassesVersion => _unlockedClassesVersion;

  LootDeck get lootDeck => _lootDeck; //todo: still mutable
  ModifierDeck get modifierDeck => _modifierDeck; //todo: still mutable
  ModifierDeck get modifierDeckAllies =>
      _modifierDeckAllies; //todo: still mutable
  SanctuaryDeck get sanctuaryDeck => _sanctuaryDeck;

  GameState() {
    _actionHandler = ActionHandler(gameState: this);
  }

  // ActionHandler delegation — public API preserved for all callers
  void action(Command command) => _actionHandler.action(command);
  void undo() => _actionHandler.undo();
  void redo() => _actionHandler.redo();
  void updateAllUI() => _actionHandler.updateAllUI();
  Command getCurrent() => _actionHandler.getCurrent();
  void resetCommandHistory() => _actionHandler.resetCommandHistory();
  void clearLocalCommands() => _actionHandler.clearLocalCommands();
  void insertReceivedDescription(int index, String description) =>
      _actionHandler.insertReceivedDescription(index, description);
  void addSaveState(GameSaveState state) => _actionHandler.addSaveState(state);

  int get commandIndex => _actionHandler.commandIndex;

  /// Writable, as in the reference (whose `ValueNotifier<int>` getter allowed
  /// direct writes); used by tests and by the Phase 2 network layer.
  set commandIndex(int value) => _actionHandler.commandIndex = value;

  GameEvent get lastEvent => _actionHandler.lastEvent;
  int get maxUndo => _actionHandler.maxUndo;
  List<Command?> get commands => _actionHandler.commands;
  List<String> get commandDescriptions => _actionHandler.commandDescriptions;
  List<GameSaveState?> get gameSaveStates => _actionHandler.gameSaveStates;

  /// The Phase 2 broadcast hook, reachable through the action handler: set
  /// by the network layer, null in headless tests.
  void Function(int index, String description, String eventJson)?
  get onAction => _actionHandler.onAction;

  set onAction(
    void Function(int index, String description, String eventJson)? value,
  ) {
    _actionHandler.onAction = value;
  }

  // Minimal observer hook — replaces the reference app's ChangeNotifier
  // notifications. The network layer (Phase 2) subscribes; unused in Phase 1.
  final List<void Function()> _listeners = [];
  void addListener(void Function() listener) => _listeners.add(listener);
  void removeListener(void Function() listener) => _listeners.remove(listener);
  void notifyListeners() => [..._listeners].forEach((l) => l());

  void init() {
    _elementState[Elements.fire] = ElementState.inert;
    _elementState[Elements.ice] = ElementState.inert;
    _elementState[Elements.air] = ElementState.inert;
    _elementState[Elements.earth] = ElementState.inert;
    _elementState[Elements.light] = ElementState.inert;
    _elementState[Elements.dark] = ElementState.inert;
  }

  void setCampaign(_StateModifier _, String value) {
    _currentCampaign = value;
  }

  void setRoundState(_StateModifier _, RoundState value) {
    _roundState = value;
  }

  void setLevel(_StateModifier _, int value) {
    _level = value;
  }

  void setSolo(_StateModifier _, bool value) {
    _solo = value;
  }

  void setAutoScenarioLevel(_StateModifier _, bool value) {
    _autoScenarioLevel = value;
  }

  void setAllyDeckInOGGloom(_StateModifier _, bool value) {
    _allyDeckInOGGloom = value;
  }

  void setDifficulty(_StateModifier _, int value) {
    _difficulty = value;
  }

  void setScenario(_StateModifier _, String value) {
    _scenario = value;
  }

  void setToastMessage(_StateModifier _, String value) {
    _toastMessage = value;
  }

  Map<String, dynamic> toJson() {
    final Map<String, int> elements = {};
    for (final key in _elementState.keys) {
      final state = _elementState[key];
      if (state != null) {
        elements[key.index.toString()] = state.index;
      }
    }
    return {
      'level': _level,
      'solo': _solo,
      'autoScenarioLevel': _autoScenarioLevel,
      'difficulty': _difficulty,
      'roundState': _roundState.index,
      'round': _round,
      'totalRounds': _totalRounds,
      'scenario': _scenario,
      'toastMessage': _toastMessage,
      'scenarioSpecialRules': _scenarioSpecialRules
          .map((r) => r.toJson())
          .toList(),
      'scenarioSectionsAdded': _scenarioSectionsAdded,
      'currentCampaign': _currentCampaign,
      'currentList': _currentList.map((item) => item.toJson()).toList(),
      'currentAbilityDecks': _currentAbilityDecks
          .map((d) => d.toJson())
          .toList(),
      'sanctuaryDeck': _sanctuaryDeck.toJson(),
      'modifierDeck': _modifierDeck.toJson(),
      'modifierDeckAllies': _modifierDeckAllies.toJson(),
      'lootDeck': _lootDeck.toJson(),
      'unlockedClasses': unlockedClasses.toList(),
      'showAllyDeck': showAllyDeck,
      'allyDeckInOGGloom': allyDeckInOGGloom,
      'elementState': elements,
    };
  }

  @override
  String toString() => json.encode(toJson());

  void save() {
    final GameSaveState state = GameSaveState();
    state.saveToDisk(this);
    addSaveState(state);
  }

  void load() {
    final GameSaveState state = GameSaveState();
    state.loadFromDisk(this);
    addSaveState(
      state,
    ); //init state: means game save state is one larger than command list
  }

  void loadFromData(String data) {
    final GameSaveState state = GameSaveState();
    state.loadFromData(data, this);
  }

  /// Fires [notifyListeners] with the current list.
  void _notifyCurrentList() {
    _reflowNoteRows();
    notifyListeners();
  }

  /// Keeps every linked [NoteRow] positioned directly after its target row (and
  /// after any earlier notes on the same target), so connected notes stay glued
  /// to their anchor through drag-reordering and the per-round initiative sort.
  /// Figures and unlinked notes keep their relative order. A note whose target
  /// is not currently present is left where it is (and re-glues if the target
  /// returns, e.g. mid network sync). No-op — and no reallocation — when there
  /// are no linked notes, which is the common case.
  void _reflowNoteRows() {
    bool hasLinkedNote = false;
    for (final item in _currentList) {
      if (item is NoteRow && item.linkedId.isNotEmpty) {
        hasLinkedNote = true;
        break;
      }
    }
    if (!hasLinkedNote) return;

    final Set<String> figureIds = {};
    for (final item in _currentList) {
      if (item is! NoteRow) figureIds.add(item.id);
    }

    final Map<String, List<NoteRow>> notesByTarget = {};
    final List<ListItemData> anchors = [];
    for (final item in _currentList) {
      if (item is NoteRow &&
          item.linkedId.isNotEmpty &&
          figureIds.contains(item.linkedId)) {
        notesByTarget.putIfAbsent(item.linkedId, () => []).add(item);
      } else {
        anchors.add(item);
      }
    }
    if (notesByTarget.isEmpty) return;

    final List<ListItemData> result = [];
    for (final item in anchors) {
      result.add(item);
      final notes = notesByTarget.remove(item.id);
      if (notes != null) result.addAll(notes);
    }
    _currentList = result;
  }

  /// Notifies every monster instance / summon list in the current list. Used
  /// by [updateAllUI] (redo / network sync).
  void notifyAllMonsterInstances() {
    for (final item in _currentList) {
      if (item is Monster) {
        item._notifyMonsterInstances();
      } else if (item is Character) {
        item.characterState._notifySummonList();
      }
    }
  }

  /// Clears the current list. only for use in tests. temp. should use load from data instead
  void clearList() {
    _currentList.clear();
    _notifyCurrentList();
  }
}

abstract class Command {
  //private class so only this class and it's children is allowed to change state
  _StateModifier stateAccess = _StateModifier();
  void execute();
  void onUndo() {}
  String describe();

  /// The [GameEvent] this command produces. Defaults to [NoEvent].
  /// Override in commands that drive UI animations.
  GameEvent get event => const NoEvent();
}

class _StateModifier {}