summaryrefslogtreecommitdiff
path: root/server/lib/core/state/game_save_state.dart
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-12 00:28:50 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-12 00:28:50 +0100
commit808294adad3f378ad8d66b698acf8df7f49c2302 (patch)
treecfd11a1395a8ad482311969f86abbbad97e7e0b4 /server/lib/core/state/game_save_state.dart
parentf6955e34489c79f6d5b764cb6a39b1387366b433 (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/state/game_save_state.dart')
-rw-r--r--server/lib/core/state/game_save_state.dart252
1 files changed, 252 insertions, 0 deletions
diff --git a/server/lib/core/state/game_save_state.dart b/server/lib/core/state/game_save_state.dart
new file mode 100644
index 0000000..331b3a8
--- /dev/null
+++ b/server/lib/core/state/game_save_state.dart
@@ -0,0 +1,252 @@
+part of 'game_state.dart';
+
+final _gameSaveStateLog = Logger('GameSaveState');
+
+class GameSaveState {
+ String? _savedState;
+
+ String getState() {
+ final state = _savedState;
+ if (state == null) throw StateError('GameSaveState: no saved state');
+ return state;
+ }
+
+ void save(GameState gameState) {
+ _savedState = gameState.toString();
+ }
+
+ void load(GameState gameState) {
+ if (_savedState != null) {
+ try {
+ final data = json.decode(_savedState ?? '') as Map<String, dynamic>;
+
+ gameState._level = data['level'] as int;
+ gameState._scenario = data['scenario']; // as String;
+ if (data.containsKey('toastMessage')) {
+ gameState._toastMessage = data['toastMessage']; // as String;
+ }
+
+ if (data.containsKey('scenarioSectionsAdded')) {
+ List<Object?> scenarioSectionsAdded =
+ data['scenarioSectionsAdded'] as List<Object?>;
+ gameState._scenarioSectionsAdded.clear();
+ for (final item in scenarioSectionsAdded) {
+ gameState._scenarioSectionsAdded.add(item as String);
+ }
+ }
+
+ if (data.containsKey('scenarioSpecialRules')) {
+ final scenarioSpecialRulesList = data['scenarioSpecialRules'] as List;
+ gameState._scenarioSpecialRules.clear();
+ for (Map<String, dynamic> item in scenarioSpecialRulesList) {
+ gameState._scenarioSpecialRules.add(SpecialRule.fromJson(item));
+ }
+ }
+ gameState._scenarioSectionsVersion++;
+ gameState._currentCampaign = data['currentCampaign'];
+ gameState._round = data['round'] as int;
+ if (data.containsKey('totalRounds')) {
+ gameState._totalRounds = data['totalRounds'] as int;
+ } else {
+ gameState._totalRounds = gameState._round;
+ }
+ final roundStateIdx = data['roundState'] as int?;
+ if (roundStateIdx != null &&
+ roundStateIdx >= 0 &&
+ roundStateIdx < RoundState.values.length) {
+ gameState._roundState = RoundState.values[roundStateIdx];
+ }
+ gameState._solo = data['solo'] as bool;
+
+ if (data.containsKey('autoScenarioLevel')) {
+ gameState._autoScenarioLevel = data['autoScenarioLevel'] as bool;
+ } else {
+ gameState._autoScenarioLevel = true;
+ }
+
+ if (data.containsKey("allyDeckInOGGloom")) {
+ gameState._allyDeckInOGGloom = data["allyDeckInOGGloom"] as bool;
+ } else {
+ gameState._allyDeckInOGGloom = true;
+ }
+
+ if (data.containsKey('difficulty')) {
+ gameState._difficulty = data['difficulty'] as int;
+ } else {
+ gameState._difficulty = 0;
+ }
+
+ //main list — update existing objects in-place
+ final list = data['currentList'] as List;
+ List<ListItemData> newList = [];
+ for (Map<String, dynamic> item in list) {
+ if (item["noteRow"] == true) {
+ final String itemId = item["id"] as String;
+ final NoteRow? existing = gameState._currentList
+ .whereType<NoteRow>()
+ .firstWhereOrNull((e) => e.id == itemId);
+ if (existing != null) {
+ existing.updateFromJson(item);
+ newList.add(existing);
+ } else {
+ newList.add(NoteRow.fromJson(item));
+ }
+ } else if (item["characterClass"] != null) {
+ final String itemId = item["id"] as String;
+ final Character? existing = gameState._currentList
+ .whereType<Character>()
+ .firstWhereOrNull((e) => e.id == itemId);
+ if (existing != null) {
+ existing.updateFromJson(item);
+ newList.add(existing);
+ } else {
+ newList.add(Character.fromJson(item));
+ }
+ } else if (item["type"] != null) {
+ final String itemId = item["id"] as String;
+ final Monster? existing = gameState._currentList
+ .whereType<Monster>()
+ .firstWhereOrNull((e) => e.id == itemId);
+ if (existing != null) {
+ existing.updateFromJson(item);
+ newList.add(existing);
+ } else {
+ newList.add(Monster.fromJson(item));
+ }
+ }
+ }
+ gameState._currentList = newList;
+ gameState._notifyCurrentList();
+
+ final unlockedClassesList = data['unlockedClasses'] as List;
+ gameState._unlockedClasses.clear();
+ for (String item in unlockedClassesList) {
+ gameState._unlockedClasses.add(item);
+ }
+ gameState._unlockedClassesVersion++;
+
+ //ability decks — update existing instances in-place
+ final decks = data['currentAbilityDecks'] as List;
+ final List<MonsterAbilityState> newAbilityDecks = [];
+ for (Map<String, dynamic> item in decks) {
+ final String deckName = item["name"] as String;
+ // Prototype has the full initialized card set; used only for nr lookups.
+ final proto = MonsterAbilityState(deckName);
+
+ List<MonsterAbilityCardModel> newDrawList = [];
+ List drawPile = item["drawPile"] as List;
+ for (final cardItem in drawPile) {
+ int nr = cardItem["nr"];
+ for (final card in proto._drawPile.getList()) {
+ if (card.nr == nr) {
+ newDrawList.add(card);
+ break;
+ }
+ }
+ }
+ List<MonsterAbilityCardModel> newDiscardList = [];
+ for (final cardItem in item["discardPile"] as List) {
+ int nr = cardItem["nr"];
+ for (final card in proto._drawPile.getList()) {
+ if (card.nr == nr) {
+ newDiscardList.add(card);
+ break;
+ }
+ }
+ }
+
+ // Reuse existing state; fall back to the prototype for monsters
+ // newly added from a remote device.
+ final state =
+ gameState._currentAbilityDecks.firstWhereOrNull(
+ (s) => s.name == deckName,
+ ) ??
+ proto;
+
+ if (item.containsKey("lastRoundDrawn")) {
+ state._lastRoundDrawn = item["lastRoundDrawn"] as int;
+ }
+ state._drawPile.clear();
+ state._discardPile.clear();
+ state._drawPile.setList(newDrawList);
+ state._discardPile.setList(newDiscardList);
+ state.drawPileVersion++;
+ newAbilityDecks.add(state);
+ }
+ gameState._currentAbilityDecks.clear();
+ gameState._currentAbilityDecks.addAll(newAbilityDecks);
+
+ _loadModifierDeck('modifierDeck', data, gameState);
+ _loadModifierDeck('modifierDeckAllies', data, gameState);
+ _loadLootDeck(data, gameState);
+
+ if (data["sanctuaryDeck"] != null) {
+ gameState._sanctuaryDeck = SanctuaryDeck.fromJson(
+ data["sanctuaryDeck"],
+ );
+ }
+
+ //this is not really a setting, but a scenario command?
+ if (data["showAllyDeck"] != null) {
+ gameState._showAllyDeck = data["showAllyDeck"];
+ }
+
+ //////elements
+ Map elementData = data['elementState'];
+ for (final element in Elements.values) {
+ final raw = elementData[element.index.toString()] as int?;
+ final idx =
+ (raw != null && raw >= 0 && raw < ElementState.values.length)
+ ? raw
+ : ElementState.inert.index;
+ gameState._elementState[element] = ElementState.values[idx];
+ }
+ } catch (e, stack) {
+ // Deserialization failure: log always (not just debug) so it surfaces
+ // in release builds and can be caught by crash-reporting tools.
+ _gameSaveStateLog.warning('GameSaveState.load error: $e\n$stack');
+ }
+ }
+ }
+
+ void saveToDisk(GameState gameState) {
+ if (_savedState == null) {
+ save(gameState);
+ }
+ getIt<SaveStore>().write(_savedState!);
+ }
+
+ void loadFromDisk(GameState gameState) {
+ //have to call after init or element state overridden
+ String? data = getIt<SaveStore>().read();
+ if (data != null) {
+ _savedState = data;
+ load(gameState);
+ } else {
+ save(gameState);
+ }
+ }
+
+ void loadFromData(String data, GameState gameState) {
+ //have to call after init or element state overridden
+ _savedState = data;
+ load(gameState);
+ }
+
+ void _loadLootDeck(Map<String, dynamic> data, GameState gameState) {
+ gameState._lootDeck.updateFromJson(data["lootDeck"]);
+ }
+
+ void _loadModifierDeck(
+ String identifier,
+ Map<String, dynamic> data,
+ GameState gameState,
+ ) {
+ final modifierDeckData = data[identifier] as Map<String, dynamic>;
+ if (identifier == 'modifierDeck') {
+ gameState._modifierDeck.updateFromJson(modifierDeckData);
+ } else {
+ gameState._modifierDeckAllies.updateFromJson(modifierDeckData);
+ }
+ }
+}