diff options
Diffstat (limited to 'server/lib/core/state')
| -rw-r--r-- | server/lib/core/state/character.dart | 143 | ||||
| -rw-r--r-- | server/lib/core/state/character_state.dart | 251 | ||||
| -rw-r--r-- | server/lib/core/state/figure_state.dart | 62 | ||||
| -rw-r--r-- | server/lib/core/state/game_save_state.dart | 252 | ||||
| -rw-r--r-- | server/lib/core/state/game_state.dart | 352 | ||||
| -rw-r--r-- | server/lib/core/state/list_item_data.dart | 22 | ||||
| -rw-r--r-- | server/lib/core/state/loot_deck_state.dart | 577 | ||||
| -rw-r--r-- | server/lib/core/state/modifier_deck.dart | 758 | ||||
| -rw-r--r-- | server/lib/core/state/monster.dart | 198 | ||||
| -rw-r--r-- | server/lib/core/state/monster_ability_state.dart | 98 | ||||
| -rw-r--r-- | server/lib/core/state/monster_instance.dart | 198 | ||||
| -rw-r--r-- | server/lib/core/state/note_row.dart | 96 | ||||
| -rw-r--r-- | server/lib/core/state/sanctuary_deck.dart | 85 |
13 files changed, 3092 insertions, 0 deletions
diff --git a/server/lib/core/state/character.dart b/server/lib/core/state/character.dart new file mode 100644 index 0000000..59fe3bf --- /dev/null +++ b/server/lib/core/state/character.dart @@ -0,0 +1,143 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class Character extends ListItemData { + final CharacterState characterState; + final CharacterClass characterClass; + + Character(this.characterState, this.characterClass) { + id = GameMethods.isObjectiveOrEscort(characterClass) + ? characterState.display + : characterClass.id; + } + + static CharacterClass _requireClass(String anId, String? edition) { + final cls = _getClassStatic(anId, edition); + if (cls == null) { + throw StateError('Character class not found: $anId (edition: $edition)'); + } + return cls; + } + + Character.fromSave(Map<String, dynamic> json) + : characterState = CharacterState.fromSave( + json['characterClass'] as String, + json['characterState'] as Map<String, dynamic>, + ), + characterClass = _requireClass( + json['characterClass'] as String, + json['edition'] as String?, + ) { + id = characterClass.id; + if (json.containsKey("note")) { + _note = json["note"] as String; + } + } + + Character.fromJson(Map<String, dynamic> json) + : characterState = CharacterState.fromJson( + json['characterClass'] as String, + json['characterState'] as Map<String, dynamic>, + ), + characterClass = _requireClass( + json['characterClass'] as String, + json['edition'] as String?, + ) { + final turnStateIdx = json['turnState'] as int?; + if (turnStateIdx != null && + turnStateIdx >= 0 && + turnStateIdx < TurnsState.values.length) { + _turnState = TurnsState.values[turnStateIdx]; + } + if (json.containsKey("note")) { + _note = json["note"] as String; + } + + id = GameMethods.isObjectiveOrEscort(characterClass) + ? characterState.display + : characterClass.id; + } + + /// Updates mutable fields in-place from [json]. [characterClass] and [id] + /// never change; only [_turnState] and [characterState] need updating. + void updateFromJson(Map<String, dynamic> json) { + final turnStateIdx = json['turnState'] as int?; + if (turnStateIdx != null && + turnStateIdx >= 0 && + turnStateIdx < TurnsState.values.length) { + _turnState = TurnsState.values[turnStateIdx]; + } + _note = json.containsKey("note") ? json["note"] as String : ""; + characterState.updateFromJson( + json['characterClass'] as String, + json['characterState'] as Map<String, dynamic>, + ); + } + + void nextRound(_StateModifier _) { + if (!GameMethods.isObjectiveOrEscort(characterClass)) { + characterState._initiative = 0; + } + } + + void flipUseFHPerks(_StateModifier s) { + //first clear all perks + for (int i = 0; i < characterState._perkList.length; i++) { + if (characterState._perkList[i]) { + characterState.flipPerk(s, i); + CharacterMethods.removePerk(s, this, i); + } + } + + characterState._useFHPerks = !characterState._useFHPerks; + } + + void flipPerk(_StateModifier s, int index) { + characterState.flipPerk(s, index); + if (characterState.perkList[index]) { + CharacterMethods.addPerk(s, this, index); + } else { + CharacterMethods.removePerk(s, this, index); + } + } + + String toSave() { + return '{' + '"characterState": ${characterState.toString()}, ' + '"note": ${jsonEncode(note)}, ' + '"characterClass": "${characterClass.id}", ' + '"edition": "${characterClass.edition}" ' + '}'; + } + + @override + Map<String, dynamic> toJson() => { + 'id': id, + 'turnState': turnState.index, + 'note': note, + 'characterState': characterState.toJson(), + 'characterClass': characterClass.id, + 'edition': characterClass.edition, + }; + + @override + String toString() => json.encode(toJson()); + + static CharacterClass? _getClassStatic( + String id, + String? edition, { + GameData? gameData, + }) { + final modelData = (gameData ?? getIt<GameData>()).modelData; + for (String key in modelData.keys) { + final item = modelData[key]?.characters.firstWhereOrNull((item) { + return item.id == id && (edition == null || edition == item.edition); + }); + if (item != null) { + return item; + } + } + return null; + } +} diff --git a/server/lib/core/state/character_state.dart b/server/lib/core/state/character_state.dart new file mode 100644 index 0000000..848bc1c --- /dev/null +++ b/server/lib/core/state/character_state.dart @@ -0,0 +1,251 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class CharacterState extends FigureState { + static const int _kMaxPerks = 18; + + String _display = ""; + final List<bool> _perkList = List.filled(_kMaxPerks, false); + int _perkListVersion = 0; + bool _useFHPerks = false; + + int _initiative = 0; + int _xp = 0; + final List<MonsterInstance> _summonList = []; + BuiltList<MonsterInstance> _summonListNotifier = BuiltList.of([]); + final ModifierDeck _modifierDeck; + + String get display => _display; + int get initiative => _initiative; + int get xp => _xp; + BuiltList<MonsterInstance> get summonList => BuiltList.of(_summonList); + BuiltList<MonsterInstance> get summonListNotifier => _summonListNotifier; + ModifierDeck get modifierDeck => _modifierDeck; + + void _notifySummonList() { + // UI-only in the reference app + } + + /// Public guarded notify — allows commands to trigger the summon list + /// update at the correct time (e.g. after a 600 ms death animation). + void notifySummonList(_StateModifier _) { + _notifySummonList(); + } + + BuiltList<bool> get perkList => BuiltList.of(_perkList); + int get perkListVersion => _perkListVersion; + bool get useFHPerks => _useFHPerks; + + CharacterState(final String id) : _modifierDeck = ModifierDeck(id); + + static ModifierDeck _deckFromJson(String id, Map<String, dynamic> json) { + if (json.containsKey("modifierDeck")) { + return ModifierDeck.fromJson(id, json["modifierDeck"]); + } + return ModifierDeck(id); + } + + CharacterState.fromSave(final String id, Map<String, dynamic> json) + : _modifierDeck = ModifierDeck(id) { + _level = json["level"]; + _display = json['display']; + if (json.containsKey("useFHPerks")) { + _useFHPerks = json["useFHPerks"]; + } + if (json.containsKey("perkList")) { + final perks = json["perkList"]; + int i = 0; + for (bool item in perks) { + if (i >= _perkList.length) break; + _perkList[i] = item; + i++; + } + } + } + + CharacterState.fromJson(final String id, Map<String, dynamic> json) + : _modifierDeck = _deckFromJson(id, json) { + _initiative = json['initiative']; + _xp = json['xp']; + _chill = json['chill']; + _health = json["health"]; + _level = json["level"]; + _maxHealth = json["maxHealth"]; + _display = json['display']; + + final summons = json["summonList"]; + for (final item in summons) { + _summonList.add(MonsterInstance.fromJson(item)); + } + _notifySummonList(); + + //todo: automate check json.containsKey for everything: the nr of update bugs... + if (json.containsKey("perkList")) { + final perks = json["perkList"]; + int i = 0; + for (bool item in perks) { + if (i >= _perkList.length) break; + _perkList[i] = item; + i++; + } + } + if (json.containsKey("useFHPerks")) { + _useFHPerks = json["useFHPerks"]; + } + + final condis = json["conditions"]; + for (int item in condis) { + if (item >= 0 && item < Condition.values.length) { + _conditions.add(Condition.values[item]); + } + } + + if (json.containsKey("conditionsAddedThisTurn")) { + final condis2 = json["conditionsAddedThisTurn"]; + for (int item in condis2) { + if (item >= 0 && item < Condition.values.length) { + _conditionsAddedThisTurn.add(Condition.values[item]); + } + } + } + if (json.containsKey("conditionsAddedPreviousTurn")) { + final condis3 = json["conditionsAddedPreviousTurn"]; + for (int item in condis3) { + if (item >= 0 && item < Condition.values.length) { + _conditionsAddedPreviousTurn.add(Condition.values[item]); + } + } + } + } + + /// Updates all fields in-place from [json]. Preserves object identity. + void updateFromJson(String _, Map<String, dynamic> json) { + _initiative = json['initiative'] as int; + _xp = json['xp'] as int; + _chill = json['chill'] as int; + _health = json["health"] as int; + _level = json["level"] as int; + _maxHealth = json["maxHealth"] as int; + _display = json['display'] as String; + _plague = 0; // not serialised — reset to match fromJson behaviour + + _summonList.clear(); + for (final item in json["summonList"]) { + _summonList.add(MonsterInstance.fromJson(item as Map<String, dynamic>)); + } + _notifySummonList(); + + for (int i = 0; i < _perkList.length; i++) { + _perkList[i] = false; + } + if (json.containsKey("perkList")) { + int i = 0; + for (bool item in json["perkList"]) { + if (i >= _perkList.length) break; + _perkList[i] = item; + i++; + } + } + _perkListVersion++; + _useFHPerks = json.containsKey("useFHPerks") + ? json["useFHPerks"] as bool + : false; + + // Assign a new list instance. + final newConditions = <Condition>[]; + for (int item in json["conditions"]) { + if (item >= 0 && item < Condition.values.length) { + newConditions.add(Condition.values[item]); + } + } + _conditions = newConditions; + + if (json.containsKey("modifierDeck")) { + _modifierDeck.updateFromJson( + json["modifierDeck"] as Map<String, dynamic>, + ); + } else { + _modifierDeck.resetToDefault(); + } + + _conditionsAddedThisTurn.clear(); + if (json.containsKey("conditionsAddedThisTurn")) { + for (int item in json["conditionsAddedThisTurn"]) { + if (item >= 0 && item < Condition.values.length) { + _conditionsAddedThisTurn.add(Condition.values[item]); + } + } + } + _conditionsAddedPreviousTurn.clear(); + if (json.containsKey("conditionsAddedPreviousTurn")) { + for (int item in json["conditionsAddedPreviousTurn"]) { + if (item >= 0 && item < Condition.values.length) { + _conditionsAddedPreviousTurn.add(Condition.values[item]); + } + } + } + } + + void flipPerk(_StateModifier _, int index) { + _perkList[index] = !_perkList[index]; + _perkListVersion++; + } + + void setDisplay(_StateModifier _, String value) { + _display = value; + } + + void setInitiative(_StateModifier _, int value) { + _initiative = value; + } + + void setXp(_StateModifier _, int value) { + _xp = max(value, 0); + } + + void addSummon(_StateModifier _, MonsterInstance summon) { + _summonList.add(summon); + _notifySummonList(); + } + + /// Removes [summon] from the list. + /// The caller is responsible for calling [notifySummonList] at the + /// appropriate time (e.g. after a 600 ms death animation). + void removeSummon(_StateModifier _, MonsterInstance summon) { + _summonList.remove(summon); + } + + String toSave() { + return '{' + '"level": ${level}, ' + '"useFHPerks": ${jsonEncode(useFHPerks)}, ' + '"display": ${jsonEncode(display)}, ' + '"perkList": ${_perkList.toString()} ' + '}'; + } + + Map<String, dynamic> toJson() => { + 'initiative': initiative, + 'health': health, + 'maxHealth': maxHealth, + 'level': level, + 'xp': xp, + 'chill': chill, + 'display': display, + 'modifierDeck': _modifierDeck.toJson(), + 'summonList': _summonList.map((s) => s.toJson()).toList(), + 'useFHPerks': useFHPerks, + 'perkList': List<bool>.of(_perkList), + 'conditions': _conditions.map((c) => c.index).toList(), + 'conditionsAddedThisTurn': _conditionsAddedThisTurn + .map((c) => c.index) + .toList(), + 'conditionsAddedPreviousTurn': _conditionsAddedPreviousTurn + .map((c) => c.index) + .toList(), + }; + + @override + String toString() => json.encode(toJson()); +} diff --git a/server/lib/core/state/figure_state.dart b/server/lib/core/state/figure_state.dart new file mode 100644 index 0000000..d14275f --- /dev/null +++ b/server/lib/core/state/figure_state.dart @@ -0,0 +1,62 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api +class FigureState { + List<Condition> _conditions = []; + + List<Condition> get conditions => _conditions; + + int _level = 1; + int _health = 0; + int _maxHealth = 0; + int _chill = 0; + int _plague = 0; + final Set<Condition> _conditionsAddedThisTurn = {}; + final Set<Condition> _conditionsAddedPreviousTurn = {}; + + int get level => _level; + int get health => _health; + int get maxHealth => _maxHealth; + int get chill => _chill; + int get plague => _plague; + BuiltSet<Condition> get conditionsAddedThisTurn => + BuiltSet.of(_conditionsAddedThisTurn); + BuiltSet<Condition> get conditionsAddedPreviousTurn => + BuiltSet.of(_conditionsAddedPreviousTurn); + + void setHealth(_StateModifier _, int value) { + _health = value; + } + + void setFigureLevel(_StateModifier _, int value) { + _level = value; + } + + void setMaxHealth(_StateModifier _, int value) { + _maxHealth = value; + } + + void setChill(_StateModifier _, int value) { + _chill = value; + } + + void setPlague(_StateModifier _, int value) { + _plague = value; + } + + void setConditions(_StateModifier _, List<Condition> value) { + _conditions = value; + } + + void addToConditionsThisTurn(_StateModifier _, Condition condition) { + _conditionsAddedThisTurn.add(condition); + } + + void removeFromConditionsThisTurn(_StateModifier _, Condition condition) { + _conditionsAddedThisTurn.remove(condition); + } + + void removeFromConditionsPreviousTurn(_StateModifier _, Condition condition) { + _conditionsAddedPreviousTurn.remove(condition); + } +} 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); + } + } +} 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<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 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<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() { + 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<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 {} diff --git a/server/lib/core/state/list_item_data.dart b/server/lib/core/state/list_item_data.dart new file mode 100644 index 0000000..c322525 --- /dev/null +++ b/server/lib/core/state/list_item_data.dart @@ -0,0 +1,22 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api +class ListItemData { + String id = ''; + TurnsState _turnState = TurnsState.notDone; + TurnsState get turnState => _turnState; + + // Free-form inline note shown on the row. Shared by characters and monsters. + String _note = ""; + String get note => _note; + + void setTurnState(_StateModifier _, TurnsState value) { + _turnState = value; + } + + void setNote(_StateModifier _, String value) { + _note = value; + } + + Map<String, dynamic> toJson() => {}; +} diff --git a/server/lib/core/state/loot_deck_state.dart b/server/lib/core/state/loot_deck_state.dart new file mode 100644 index 0000000..31c6df7 --- /dev/null +++ b/server/lib/core/state/loot_deck_state.dart @@ -0,0 +1,577 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class LootCard { + // ignore: prefer-match-file-name, file contains multiple loot deck state types + static const int _kHighCharCount = 4; + static const int _kLowCharCount = 2; + + final String gfx; + final int id; + final LootBaseValue baseValue; + final LootType lootType; + String owner = ""; + int _enhanced = 0; + int get enhanced => _enhanced; + + LootCard({ + required this.id, + required this.lootType, + required this.baseValue, + required enhanced, + required this.gfx, + }) { + _enhanced = enhanced; + } + + Map<String, dynamic> toJson() => { + 'gfx': gfx, + 'owner': owner, + 'id': id, + 'enhanced': enhanced, + 'baseValue': baseValue.index, + 'lootType': lootType.index, + }; + + @override + String toString() => json.encode(toJson()); + + int? getValue() { + int value = 1; + if (lootType == LootType.other) { + if (enhanced > 0) { + return enhanced; + } + return null; + } + if (enhanced > 0) { + value += enhanced; + } + int characters = GameMethods.getCurrentCharacterAmount(); + if (characters >= _kHighCharCount) { + return value; + } + if (baseValue == LootBaseValue.oneIf4twoIfNot) { + value++; + } else if (characters <= _kLowCharCount && + baseValue == LootBaseValue.oneIf3or4twoIfNot) { + value++; + } + return value; + } +} + +class LootDeck { + static const int _kSpecialCard1418 = 1418; + static const int _kSpecialCard1419 = 1419; + static const int _kTreasureCardId = 9999; + static const int _kMaterialOneCount = 2; + static const int _kMaterialTwoCount = 3; + static const int _kHerbPoolCount = 2; + static const int _kCoin1Count = 12; + static const int _kCoin2Count = 6; + static const int _kMaterialPoolSize = 8; + static const int _kHerbPoolSize = 2; + + List<LootCard> _coinPool = []; + List<LootCard> _lumberPool = []; + List<LootCard> _hidePool = []; + List<LootCard> _metalPool = []; + List<LootCard> _corpsecapPool = []; + List<LootCard> _arrowvinePool = []; + List<LootCard> _flamefruitPool = []; + List<LootCard> _axenutPool = []; + List<LootCard> _rockrootPool = []; + List<LootCard> _snowthistlePool = []; + + BuiltList<LootCard> get coinPool => BuiltList.of(_coinPool); + BuiltList<LootCard> get lumberPool => BuiltList.of(_lumberPool); + BuiltList<LootCard> get hidePool => BuiltList.of(_hidePool); + BuiltList<LootCard> get metalPool => BuiltList.of(_metalPool); + BuiltList<LootCard> get corpsecapPool => BuiltList.of(_corpsecapPool); + BuiltList<LootCard> get arrowvinePool => BuiltList.of(_arrowvinePool); + BuiltList<LootCard> get flamefruitPool => BuiltList.of(_flamefruitPool); + BuiltList<LootCard> get axenutPool => BuiltList.of(_axenutPool); + BuiltList<LootCard> get rockrootPool => BuiltList.of(_rockrootPool); + BuiltList<LootCard> get snowthistlePool => BuiltList.of(_snowthistlePool); + + //2 +1, 3 oneIf3or4twoIfNot, 3 oneIf4twoIfNot + + BuiltList<int> get addedCards => BuiltList.of(_addedCards); + List<int> _addedCards = [0, 0, 0, 0, 0, 0, 0, 0, 0]; + Map<String, int> _enhancements = {}; + + final CardStack<LootCard> _drawPile = CardStack<LootCard>(); + final CardStack<LootCard> _discardPile = CardStack<LootCard>(); + + bool get drawPileIsEmpty => _drawPile.isEmpty; + bool get drawPileIsNotEmpty => _drawPile.isNotEmpty; + bool get discardPileIsEmpty => _discardPile.isEmpty; + bool get discardPileIsNotEmpty => _discardPile.isNotEmpty; + LootCard get drawPileTop => _drawPile.peek; + LootCard get discardPileTop => _discardPile.peek; + BuiltList<LootCard> get drawPileContents => BuiltList.of(_drawPile.getList()); + BuiltList<LootCard> get discardPileContents => + BuiltList.of(_discardPile.getList()); + int get drawPileSize => _drawPile.size(); + int get discardPileSize => _discardPile.size(); + + bool get hasCard1418 => _hasCard1418; + bool _hasCard1418 = false; + bool get hasCard1419 => _hasCard1419; + bool _hasCard1419 = false; + + CardStack<LootCard> get drawPileNotifier => _drawPile; + + LootDeck(LootDeckModel model, LootDeck other) { + _hasCard1418 = other._hasCard1418; + _hasCard1419 = other._hasCard1419; + _enhancements = other._enhancements; + + //build deck + _initPools(); + _setDeck(model); + } + + LootDeck.from(LootDeck other) { + _hasCard1418 = other._hasCard1418; + _hasCard1419 = other._hasCard1419; + _enhancements = other._enhancements; + + _initPools(); + } + + LootDeck.empty() { + _initPools(); + } + + LootDeck.fromJson(Map<String, dynamic> lootDeckData) { + updateFromJson(lootDeckData); + } + + /// Updates this deck in-place from [lootDeckData]. + void updateFromJson(Map<String, dynamic> lootDeckData) { + _hasCard1418 = lootDeckData["1418"] as bool; + _hasCard1419 = lootDeckData["1419"] as bool; + + _addedCards = lootDeckData.containsKey('addedCards') + ? List<int>.from(lootDeckData['addedCards'] as List) + : [0, 0, 0, 0, 0, 0, 0, 0, 0]; + + _enhancements = lootDeckData.containsKey('enhancements') + ? Map<String, int>.from(lootDeckData['enhancements'] as Map) + : {}; + + _initPools(); + + LootCard cardFromJson(Map<dynamic, dynamic> item, int fallbackId) { + final String gfx = item["gfx"] as String; + final String owner = item.containsKey('owner') + ? item["owner"] as String + : ""; + final int id = item.containsKey('id') ? item["id"] as int : fallbackId; + + // 'enhanced' was stored as bool in older saves, int in newer ones. + int enhanced = 0; + if (item['enhanced'] is bool) { + enhanced = (item['enhanced'] as bool) ? 1 : 0; + } else if (item['enhanced'] is num) { + enhanced = (item['enhanced'] as num).toInt(); + } + + final baseIdx = item["baseValue"] is int ? item["baseValue"] as int : 0; + final lootTypeIdx = item["lootType"] is int ? item["lootType"] as int : 0; + final LootBaseValue baseValue = + (baseIdx >= 0 && baseIdx < LootBaseValue.values.length) + ? LootBaseValue.values[baseIdx] + : LootBaseValue.values.first; + final LootType lootType = + (lootTypeIdx >= 0 && lootTypeIdx < LootType.values.length) + ? LootType.values[lootTypeIdx] + : LootType.values.first; + + return LootCard( + id: id, + gfx: gfx, + enhanced: enhanced, + baseValue: baseValue, + lootType: lootType, + )..owner = owner; + } + + List<LootCard> newDrawList = []; + List drawPile = lootDeckData["drawPile"] as List; + int id = 0; + for (final item in drawPile) { + if (item.containsKey('id')) id = item["id"] as int; + newDrawList.add(cardFromJson(item as Map, id)); + } + List<LootCard> newDiscardList = []; + for (final item in lootDeckData["discardPile"] as List) { + if (item.containsKey('id')) id = item["id"] as int; + newDiscardList.add(cardFromJson(item as Map, id)); + } + _drawPile.clear(); + _discardPile.clear(); + _drawPile.setList(newDrawList); + _discardPile.setList(newDiscardList); + } + + void setDeck(_StateModifier _, LootDeckModel model) { + _setDeck(model); + } + + void returnLootCard(_StateModifier _, bool top) { + final card = _discardPile.pop(); + card.owner = ""; + if (top) { + _drawPile.push(card); + } else { + _drawPile.insert(0, card); + } + } + + void _addCardFromPool(int amount, List<LootCard> pool, List<LootCard> cards) { + pool.shuffle(); + if (amount > pool.length) { + amount = pool.length; + } + for (int i = 0; i < amount; i++) { + cards.add(pool[i]); + } + pool.sort((a, b) => a.id - b.id); //may not be needed + } + + void _setDeck(LootDeckModel model) { + List<LootCard> cards = []; + + if (_hasCard1419) { + _addOtherType(_kSpecialCard1419, cards, "special 1419"); + } + if (_hasCard1418) { + _addOtherType(_kSpecialCard1418, cards, "special 1418"); + } + + _addCardFromPool(model.arrowvine, _arrowvinePool, cards); + _addCardFromPool(model.corpsecap, _corpsecapPool, cards); + _addCardFromPool(model.axenut, _axenutPool, cards); + _addCardFromPool(model.flamefruit, _flamefruitPool, cards); + _addCardFromPool(model.rockroot, _rockrootPool, cards); + _addCardFromPool(model.snowthistle, _snowthistlePool, cards); + + _addCardFromPool(model.coin, _coinPool, cards); + _addCardFromPool(model.metal, _metalPool, cards); + _addCardFromPool(model.hide, _hidePool, cards); + _addCardFromPool(model.lumber, _lumberPool, cards); + + for (int i = 0; i < model.treasure; i++) { + _addOtherType(_kTreasureCardId, cards, "treasure"); + } + + _drawPile.setList(cards); + _discardPile.setList([]); + _shuffle(); + } + + void _addOtherType(int id, List<LootCard> cards, String gfx) { + cards.add( + LootCard( + id: id, + baseValue: LootBaseValue.one, + enhanced: _enhancements[id.toString()] ?? 0, + lootType: LootType.other, + gfx: gfx, + ), + ); + } + + void _initMaterialPool(int startId, List<LootCard> list, String gfx) { + list.clear(); + for (int i = 0; i < _kMaterialOneCount; i++) { + list.add( + LootCard( + id: startId, + baseValue: LootBaseValue.one, + enhanced: _enhancements[startId.toString()] ?? 0, + lootType: LootType.materiel, + gfx: gfx, + ), + ); + startId++; + } + for (int i = 0; i < _kMaterialTwoCount; i++) { + list.add( + LootCard( + id: startId, + baseValue: LootBaseValue.oneIf3or4twoIfNot, + enhanced: _enhancements[startId.toString()] ?? 0, + lootType: LootType.materiel, + gfx: gfx, + ), + ); + startId++; + } + for (int i = 0; i < _kMaterialTwoCount; i++) { + list.add( + LootCard( + id: startId, + baseValue: LootBaseValue.oneIf4twoIfNot, + enhanced: _enhancements[startId.toString()] ?? 0, + lootType: LootType.materiel, + gfx: gfx, + ), + ); + startId++; + } + } + + void _initHerbPool(int startId, List<LootCard> list, String gfx) { + list.clear(); + for (int i = 0; i < _kHerbPoolCount; i++) { + list.add( + LootCard( + id: startId, + baseValue: LootBaseValue.one, + enhanced: _enhancements[startId.toString()] ?? 0, + lootType: LootType.materiel, + gfx: gfx, + ), + ); + startId++; + } + } + + void _initPools() { + _coinPool = []; + _lumberPool = []; + _hidePool = []; + _metalPool = []; + _axenutPool = []; + _arrowvinePool = []; + _rockrootPool = []; + _flamefruitPool = []; + _snowthistlePool = []; + _corpsecapPool = []; + + int id = 1; + + for (int i = 0; i < _kCoin1Count; i++) { + _addOtherType(id, _coinPool, "coin 1"); + id++; + } + for (int i = 0; i < _kCoin2Count; i++) { + _addOtherType(id, _coinPool, "coin 2"); + id++; + } + _addOtherType(id, _coinPool, "coin 3"); + id++; + _addOtherType(id, _coinPool, "coin 3"); + id++; + + _initMaterialPool(id, _lumberPool, "lumber"); + id += _kMaterialPoolSize; + _initMaterialPool(id, _hidePool, "hide"); + id += _kMaterialPoolSize; + _initMaterialPool(id, _metalPool, "metal"); + id += _kMaterialPoolSize; + _initHerbPool(id, _arrowvinePool, "arrowvine"); + id += _kHerbPoolSize; + _initHerbPool(id, _axenutPool, "axenut"); + id += _kHerbPoolSize; + _initHerbPool(id, _corpsecapPool, "corpsecap"); + id += _kHerbPoolSize; + _initHerbPool(id, _flamefruitPool, "flamefruit"); + id += _kHerbPoolSize; + _initHerbPool(id, _snowthistlePool, "snowthistle"); + id += _kHerbPoolSize; + _initHerbPool(id, _rockrootPool, "rockroot"); + } + + void addSpecial1418(_StateModifier _) { + if (!_hasCard1418) { + _hasCard1418 = true; + _drawPile.add( + LootCard( + id: _kSpecialCard1418, + lootType: LootType.other, + baseValue: LootBaseValue.one, + enhanced: 0, + gfx: "special 1418", + ), + ); + //add directly to current deck and shuffle. save state separately + _shuffle(); + } + } + + void addSpecial1419(_StateModifier _) { + if (!_hasCard1419) { + _hasCard1419 = true; + _drawPile.add( + LootCard( + id: _kSpecialCard1419, + lootType: LootType.other, + baseValue: LootBaseValue.one, + enhanced: 0, + gfx: "special 1419", + ), + ); + _shuffle(); + } + } + + void removeSpecial1418(_StateModifier _) { + _hasCard1418 = false; + _drawPile.removeWhere((element) => element.id == _kSpecialCard1418); + _discardPile.removeWhere((element) => element.id == _kSpecialCard1418); + } + + void removeSpecial1419(_StateModifier _) { + _hasCard1419 = false; + _drawPile.removeWhere((element) => element.id == _kSpecialCard1419); + _discardPile.removeWhere((element) => element.id == _kSpecialCard1419); + } + + List<LootCard> _getAvailableCards(List<LootCard> pool) { + List<LootCard> list = []; + for (final item in pool) { + if (!_drawPile.getList().any((element) => element.id == item.id)) { + list.add(item); + } + } + list.shuffle(); + return list; + } + + void addExtraCard(_StateModifier _, String identifier) { + _initPools(); + _shuffle(); + if (identifier == "hide") { + final pool = _getAvailableCards(_hidePool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[0] = _addedCards.first + 1; + } + } + if (identifier == "lumber") { + final pool = _getAvailableCards(_lumberPool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[1]++; + } + } + if (identifier == "metal") { + final pool = _getAvailableCards(_metalPool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[2]++; + } + } + if (identifier == "arrowvine") { + final pool = _getAvailableCards(_arrowvinePool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[3]++; + } + } + if (identifier == "axenut") { + final pool = _getAvailableCards(_axenutPool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[4]++; + } + } + if (identifier == "corpsecap") { + final pool = _getAvailableCards(_corpsecapPool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[5]++; + } + } + if (identifier == "flamefruit") { + final pool = _getAvailableCards(_flamefruitPool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[6]++; + } + } + if (identifier == "rockroot") { + final pool = _getAvailableCards(_rockrootPool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[7]++; + } + } + if (identifier == "snowthistle") { + final pool = _getAvailableCards(_snowthistlePool); + if (pool.isNotEmpty) { + _drawPile.add(pool.first); + _addedCards[8]++; + } + } + _shuffle(); + } + + void addEnhancement( + _StateModifier _, + int id, + int value, { + GameState? gameState, + GameData? gameData, + }) { + _enhancements[id.toString()] = value; + //reset loot deck + _initPools(); + final gs = gameState ?? getIt<GameState>(); + final gd = gameData ?? getIt<GameData>(); + String scenario = gs.scenario; + LootDeckModel? lootDeckModel = + gd.modelData[gs.currentCampaign]?.scenarios[scenario]?.lootDeck; + if (lootDeckModel != null) { + _setDeck(lootDeckModel); + } + } + + void _shuffle() { + while (_discardPile.isNotEmpty) { + LootCard card = _discardPile.pop(); + _drawPile.push(card); + } + _drawPile.shuffle(); + } + + void draw(_StateModifier _, {GameState? gameState}) { + //put top of draw pile on discard pile + LootCard card = _drawPile.pop(); + + //mark owner + final gs = gameState ?? getIt<GameState>(); + for (final item in gs.currentList) { + if (item.turnState == TurnsState.current && item is Character) { + if (!GameMethods.isObjectiveOrEscort(item.characterClass)) { + card.owner = item.characterClass.id; + break; + } + } + } + + _discardPile.push(card); + } + + Map<String, dynamic> toJson() => { + 'drawPile': _drawPile.getList().map((c) => c.toJson()).toList(), + 'discardPile': _discardPile.getList().map((c) => c.toJson()).toList(), + 'addedCards': _addedCards, + 'enhancements': _enhancements, + '1418': _hasCard1418, + '1419': _hasCard1419, + }; + + @override + String toString() => json.encode(toJson()); +} + +enum LootType { materiel, other } + +enum LootBaseValue { one, oneIf4twoIfNot, oneIf3or4twoIfNot } diff --git a/server/lib/core/state/modifier_deck.dart b/server/lib/core/state/modifier_deck.dart new file mode 100644 index 0000000..6575e01 --- /dev/null +++ b/server/lib/core/state/modifier_deck.dart @@ -0,0 +1,758 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class ModifierDeck { + static const int _kImbuementLevel1 = 1; + static const int _kImbuementLevel2 = 2; + static const int _kPlusMinus1Count = 5; + static const int _kPlus0Count = 6; + static const int _kCursePosition = 5; + + final String name; + final CardStack<ModifierCard> _drawPile = CardStack<ModifierCard>(); + final CardStack<ModifierCard> _discardPile = CardStack<ModifierCard>(); + final CardStack<ModifierCard> _removedPile = CardStack<ModifierCard>(); + final Map<String, int> _removables = { + "curse": 0, + "bless": 0, + "in-enfeeble": 0, + "vi-enfeeble": 0, + "vi-gr-enfeeble": 0, + "li-enfeeble": 0, + "in-empower": 0, + "rm-empower": 0, + "vi-empower": 0, + "vi-gr-empower": 0, + }; + + /// Removable gfx keys that get physical draw-pile card sync. In the + /// reference app this is exactly the set of counters that have a + /// `_handleRemovableCards` listener attached in `_initListeners()`, i.e. the + /// keys present at construction. Entries added later by `getRemovable()` + /// (e.g. "enfeeble") never trigger physical card sync. + final Set<String> _syncedRemovables = {}; + + int _badOmen = 0; + bool _corrosiveSpew = false; + int _addedMinusOnes = 0; + int _imbuement = 0; + + int _revealedCount = 0; + bool _cassandraSpecial = false; + + bool _needsShuffle = false; + bool get needsShuffle => _needsShuffle; + + BuiltList<ModifierCard> get drawPileContents => + BuiltList.of(_drawPile.getList()); + BuiltList<ModifierCard> get discardPileContents => + BuiltList.of(_discardPile.getList()); + BuiltList<ModifierCard> get removedPileContents => + BuiltList.of(_removedPile.getList()); + bool get drawPileIsEmpty => _drawPile.isEmpty; + bool get drawPileIsNotEmpty => _drawPile.isNotEmpty; + bool get discardPileIsEmpty => _discardPile.isEmpty; + bool get discardPileIsNotEmpty => _discardPile.isNotEmpty; + int get drawPileSize => _drawPile.size(); + int get discardPileSize => _discardPile.size(); + int get removedPileSize => _removedPile.size(); + ModifierCard get discardPileTop => _discardPile.peek; + ModifierCard get drawPileTop => _drawPile.peek; + + CardStack<ModifierCard> get drawPileNotifier => _drawPile; + int get badOmen => _badOmen; + bool get corrosiveSpew => _corrosiveSpew; + int get addedMinusOnes => _addedMinusOnes; + int get imbuement => _imbuement; + int get revealedCount => _revealedCount; + bool get cassandraSpecial => _cassandraSpecial; + + ModifierDeck(this.name) { + //build deck + _initDeck(); + _initListeners(); + } + + ModifierDeck.fromJson(this.name, Map<String, dynamic> modifierDeckData) { + _initDeck(); + _initListeners(); + updateFromJson(modifierDeckData); + } + + /// Resets this deck to the default 20-card state. + void resetToDefault() { + _initDeck(); + _cassandraSpecial = false; + } + + /// Updates this deck in-place from [modifierDeckData]. + void updateFromJson(Map<String, dynamic> modifierDeckData) { + // Reset removable counts first (the piles are fully replaced below + // anyway, so no physical card sync is needed here). + for (final key in _removables.keys) { + _removables[key] = 0; + } + _needsShuffle = false; + + for (final item in modifierDeckData["drawPile"] as List) { + String gfx = item["gfx"]; + if (gfx == "curse" || + gfx.contains("empower") || + gfx.contains("enfeeble") || + gfx == "bless") { + addRemovableValue(_StateModifier(), gfx, 1); + } + } + for (final item in modifierDeckData["discardPile"] as List) { + String gfx = item["gfx"]; + if (_isMultiplyType(gfx)) { + _needsShuffle = true; + } + } + + _drawPile.clear(); + _discardPile.clear(); + _removedPile.clear(); + _drawPile.setList(_getCardsFromJson(modifierDeckData, "drawPile")); + _discardPile.setList(_getCardsFromJson(modifierDeckData, "discardPile")); + if (modifierDeckData.containsKey('removedPile')) { + _removedPile.setList(_getCardsFromJson(modifierDeckData, "removedPile")); + } + + _imbuement = modifierDeckData.containsKey("imbuement") + ? modifierDeckData['imbuement'] as int + : 0; + _badOmen = modifierDeckData.containsKey('badOmen') + ? modifierDeckData["badOmen"] as int + : 0; + _corrosiveSpew = modifierDeckData.containsKey('corrosiveSpew') + ? modifierDeckData["corrosiveSpew"] as bool + : false; + _revealedCount = min( + modifierDeckData.containsKey('revealed') + ? modifierDeckData["revealed"] as int + : 0, + drawPileSize, + ); + _cassandraSpecial = modifierDeckData.containsKey('cassandra') + ? modifierDeckData["cassandra"] as bool + : false; + _addedMinusOnes = modifierDeckData.containsKey('addedMinusOnes') + ? modifierDeckData["addedMinusOnes"] as int + : 0; + } + + void setRemovableValue(_StateModifier _, String id, int value) { + if (_removables.containsKey(id)) { + _removables[id] = value; + if (_syncedRemovables.contains(id)) { + _handleRemovableCards(value, id); + } + } + } + + void addRemovableValue(_StateModifier _, String id, int value) { + final current = _removables[id]; + if (current != null) { + final newValue = current + value; + _removables[id] = newValue; + if (_syncedRemovables.contains(id)) { + _handleRemovableCards(newValue, id); + } + } + } + + int getRemovable(String id) { + _removables[id] ??= 0; + return _removables[id] ?? 0; + } + + void moveCardToRemovedPile(_StateModifier s, String gfx) { + if (hasCard(gfx)) { + removeCard(s, gfx); + _removedPile.add(ModifierCard(CardType.add, gfx)); + } + } + + void restoreCardFromRemovedPile(_StateModifier s, String gfx, CardType type) { + addCard(s, gfx, type); + _removedPile.removeFirstWhere((card) => card.gfx == gfx); + } + + void setBadOmen(_StateModifier _, int value) { + _badOmen = value; + } + + void setCorrosiveSpew(_StateModifier _) { + _corrosiveSpew = true; + } + + void addCSSanctuary(_StateModifier s, {GameState? gameState}) { + //adds one of each + final gs = gameState ?? getIt<GameState>(); + _drawPile.add(gs._sanctuaryDeck.drawFlip(s)); + _drawPile.add(gs._sanctuaryDeck.drawMult(s)); + _drawPile.shuffle(); + } + + void removeCSSanctuary(_StateModifier _, {GameState? gameState}) { + var list = _drawPile.getList(); + final gs = gameState ?? getIt<GameState>(); + for (int i = list.length - 1; i >= 0; i--) { + if (list[i].gfx.startsWith("sanctuary")) { + gs._sanctuaryDeck.returnCard(list[i].gfx); + _drawPile.removeAt(i); + } + } + list = _discardPile.getList(); + for (int i = list.length - 1; i >= 0; i--) { + if (list[i].gfx.startsWith("sanctuary")) { + gs._sanctuaryDeck.returnCard(list[i].gfx); + _discardPile.removeAt(i); + } + } + } + + bool hasCSSanctuary() { + if (_drawPile.getList().firstWhereOrNull((test) { + return test.gfx.startsWith("sanctuary"); + }) != + null || + _discardPile.getList().firstWhereOrNull((test) { + return test.gfx.startsWith("sanctuary"); + }) != + null) { + return true; + } + return false; + } + + void addCSPartyCard(_StateModifier s, int type) { + addCard(s, "party/$type", CardType.remove); + } + + void removeCSPartyCard(_StateModifier _) { + _drawPile.removeWhere((test) { + return test.gfx.startsWith("party/"); + }); + _discardPile.removeWhere((test) { + return test.gfx.startsWith("party/"); + }); + } + + bool hasPartyCard() { + if (_drawPile.getList().firstWhereOrNull((test) { + return test.gfx.startsWith("party/"); + }) != + null || + _discardPile.getList().firstWhereOrNull((test) { + return test.gfx.startsWith("party/"); + }) != + null) { + return true; + } + return false; + } + + void addHailSpecial(_StateModifier s) { + addCard(s, "special/hail", CardType.add); + } + + void removeHailSpecial(_StateModifier s) { + removeCard(s, "special/hail"); + } + + void revealCards(_StateModifier _, int amount) { + _revealedCount = amount; + } + + void setCassandraSpecial(_StateModifier _, bool on) { + _cassandraSpecial = on; + } + + bool hasHail() { + if (_discardPile.getList().firstWhereOrNull( + (item) => item.gfx == "special/hail", + ) != + null) { + return true; + } + if (_drawPile.getList().firstWhereOrNull( + (item) => item.gfx == "special/hail", + ) != + null) { + return true; + } + return false; + } + + void addMinusOne(_StateModifier _) { + _addedMinusOnes++; + _drawPile.insert(0, ModifierCard(CardType.add, "minus1")); + _shuffleDrawPileRespectCassandra(); + _revealedCount = 0; + if (_addedMinusOnes < 0) { + //do not add/remove extra minus ones to removed pile + _removedPile.removeFirstWhere((item) => item.gfx == "minus1"); + } + } + + void removeMinusOne(_StateModifier _) { + _shuffle(); + + final card = _removeCardFromDrawPile("minus1"); + if (card != null) { + _addedMinusOnes--; + if (_addedMinusOnes < 0) { + _removedPile.add(card); + } + } + } + + bool hasMinus1() { + return _drawPile.getList().firstWhereOrNull( + (element) => element.gfx == "minus1", + ) != + null || + _discardPile.getList().firstWhereOrNull( + (element) => element.gfx == "minus1", + ) != + null; + } + + bool hasMinus2() { + return !(_removedPile.getList().firstWhereOrNull( + (element) => element.gfx == "minus2", + ) != + null); + } + + bool hasNull() { + return _drawPile.getList().firstWhereOrNull( + (element) => element.gfx == "nullAttack", + ) != + null || + _discardPile.getList().firstWhereOrNull( + (element) => element.gfx == "nullAttack", + ) != + null; + } + + void removeNull(_StateModifier _) { + _shuffle(); + final card = _removeCardFromDrawPile("nullAttack"); + if (card != null) { + _removedPile.add(card); + } + } + + void addNull(_StateModifier _) { + _drawPile.add(ModifierCard(CardType.multiply, "nullAttack")); + _removedPile.removeFirstWhere((item) => item.gfx == "nullAttack"); + _shuffle(); + } + + bool hasCard(String gfx) { + final drawPileHas = + _drawPile.getList().firstWhereOrNull((test) => test.gfx == gfx) != null; + final discardPileHas = + _discardPile.getList().firstWhereOrNull((test) => test.gfx == gfx) != + null; + return (drawPileHas || discardPileHas); + } + + void removeCard(_StateModifier _, String gfx) { + _shuffle(); + _removeCardFromDrawPile(gfx); + _shuffle(); + } + + void removeCardFromDiscard(_StateModifier _, int index) { + final card = _discardPile.removeAt(index); + _removedPile.add(card); + if (card.gfx == "minus1") { + _addedMinusOnes--; + } + } + + void removeCardFromDrawPile(_StateModifier _, int index) { + final card = _drawPile.removeAt(index); + _removedPile.add(card); + if (card.gfx == "minus1") { + _addedMinusOnes--; + } + if (_revealedCount > _drawPile.size() - 1 - index) { + _revealedCount--; + } + } + + void returnCardToDiscard(_StateModifier _, int index) { + final card = _removedPile.removeAt(index); + _discardPile.add(card); + if (card.gfx == "minus1") { + _addedMinusOnes++; + } + } + + void returnCardToDrawPileFromRemoved(_StateModifier _, int index) { + final card = _removedPile.removeAt(index); + _drawPile.add(card); + _revealedCount++; + if (card.gfx == "minus1") { + _addedMinusOnes++; + } + } + + void returnCardToDrawPile(_StateModifier _) { + final card = _discardPile.pop(); + _drawPile.push(card); + //todo: how to tell if revealed should change? if it is over 0? + } + + void addCard(_StateModifier _, String id, CardType type) { + _drawPile.add(ModifierCard(type, id)); + _shuffle(); + } + + void removeMinusTwo(_StateModifier _) { + _shuffle(); + final card = _removeCardFromDrawPile("minus2"); + if (card != null) { + _removedPile.add(card); + } + } + + void addMinusTwo(_StateModifier _) { + _drawPile.add(ModifierCard(CardType.add, "minus2")); + _removedPile.removeFirstWhere((item) => item.gfx == "minus2"); + _shuffle(); + } + + void setImbue1(_StateModifier _) { + assert(name.isEmpty); //only basic deck for this feature + + _shuffle(); + _removeCardFromDrawPile("minus1"); + _removeCardFromDrawPile("minus1"); + _removeCardFromDrawPile("minus1"); + _drawPile.add(ModifierCard(CardType.add, "imbue-plus1")); + _drawPile.add(ModifierCard(CardType.add, "imbue-plus1")); + _drawPile.add(ModifierCard(CardType.add, "imbue-plus1")); + _drawPile.add(ModifierCard(CardType.add, "imbue-plus2muddle")); + _drawPile.add(ModifierCard(CardType.add, "imbue-plus0poison")); + _shuffle(); + _imbuement = _kImbuementLevel1; + } + + void setImbue2(_StateModifier m) { + assert(name.isEmpty); //only basic deck for this feature + + if (_imbuement == 0) { + setImbue1(m); + } + + _shuffle(); + _removeCardFromDrawPile("minus2"); + _removeCardFromDrawPile("plus0"); + _removeCardFromDrawPile("plus0"); + + _drawPile.add(ModifierCard(CardType.add, "imbue2-plus3")); + _drawPile.add(ModifierCard(CardType.add, "imbue2-plus1heal1")); + _drawPile.add(ModifierCard(CardType.add, "imbue2-plus1heal1")); + _drawPile.add(ModifierCard(CardType.add, "imbue2-plus1curse")); + _drawPile.add(ModifierCard(CardType.add, "imbue2-plus0wound")); + _shuffle(); + _imbuement = _kImbuementLevel2; + } + + void resetImbue(_StateModifier _) { + assert(name.isEmpty); //only basic deck for this feature + + if (_imbuement != 0) { + _shuffle(); + _drawPile.removeWhere((element) => element.gfx.startsWith("imbue")); + + _drawPile.add(ModifierCard(CardType.add, "minus1")); + _drawPile.add(ModifierCard(CardType.add, "minus1")); + _drawPile.add(ModifierCard(CardType.add, "minus1")); + if (_imbuement == _kImbuementLevel2) { + if (hasMinus2()) { + //if minus2 has not been separately removed + _drawPile.add(ModifierCard(CardType.add, "minus2")); + } + _drawPile.add(ModifierCard(CardType.add, "plus0")); + _drawPile.add(ModifierCard(CardType.add, "plus0")); + } + _imbuement = 0; + _shuffle(); + } + } + + void shuffle(_StateModifier _) { + if (_cassandraSpecial) { + //dont shuffle the revealed cards + _shuffleOnlyBelowRevealed(); + } else { + _shuffle(); + } + } + + void shuffleUnDrawn(_StateModifier _) { + _drawPile.shuffle(); + _revealedCount = 0; + } + + void draw(_StateModifier _) { + if (_revealedCount > 0) { + _revealedCount--; + } + //shuffle deck, for the case the deck ends during play + if (_drawPile.isEmpty) { + _shuffle(); + } + //put top of draw pile on discard pile + if (_drawPile.isNotEmpty) { + ModifierCard card = _drawPile.pop(); + if (card.type == CardType.multiply) { + _needsShuffle = true; + } + + if (_removables[card.gfx] != null) { + addRemovableValue(_StateModifier(), card.gfx, -1); + } + _discardPile.push(card); + } + } + + void reorderCards(_StateModifier s, int newIndex, int oldIndex) { + List<ModifierCard> list = List.of(_drawPile.getList()); + final item = list.removeAt(oldIndex); + list.insert(newIndex, item); + _drawPile.setList(list); + + //if rearranging between revealed and unrevealed then un-reveal everything below the unknown moved card. + final revertOldIndex = _drawPile.size() - oldIndex; + final revertNewIndex = _drawPile.size() - newIndex; + if (revertOldIndex <= revealedCount && revertNewIndex > revealedCount) { + //moving one revealed card to unrevealed area - hide one + revealCards(s, revealedCount - 1); + } + if (revertNewIndex <= revealedCount && revertOldIndex > revealedCount) { + //hide new index card and those below + revealCards(s, revertNewIndex - 1); + } + } + + Map<String, dynamic> toJson() => { + 'addedMinusOnes': _addedMinusOnes, + 'imbuement': _imbuement, + 'badOmen': _badOmen, + 'corrosiveSpew': _corrosiveSpew, + 'revealed': _revealedCount, + 'cassandra': _cassandraSpecial, + 'drawPile': _drawPile.getList().map((c) => c.toJson()).toList(), + 'removedPile': _removedPile.getList().map((c) => c.toJson()).toList(), + 'discardPile': _discardPile.getList().map((c) => c.toJson()).toList(), + }; + + @override + String toString() => json.encode(toJson()); + + void _initListeners() { + // UI-only in the reference app. In the reference this attached the + // _handleRemovableCards listener to each counter notifier, so physical + // card sync only ever happened for the keys present here (always the ten + // initial ones); record that set for set/addRemovableValue. + _syncedRemovables + ..clear() + ..addAll(_removables.keys); + } + + List<ModifierCard> _getCardsFromJson( + Map<String, dynamic> modifierDeckData, + String deckId, + ) { + List<ModifierCard> newList = []; + for (final item in modifierDeckData[deckId] as List) { + String gfx = item["gfx"]; + gfx = gfx.replaceAll("-allies", ""); + if (gfx == "curse") { + newList.add(ModifierCard(CardType.remove, gfx)); + } else if (gfx.contains("enfeeble")) { + if (gfx == "enfeeble") { + //if updating from old version + gfx = "in-enfeeble"; + } + newList.add(ModifierCard(CardType.remove, gfx)); + } else if (gfx.contains("empower")) { + newList.add(ModifierCard(CardType.remove, gfx)); + } else if (gfx == "bless") { + newList.add(ModifierCard(CardType.remove, gfx)); + } else if (_isMultiplyType(gfx)) { + newList.add(ModifierCard(CardType.multiply, gfx)); + } else { + newList.add(ModifierCard(CardType.add, gfx)); + } + } + return newList; + } + + void _initDeck() { + List<ModifierCard> cards = []; + cards.add(ModifierCard(CardType.add, "minus2")); + cards.add(ModifierCard(CardType.add, "plus2")); + cards.add(ModifierCard(CardType.multiply, "doubleAttack")); + cards.add(ModifierCard(CardType.multiply, "nullAttack")); + for (int i = 0; i < _kPlusMinus1Count; i++) { + cards.add(ModifierCard(CardType.add, "minus1")); + cards.add(ModifierCard(CardType.add, "plus1")); + } + for (int i = 0; i < _kPlus0Count; i++) { + cards.add(ModifierCard(CardType.add, "plus0")); + } + _drawPile.setList(cards); + _discardPile.setList([]); + _removedPile.setList([]); + _shuffle(); + _badOmen = 0; + _corrosiveSpew = false; + _addedMinusOnes = 0; + _imbuement = 0; + _needsShuffle = false; + for (final item in _removables.keys) { + _removables[item] = 0; + } + } + + ModifierCard? _removeCardFromDrawPile(String gfx) { + final card = _drawPile.getList().lastWhereOrNull( + (element) => element.gfx == gfx, + ); + if (card != null) { + _drawPile.remove(card); + _drawPile.shuffle(); + } + return card; + } + + /// Syncs the physical removable cards in the draw pile with the + /// [notifierValue] stored in [_removables] for [gfx]. In the reference app + /// this ran as a listener on the removable counter notifiers; it is now + /// called directly from [setRemovableValue] and [addRemovableValue]. + void _handleRemovableCards(int notifierValue, String gfx) { + //count and add or remove, then shuffle + int count = 0; + bool shuffle = true; + for (final item in _drawPile.getList()) { + if (item.gfx == gfx) { + count++; + } + } + if (count == notifierValue) { + shuffle = false; + } else if (count < notifierValue) { + for (int i = count; i < notifierValue; i++) { + if (gfx == "rm-empower" && corrosiveSpew) { + shuffle = false; + //put on top + //_drawPile.insert(0, ModifierCard(CardType.remove, gfx)); + _drawPile.push(ModifierCard(CardType.remove, gfx)); + } else if (gfx == "curse" && _badOmen > 0) { + _badOmen--; + shuffle = false; + //put in sixth or as far down as it goes. + int position = _kCursePosition; + final size = _drawPile.getList().length; + if (size < _kPlus0Count) { + position = size; + } + _drawPile.insert(size - position, ModifierCard(CardType.remove, gfx)); + } else { + _drawPile.insert(0, ModifierCard(CardType.remove, gfx)); + } + } + } else { + int toRemove = count - notifierValue; + for (int i = 0; i < toRemove; i++) { + _drawPile.removeFirstWhere((card) => card.gfx == gfx); + } + } + if (shuffle) { + _shuffleDrawPileRespectCassandra(); + } + } + + void _shuffle() { + while (_discardPile.isNotEmpty) { + ModifierCard card = _discardPile.pop(); + //remove curse and bless + if (card.type != CardType.remove) { + _drawPile.push(card); + } + } + _drawPile.shuffle(); + + _needsShuffle = false; + _revealedCount = 0; + } + + void _shuffleOnlyBelowRevealed() { + final revealCount = _revealedCount; + List<ModifierCard> revealed = []; + for (int i = 0; i < _revealedCount; i++) { + revealed.insert(0, _drawPile.pop()); + } + _shuffle(); + _revealedCount = revealCount; + for (int i = 0; i < _revealedCount; i++) { + _drawPile.add(revealed[i]); + } + } + + void _shuffleDrawPileRespectCassandra() { + if (_cassandraSpecial) { + //dont shuffle the revealed cards + List<ModifierCard> revealed = []; + for (int i = 0; i < _revealedCount; i++) { + revealed.insert(0, _drawPile.pop()); + } + _drawPile.shuffle(); + for (int i = 0; i < _revealedCount; i++) { + _drawPile.add(revealed[i]); + } + } else { + _revealedCount = 0; + _drawPile.shuffle(); + } + } + + bool _isMultiplyType(String gfx) { + if (gfx.contains("nullAttack") || gfx.contains("doubleAttack")) { + return true; + } + if (gfx == "P4" && name == "Nightshroud") { + if (GameMethods.getCharacterByName( + "Nightshroud", + )?.characterClass.edition == + "Gloomhaven 2nd Edition") { + return true; + } + } + return false; + } +} + +enum CardType { add, multiply, remove } + +class ModifierCard { + final CardType type; + final String gfx; + + ModifierCard(this.type, this.gfx); + + Map<String, dynamic> toJson() => {'gfx': gfx}; + + @override + String toString() => '{"gfx": "$gfx" }'; +} diff --git a/server/lib/core/state/monster.dart b/server/lib/core/state/monster.dart new file mode 100644 index 0000000..6ed3f67 --- /dev/null +++ b/server/lib/core/state/monster.dart @@ -0,0 +1,198 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class Monster extends ListItemData { + Monster(String name, int level, this._isAlly, {GameData? gameData}) + : type = _findType(name, gameData) { + id = name; + _level = level; + _addAbilityDeck(); + } + + static MonsterModel _findType(String name, GameData? gameData) { + final gd = gameData ?? getIt<GameData>(); + for (final key in gd.modelData.keys) { + final campaign = gd.modelData[key]; + if (campaign == null) continue; + if (campaign.monsters.containsKey(name)) { + final model = campaign.monsters[name]; + if (model != null) return model; + } + } + throw StateError('Monster model not found: $name'); + } + + MonsterModel type; + final List<MonsterInstance> _monsterInstances = []; + final BuiltList<MonsterInstance> _monsterInstancesNotifier = BuiltList.of([]); + int _level = 0; + bool _isAlly; + bool _isActive = false; + int _version = 0; + + int get level => _level; + bool get isAlly => _isAlly; + + //note: this is only used for the no standee tracking setting + bool get isActive => _isActive; + + BuiltList<MonsterInstance> get monsterInstances => + BuiltList.of(_monsterInstances); + BuiltList<MonsterInstance> get monsterInstancesNotifier => + _monsterInstancesNotifier; + + void _notifyMonsterInstances() { + // UI-only in the reference app + } + + /// Public guarded notify. The per-instance notification was UI-only in the + /// reference app; kept as a no-op hook for API compatibility. + void notifyMonsterInstances(_StateModifier _) { + _notifyMonsterInstances(); + } + + Monster.fromJson(Map<String, dynamic> json, {GameData? gameData}) + : _isAlly = false, + type = _findType(json['type'] as String, gameData) { + id = json['id']; + final turnStateIdx = json['turnState'] as int?; + if (turnStateIdx != null && + turnStateIdx >= 0 && + turnStateIdx < TurnsState.values.length) { + _turnState = TurnsState.values[turnStateIdx]; + } + if (json.containsKey("note")) { + _note = json["note"] as String; + } + _level = json['level']; + if (json.containsKey("isAlly")) { + _isAlly = json['isAlly']; + } + if (json.containsKey("isActive")) { + _isActive = json['isActive']; + } + + List<Object?> instanceList = json["monsterInstances"] as List<Object?>; + + _monsterInstances.clear(); + for (Map<String, dynamic> item + in instanceList.cast<Map<String, dynamic>>()) { + _monsterInstances.add(MonsterInstance.fromJson(item)); + } + + //fixing update issue, when _isActive is repurposed to work even with standees + if (_monsterInstances.isNotEmpty && !_isActive) { + if (!json.containsKey("v")) { + _isActive = true; + } + } + if (json.containsKey("v")) { + _version = json['v']; + } + _notifyMonsterInstances(); + } + + /// Updates all mutable fields in-place from [json]. + void updateFromJson(Map<String, dynamic> json) { + final turnStateIdx = json['turnState'] as int?; + if (turnStateIdx != null && + turnStateIdx >= 0 && + turnStateIdx < TurnsState.values.length) { + _turnState = TurnsState.values[turnStateIdx]; + } + _note = json.containsKey("note") ? json["note"] as String : ""; + _level = json['level'] as int; + if (json.containsKey("isAlly")) { + _isAlly = json['isAlly'] as bool; + } + if (json.containsKey("isActive")) { + _isActive = json['isActive'] as bool; + } + + _monsterInstances.clear(); + for (Map<String, dynamic> item in json["monsterInstances"] as List) { + _monsterInstances.add(MonsterInstance.fromJson(item)); + } + + // Backwards-compat: set isActive when instances exist but version flag absent. + if (_monsterInstances.isNotEmpty && !_isActive) { + if (!json.containsKey("v")) { + _isActive = true; + } + } + if (json.containsKey("v")) { + _version = json['v'] as int; + } + _notifyMonsterInstances(); + } + + void setMonsterInstances(_StateModifier _, List<MonsterInstance> instances) { + _monsterInstances.clear(); + _monsterInstances.addAll(instances); + } + + void clearMonsterInstances(_StateModifier _) { + _monsterInstances.clear(); + } + + void sortMonsterInstances(_StateModifier s) { + RoundMethods.sortMonsterInstances(s, _monsterInstances); + } + + void setActive(_StateModifier _, bool value) { + _isActive = value; + } + + bool hasElites() { + for (final instance in _monsterInstances) { + if (instance.type == MonsterType.elite) { + return true; + } + } + return false; + } + + //includes boss + bool hasNormal() { + for (final instance in _monsterInstances) { + if (instance.type != MonsterType.elite) { + return true; + } + } + return false; + } + + void setLevel(_StateModifier _, int level) { + _level = level; + for (final item in _monsterInstances) { + item._setLevel(this); + } + } + + @override + Map<String, dynamic> toJson() => { + 'id': id, + 'turnState': turnState.index, + 'note': note, + 'isActive': isActive, + 'type': type.name, + 'monsterInstances': _monsterInstances.map((m) => m.toJson()).toList(), + 'isAlly': isAlly, + 'v': _version, + 'level': level, + }; + + @override + String toString() => json.encode(toJson()); + + void _addAbilityDeck({GameState? gameState}) { + final gs = gameState ?? getIt<GameState>(); + for (MonsterAbilityState deck in gs.currentAbilityDecks) { + if (deck.name == type.deck) { + return; + } + } + gs._currentAbilityDecks.add(MonsterAbilityState(type.deck)); + } +} diff --git a/server/lib/core/state/monster_ability_state.dart b/server/lib/core/state/monster_ability_state.dart new file mode 100644 index 0000000..161a063 --- /dev/null +++ b/server/lib/core/state/monster_ability_state.dart @@ -0,0 +1,98 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class MonsterAbilityState { + final String name; + + int drawPileVersion = 0; + + final CardStack<MonsterAbilityCardModel> _drawPile = + CardStack<MonsterAbilityCardModel>(); + final CardStack<MonsterAbilityCardModel> _discardPile = + CardStack<MonsterAbilityCardModel>(); + + int get lastRoundDrawn => _lastRoundDrawn; + int _lastRoundDrawn = 0; + + BuiltList<MonsterAbilityCardModel> get drawPileContents => + BuiltList.of(_drawPile.getList()); + BuiltList<MonsterAbilityCardModel> get discardPileContents => + BuiltList.of(_discardPile.getList()); + bool get drawPileIsEmpty => _drawPile.isEmpty; + bool get drawPileIsNotEmpty => _drawPile.isNotEmpty; + bool get discardPileIsEmpty => _discardPile.isEmpty; + bool get discardPileIsNotEmpty => _discardPile.isNotEmpty; + MonsterAbilityCardModel get drawPileTop => _drawPile.peek; + MonsterAbilityCardModel get discardPileTop => _discardPile.peek; + int get drawPileSize => _drawPile.size(); + int get discardPileSize => _discardPile.size(); + + MonsterAbilityState(this.name, {GameData? gameData}) { + final gd = gameData ?? getIt<GameData>(); + + List<MonsterAbilityDeckModel> monsters = []; + for (String key in gd.modelData.keys) { + monsters.addAll(gd.modelData[key]?.monsterAbilities ?? []); + } + for (MonsterAbilityDeckModel model in monsters) { + if (name == model.name) { + _drawPile.init(model.cards); + _shuffle(); + break; + } + } + + _lastRoundDrawn = 0; + } + + void shuffle(_StateModifier _) { + _shuffle(); + drawPileVersion++; + } + + void shuffleUnDrawn(_StateModifier _) { + _drawPile.shuffle(); + drawPileVersion++; + } + + void removeFromDrawPile(_StateModifier _, MonsterAbilityCardModel card) { + _drawPile.remove(card); + drawPileVersion++; + } + + void removeFromDiscardPile(_StateModifier _, MonsterAbilityCardModel card) { + _discardPile.remove(card); + } + + void reorderDrawPile(_StateModifier _, int oldIndex, int newIndex) { + final list = _drawPile.getList(); + list.insert(newIndex, list.removeAt(oldIndex)); + _drawPile.setList(list); + } + + void _shuffle() { + while (_discardPile.isNotEmpty) { + _drawPile.push(_discardPile.pop()); + } + _drawPile.shuffle(); + } + + void draw(_StateModifier _, {GameState? gameState}) { + //put top of draw pile on discard pile + if (_drawPile.isNotEmpty) { + _discardPile.push(_drawPile.pop()); + } + _lastRoundDrawn = (gameState ?? getIt<GameState>()).totalRounds; + } + + Map<String, dynamic> toJson() => { + 'name': name, + 'drawPile': _drawPile.getList().map((c) => c.toJson()).toList(), + 'discardPile': _discardPile.getList().map((c) => c.toJson()).toList(), + 'lastRoundDrawn': lastRoundDrawn, + }; + + @override + String toString() => json.encode(toJson()); +} diff --git a/server/lib/core/state/monster_instance.dart b/server/lib/core/state/monster_instance.dart new file mode 100644 index 0000000..a3fde0c --- /dev/null +++ b/server/lib/core/state/monster_instance.dart @@ -0,0 +1,198 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class MonsterInstance extends FigureState { + static const int _kIncarnateHealthMultiplier = 2; + MonsterInstance( + this.standeeNr, + this._type, + bool summoned, + Monster monster, { + GameState? gameState, + }) { + _setLevel(monster); + gfx = monster.type.gfx; + name = monster.type.name; + move = 0; //only used for summons + attack = 0; + range = 0; + _roundSummoned = summoned ? (gameState ?? getIt<GameState>()).round : -1; + } + + MonsterInstance.summon( + this.standeeNr, + this._type, + this.name, + int summonHealth, + this.move, + this.attack, + this.range, + this.gfx, + this._roundSummoned, + ) { + //deal with summon init + _maxHealth = summonHealth; + _health = summonHealth; + } + + String getId() { + return name + gfx + standeeNr.toString(); + } + + int standeeNr = 0; + + void setType(_StateModifier _, MonsterType value) { + _type = value; + } + + MonsterType get type => _type; + MonsterType _type = + MonsterType.normal; //can't be final due to ice wraith special + String name = ''; + String gfx = ''; + + //summon stats. not used currently + int move = 0; + int attack = 0; + int range = 0; + + int get roundSummoned => _roundSummoned; + void setRoundSummoned(_StateModifier _, int value) { + _roundSummoned = value; + } + + int _roundSummoned = -1; + + void _setLevel(Monster monster, {GameState? gameState}) { + StatValue newHealthValue = const IntStatValue( + 10, + ); //need to put something outer than 0 or the standee will die immediately causing glitch + final levels = monster.type.levels; + final levelIndex = levels.isEmpty + ? -1 + : monster.level.clamp(0, levels.length - 1); + if (levelIndex >= 0) { + if (type == MonsterType.boss) { + newHealthValue = levels[levelIndex].boss?.health ?? newHealthValue; + } else if (type == MonsterType.elite) { + newHealthValue = levels[levelIndex].elite?.health ?? newHealthValue; + } else if (type == MonsterType.normal) { + newHealthValue = levels[levelIndex].normal?.health ?? newHealthValue; + } + } + int? value = StatCalculator.calculateFormula(newHealthValue); + if (value != null) { + _maxHealth = value; + } else { + final gs = gameState ?? getIt<GameState>(); + //handle edge case + if (newHealthValue is FormulaStatValue && + newHealthValue.formula == "Hollowpact") { + int value = 7; + for (final item in gs.currentList) { + if (item is Character && item.id == "Hollowpact") { + final healthByLevel = item.characterClass.healthByLevel; + final level = item.characterState.level; + if (level >= 1 && level <= healthByLevel.length) { + value = healthByLevel[level - 1]; + } + break; + } + } + _maxHealth = value; + } + if (newHealthValue is FormulaStatValue && + newHealthValue.formula == "Incarnate") { + int value = 36; //double Incarnates level 5 health + for (final item in gs.currentList) { + if (item is Character && item.id == "Incarnate") { + final healthByLevel = item.characterClass.healthByLevel; + final level = item.characterState.level; + if (level >= 1 && level <= healthByLevel.length) { + value = healthByLevel[level - 1] * _kIncarnateHealthMultiplier; + } + break; + } + } + _maxHealth = value; + } + } + _level = monster.level; + _health = maxHealth; + } + + Map<String, dynamic> toJson() => { + 'health': health, + 'maxHealth': maxHealth, + 'level': level, + 'standeeNr': standeeNr, + 'move': move, + 'attack': attack, + 'range': range, + 'name': name, + 'gfx': gfx, + 'roundSummoned': roundSummoned, + 'type': type.index, + 'chill': chill, + 'plague': plague, + 'conditions': conditions.map((c) => c.index).toList(), + 'conditionsAddedThisTurn': _conditionsAddedThisTurn + .map((c) => c.index) + .toList(), + 'conditionsAddedPreviousTurn': _conditionsAddedPreviousTurn + .map((c) => c.index) + .toList(), + }; + + @override + String toString() => json.encode(toJson()); + + MonsterInstance.fromJson(Map<String, dynamic> json) { + standeeNr = json["standeeNr"]; + _health = json["health"]; + _level = json["level"]; + _maxHealth = json["maxHealth"]; + name = json["name"]; + gfx = json["gfx"]; + final typeIdx = json["type"] as int?; + _type = + (typeIdx != null && typeIdx >= 0 && typeIdx < MonsterType.values.length) + ? MonsterType.values[typeIdx] + : MonsterType.normal; + move = json["move"]; + attack = json["attack"]; + range = json["range"]; + _roundSummoned = json.containsKey("roundSummoned") + ? json["roundSummoned"] + : -1; + _chill = json["chill"]; + if (json.containsKey("plague")) { + _plague = json["plague"]; + } + final condis = json["conditions"]; + for (int item in condis) { + if (item >= 0 && item < Condition.values.length) { + conditions.add(Condition.values[item]); + } + } + + if (json.containsKey("conditionsAddedThisTurn")) { + List<Object?> condis2 = json["conditionsAddedThisTurn"] as List<Object?>; + for (int item in condis2.cast<int>()) { + if (item >= 0 && item < Condition.values.length) { + _conditionsAddedThisTurn.add(Condition.values[item]); + } + } + } + if (json.containsKey("conditionsAddedPreviousTurn")) { + List<Object?> condis3 = + json["conditionsAddedPreviousTurn"] as List<Object?>; + for (int item in condis3.cast<int>()) { + if (item >= 0 && item < Condition.values.length) { + _conditionsAddedPreviousTurn.add(Condition.values[item]); + } + } + } + } +} diff --git a/server/lib/core/state/note_row.dart b/server/lib/core/state/note_row.dart new file mode 100644 index 0000000..5375da0 --- /dev/null +++ b/server/lib/core/state/note_row.dart @@ -0,0 +1,96 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +/// A free-form note that lives in the main list as its own row, styled like a +/// player/monster row but in a user-pickable colour. +/// +/// A note can be unlinked (a free-floating row placed wherever the user drags +/// it) or linked to a figure (a character or monster row) by that figure's +/// [id]. When linked it is kept positioned directly beneath its target by +/// [GameState._reflowNoteRows]. For a monster target it may additionally be +/// pinned to a specific [standeeNr] to annotate one standee rather than the +/// whole group. +class NoteRow extends ListItemData { + // Slate tone, clearly distinct from character/monster rows. + static const int defaultColor = 0xFF4E5D6C; + + String _text = ""; + int _color = defaultColor; + // "" means unlinked. + String _linkedId = ""; + // 0 means "whole group / not standee-specific". + int _standeeNr = 0; + + String get text => _text; + int get color => _color; + String get linkedId => _linkedId; + int get standeeNr => _standeeNr; + + bool get isLinked => _linkedId.isNotEmpty; + + NoteRow(String anId) { + id = anId; + } + + NoteRow.create( + String anId, { + String text = "", + int color = defaultColor, + String linkedId = "", + int standeeNr = 0, + }) { + id = anId; + _text = text; + _color = color; + _linkedId = linkedId; + _standeeNr = standeeNr; + } + + NoteRow.fromJson(Map<String, dynamic> json) { + id = json['id'] as String; + _applyJson(json); + } + + /// Updates fields in-place (preserving object identity across network + /// syncs). + void updateFromJson(Map<String, dynamic> json) { + _applyJson(json); + } + + void _applyJson(Map<String, dynamic> json) { + _text = json['text'] as String? ?? ""; + _color = json['color'] as int? ?? defaultColor; + _linkedId = json['linkedId'] as String? ?? ""; + _standeeNr = json['standeeNr'] as int? ?? 0; + } + + void setText(_StateModifier _, String value) { + _text = value; + } + + void setColor(_StateModifier _, int value) { + _color = value; + } + + /// Links the note to [linkedId] (a figure id; "" to unlink) and, for monster + /// targets, an optional [standeeNr] (0 for the whole group). + void setLink(_StateModifier _, String linkedId, int standeeNr) { + _linkedId = linkedId; + _standeeNr = linkedId.isEmpty ? 0 : standeeNr; + } + + @override + Map<String, dynamic> toJson() => { + 'id': id, + // Discriminator used by GameSaveState.load to rebuild the right type. + 'noteRow': true, + 'text': _text, + 'color': _color, + 'linkedId': _linkedId, + 'standeeNr': _standeeNr, + }; + + @override + String toString() => json.encode(toJson()); +} diff --git a/server/lib/core/state/sanctuary_deck.dart b/server/lib/core/state/sanctuary_deck.dart new file mode 100644 index 0000000..8858fea --- /dev/null +++ b/server/lib/core/state/sanctuary_deck.dart @@ -0,0 +1,85 @@ +part of 'game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class SanctuaryDeck { + static const int _kCardTypeCount = 5; + + final CardStack<ModifierCard> _multPile = CardStack<ModifierCard>(); + final CardStack<ModifierCard> _flipPile = CardStack<ModifierCard>(); + + SanctuaryDeck() { + //build deck + _initDeck(); + } + + SanctuaryDeck.fromJson(Map<String, dynamic> modifierDeckData) { + _initDeck(); + + List<ModifierCard> newMultList = []; + List<ModifierCard> newFlipList = []; + for (final item in modifierDeckData["multPile"] as List) { + String gfx = item["gfx"]; + newMultList.add(ModifierCard(CardType.remove, gfx)); + } + for (final item in modifierDeckData["flipPile"] as List) { + String gfx = item["gfx"]; + newFlipList.add(ModifierCard(CardType.remove, gfx)); + } + _multPile.setList(newMultList); + _flipPile.setList(newFlipList); + } + + ModifierCard drawMult(_StateModifier _) { + if (_multPile.isEmpty) { + _initDeck(); + } + _multPile.shuffle(); + return _multPile.pop(); + } + + ModifierCard drawFlip(_StateModifier _) { + if (_flipPile.isEmpty) { + _initDeck(); + } + _flipPile.shuffle(); + return _flipPile.pop(); + } + + void returnCard(String gfx) { + if (gfx.contains("flip")) { + _flipPile.add(ModifierCard(CardType.remove, gfx)); + _flipPile.shuffle(); + } else { + _multPile.add(ModifierCard(CardType.remove, gfx)); + _multPile.shuffle(); + } + } + + Map<String, dynamic> toJson() => { + 'multPile': _multPile.getList().map((c) => c.toJson()).toList(), + 'flipPile': _flipPile.getList().map((c) => c.toJson()).toList(), + }; + + @override + String toString() => json.encode(toJson()); + + void _initDeck() { + _multPile.clear(); + _flipPile.clear(); + List<ModifierCard> flipCards = []; + List<ModifierCard> multCards = []; + final prefix = "sanctuary/"; + for (int i = 1; i < _kCardTypeCount; i++) { + //2 of each of 4 different cards + flipCards.add(ModifierCard(CardType.remove, "${prefix}flip-$i")); + flipCards.add(ModifierCard(CardType.remove, "${prefix}flip-$i")); + multCards.add(ModifierCard(CardType.remove, "${prefix}x2-$i")); + multCards.add(ModifierCard(CardType.remove, "${prefix}x2-$i")); + } + _flipPile.setList(flipCards); + _multPile.setList(multCards); + _flipPile.shuffle(); + _multPile.shuffle(); + } +} |
