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_state.dart | 352 ++++++++++++++++++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 server/lib/core/state/game_state.dart (limited to 'server/lib/core/state/game_state.dart') diff --git a/server/lib/core/state/game_state.dart b/server/lib/core/state/game_state.dart new file mode 100644 index 0000000..a6884cc --- /dev/null +++ b/server/lib/core/state/game_state.dart @@ -0,0 +1,352 @@ +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? pendingAutoAddDialog = null; + + List _scenarioSectionsAdded = []; + List _scenarioSpecialRules = []; + int _scenarioSectionsVersion = 0; + List _currentList = []; //has both monsters and characters + final List _currentAbilityDecks = + []; + final Map _elementState = HashMap(); + Set _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` 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 get scenarioSectionsAdded => + BuiltList.of(_scenarioSectionsAdded); + BuiltList get scenarioSpecialRules => + BuiltList.of(_scenarioSpecialRules); + BuiltList get currentList => BuiltList.of(_currentList); + BuiltList get currentAbilityDecks => + BuiltList.of(_currentAbilityDecks); + BuiltMap get elementState => + BuiltMap.of(_elementState); + + ElementState elementStateFor(Elements element) => _elementState[element]!; + BuiltSet 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` 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 get commands => _actionHandler.commands; + List get commandDescriptions => _actionHandler.commandDescriptions; + List get gameSaveStates => _actionHandler.gameSaveStates; + + /// The Phase 2 broadcast hook is reachable through the action handler. + void Function(int index, String description, String eventJson)? + get onAction => _actionHandler.onAction; + + // Minimal observer hook — replaces the reference app's ChangeNotifier + // notifications. The network layer (Phase 2) subscribes; unused in Phase 1. + final List _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 toJson() { + final Map 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() { + GameSaveState state = GameSaveState(); + state.saveToDisk(this); + addSaveState(state); + } + + void load() { + GameSaveState state = GameSaveState(); + state.loadFromDisk(this); + addSaveState( + state, + ); //init state: means game save state is one larger than command list + } + + void loadFromData(String data) { + 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 figureIds = {}; + for (final item in _currentList) { + if (item is! NoteRow) figureIds.add(item.id); + } + + final Map> notesByTarget = {}; + final List 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 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 {} -- cgit v1.3.1