From 808294adad3f378ad8d66b698acf8df7f49c2302 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Thu, 12 Nov 2026 00:28:50 +0100 Subject: 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. --- server/lib/core/state/game_save_state.dart | 252 +++++++++++++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 server/lib/core/state/game_save_state.dart (limited to 'server/lib/core/state/game_save_state.dart') 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; + + 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 scenarioSectionsAdded = + data['scenarioSectionsAdded'] as List; + 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 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 newList = []; + for (Map item in list) { + if (item["noteRow"] == true) { + final String itemId = item["id"] as String; + final NoteRow? existing = gameState._currentList + .whereType() + .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() + .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() + .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 newAbilityDecks = []; + for (Map 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 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 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().write(_savedState!); + } + + void loadFromDisk(GameState gameState) { + //have to call after init or element state overridden + String? data = getIt().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 data, GameState gameState) { + gameState._lootDeck.updateFromJson(data["lootDeck"]); + } + + void _loadModifierDeck( + String identifier, + Map data, + GameState gameState, + ) { + final modifierDeckData = data[identifier] as Map; + if (identifier == 'modifierDeck') { + gameState._modifierDeck.updateFromJson(modifierDeckData); + } else { + gameState._modifierDeckAllies.updateFromJson(modifierDeckData); + } + } +} -- cgit v1.3.1