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; /// 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). String scenario = ""; String _toastMessage = ""; bool _showAllyDeck = false; List? pendingAutoAddDialog; 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; 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, 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 _listeners = []; void addListener(void Function() listener) => _listeners.add(listener); void removeListener(void Function() listener) => _listeners.remove(listener); void notifyListeners() { for (final listener in [..._listeners]) { listener(); } } 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() { 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 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 {}