From 808294adad3f378ad8d66b698acf8df7f49c2302 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Thu, 12 Nov 2026 00:28:50 +0100 Subject: Phase 1: headless game engine on the server (M1) Complete mechanical port of the reference app's game engine to server/lib/core/ so later phases are UI-only: - models/ (7), state/ (GameState + 18 part files), methods/ (7), game_methods, 79 command files, enums, card_stack, stat_calculator, action_handler (index, 250-deep history, save-per-action, undo/redo), disk-based game_data, l10n, translation_service, service_locator - ValueNotifier/ChangeNotifier removed in favor of plain fields with a minimal GameState listener hook for the Phase 2 broadcast layer; shared_preferences replaced by the SaveStore abstraction (InMemory for tests, File-backed for bin/main.dart) - command registry: 82 entries mapping wire names to constructors with arg validation; live-object args (loot/ability cards, figure lists) travel as id/name/nr and resolve against live state, enums by name, injected singletons never serialize - line_builder ported to Phase 1 scope: stat_applier + minimal LineBuilder (isElement, tokens); widget rendering deferred to Phase 4 - ported test suite: 81 test files, 562 tests green (command tests 1:1 with the reference, resource tests, registry smoke tests) - new headless integration test drives a full round: scenario setup, characters + standee, secret-initiative gate, draw, every figure's turn (incl. undo/redo), next round, round 2, round 3 - PORTING.md: the conventions contract used for the port - bin/main.dart boots the engine (file save store, assets/data) before serving; pubspec gains built_collection, collection, get_it, intl - dart format drift on pre-existing net/test files from the current formatter (whitespace only) dart analyze warning-free; dart test 562/562. --- server/lib/core/methods/round_methods.dart | 493 +++++++++++++++++++++++++++++ 1 file changed, 493 insertions(+) create mode 100644 server/lib/core/methods/round_methods.dart (limited to 'server/lib/core/methods/round_methods.dart') diff --git a/server/lib/core/methods/round_methods.dart b/server/lib/core/methods/round_methods.dart new file mode 100644 index 0000000..4ad146d --- /dev/null +++ b/server/lib/core/methods/round_methods.dart @@ -0,0 +1,493 @@ +part of '../state/game_state.dart'; + +// ignore_for_file: library_private_types_in_public_api + +class RoundMethods { + static const int _kMaxLevel = 7; + static const int _kMinLevel = 0; + static void setRoundState( + _StateModifier _, + RoundState state, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + gs._roundState = state; + } + + static void setRound(_StateModifier _, int round, {GameState? gameState}) { + final gs = gameState ?? getIt(); + gs._round = round; + gs._totalRounds++; + } + + static void resetRound( + _StateModifier _, + int round, + bool resetTotal, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + gs._round = round; + if (resetTotal) { + gs._totalRounds = round; + } + } + + static void sortCharactersFirst(_StateModifier _, {GameState? gameState}) { + final gs = gameState ?? getIt(); + gs._currentList.sort(_compareForCharactersFirst); + // Sorting compares note rows as initiative 0, scattering them; re-glue any + // linked notes back under their target. Callers that notify via + // updateList.notify() (e.g. DrawCommand) bypass _notifyCurrentList, so the + // reflow must happen here rather than only in _notifyCurrentList. + gs._reflowNoteRows(); + } + + static int _compareForCharactersFirst(ListItemData a, ListItemData b) { + final deadResult = _compareDeadCharacters(a, b); + if (deadResult != null) return deadResult; + + final aIsChar = a is Character; + final bIsChar = b is Character; + if (aIsChar && bIsChar) return 0; + if (bIsChar) return 1; + if (aIsChar) return -1; + + // both are monsters — inactive at bottom + if (a is Monster && b is Monster) { + if (a.isActive && !b.isActive) return -1; + if (!a.isActive && b.isActive) return 1; + } + return -1; + } + + // Returns a sort result if either figure is a dead character (dead go last), + // or null if neither is dead and the caller should continue comparing. + static int? _compareDeadCharacters(ListItemData a, ListItemData b) { + final aIsDead = a is Character && a.characterState.health == 0; + final bIsDead = b is Character && b.characterState.health == 0; + if (!aIsDead && bIsDead) return -1; + if (aIsDead && !bIsDead) return 1; + if (aIsDead) return -1; // both dead characters + return null; + } + + static void sortItemToPlace( + _StateModifier _, + String id, + int initiative, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + final newList = gs.currentList.toList(); + ListItemData? item; + int currentTurnItemIndex = 0; + for (int i = 0; i < newList.length; i++) { + if (newList[i].turnState == TurnsState.current) { + currentTurnItemIndex = i; + } + if (newList[i].id == id) { + item = newList.removeAt(i); + } + } + if (item == null) { + return; + } + + int init = 0; + for (int i = 0; i < newList.length; i++) { + ListItemData currentItem = newList[i]; + int currentItemInitiative = GameMethods.getInitiative(currentItem); + if (currentItemInitiative > initiative && currentItemInitiative > init) { + if (i > currentTurnItemIndex) { + newList.insert(i, item); + gs._currentList = newList; + gs._notifyCurrentList(); + return; + } else { + //in case initiative is earlier than current turn, ignore anything current turn, and earlier and place later + int insertIndex = currentTurnItemIndex + 1; + for (int j = currentTurnItemIndex + 1; j < newList.length; j++) { + if (GameMethods.getInitiative(newList[j]) >= initiative) { + insertIndex = j; + break; + } + } + if (insertIndex > newList.length) { + newList.add(item); + } else { + newList.insert(insertIndex, item); + } + + gs._currentList = newList; + gs._notifyCurrentList(); + return; + } + } + init = + currentItemInitiative; //this check is for the case user has moved items around the order may be off + } + + newList.add(item); + gs._currentList = newList; + gs._notifyCurrentList(); + } + + static void sortByInitiative(_StateModifier _, {GameState? gameState}) { + final gs = gameState ?? getIt(); + gs._currentList.sort((a, b) { + final deadResult = _compareDeadCharacters(a, b); + if (deadResult != null) return deadResult; + + int aInitiative = 0; + int bInitiative = 0; + if (a is Character) { + aInitiative = a.characterState.initiative; + } else if (a is Monster) { + if (!a.isActive) { + if (b is Monster && !b.isActive) { + return -1; + } + return 1; //inactive at bottom + } + + //find the deck + for (final item in gs.currentAbilityDecks) { + if (item.name == a.type.deck && item.discardPileIsNotEmpty) { + aInitiative = item.discardPileTop.initiative; + } + } + } + if (b is Character) { + bInitiative = b.characterState.initiative; + } else if (b is Monster) { + if (!b.isActive) { + if (a is Monster && !a.isActive) { + return 1; + } + return -1; //inactive at bottom + } + //find the deck + for (final item in gs.currentAbilityDecks) { + if (item.name == b.type.deck && item.discardPileIsNotEmpty) { + bInitiative = item.discardPileTop.initiative; + } + } + } + return aInitiative.compareTo(bInitiative); + }); + // Re-glue linked note rows after the initiative sort (see sortCharactersFirst). + gs._reflowNoteRows(); + } + + static void sortMonsterInstances( + _StateModifier _, + List instances, + ) { + instances.sort((a, b) { + if (a.type == MonsterType.elite && b.type != MonsterType.elite) { + return -1; + } + if (b.type == MonsterType.elite && a.type != MonsterType.elite) { + return 1; + } + return a.standeeNr.compareTo(b.standeeNr); + }); + } + + static void addToMainList( + _StateModifier _, + int? index, + ListItemData item, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + final newList = gs.currentList.toList(); + if (index != null) { + newList.insert(index, item); + } else { + newList.add(item); + } + gs._currentList = newList; + gs._notifyCurrentList(); + } + + static void reorderMainList( + _StateModifier _, + int newIndex, + int oldIndex, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + gs._currentList.insert(newIndex, gs._currentList.removeAt(oldIndex)); + gs._notifyCurrentList(); + } + + static void removeFromMainList( + _StateModifier _, + String id, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + gs._currentList = gs._currentList.where((item) => item.id != id).toList(); + gs._notifyCurrentList(); + } + + /// Deletes any note rows tied to a specific standee ([standeeNr] > 0) of the + /// monster [linkedId] — called when that standee is defeated so its note goes + /// with it. Notes for the whole group (standeeNr 0) are left alone. + static void removeNoteRowsForStandee( + _StateModifier _, + String linkedId, + int standeeNr, { + GameState? gameState, + }) { + if (standeeNr <= 0) return; + final gs = gameState ?? getIt(); + final filtered = gs._currentList + .where( + (item) => + !(item is NoteRow && + item.linkedId == linkedId && + item.standeeNr == standeeNr), + ) + .toList(); + if (filtered.length != gs._currentList.length) { + gs._currentList = filtered; + gs._notifyCurrentList(); + } + } + + static void updateForSpecialRules( + _StateModifier _, { + GameState? gameState, + GameData? gameData, + }) { + final gs = gameState ?? getIt(); + final gd = gameData ?? getIt(); + List? rules = + gd.modelData[gs.currentCampaign]?.scenarios[gs.scenario]?.specialRules; + if (rules != null) { + for (SpecialRule rule in rules) { + if (rule.type == "Objective" || rule.type == "Escort") { + Character? character = + gs.currentList.firstWhereOrNull( + (element) => element.id == rule.name, + ) + as Character?; + if (character != null) { + int? newHealth = StatCalculator.calculateFormula( + rule.health.toString(), + ); + if (newHealth != character.characterState.maxHealth && + newHealth != null) { + character.characterState._maxHealth = newHealth; + character.characterState._health = newHealth; + } + } + } else if (rule.type == "LevelAdjust") { + Monster? monster = + gs.currentList.firstWhereOrNull( + (element) => element.id == rule.name, + ) + as Monster?; + if (monster != null) { + if (gs.level == monster.level) { + int newLevel = (monster.level + rule.level).clamp( + _kMinLevel, + _kMaxLevel, + ); + monster._level = newLevel; + for (MonsterInstance instance in monster._monsterInstances) { + instance._setLevel(monster); + } + } + } + } + } + } + } + + static void clearTurnStateConditions( + _StateModifier _, + FigureState figure, + bool clearLastTurnToo, + ) { + if (!clearLastTurnToo) { + figure._conditionsAddedPreviousTurn.clear(); + figure._conditionsAddedPreviousTurn.addAll( + figure.conditionsAddedThisTurn.toSet(), + ); + } else { + figure._conditionsAddedPreviousTurn.clear(); + } + + figure._conditionsAddedThisTurn.clear(); + + figure._chill = figure.conditions.where((a) => a == Condition.chill).length; + } + + static void clearTurnState( + _StateModifier stateModifier, + bool clearLastTurnToo, { + GameState? gameState, + }) { + final gs = gameState ?? getIt(); + for (final item in gs._currentList) { + item._turnState = TurnsState.notDone; + if (item is Character) { + clearTurnStateConditions( + stateModifier, + item.characterState, + clearLastTurnToo, + ); + for (final instance in item.characterState._summonList) { + clearTurnStateConditions(stateModifier, instance, clearLastTurnToo); + } + } else if (item is Monster) { + for (final instance in item._monsterInstances) { + clearTurnStateConditions(stateModifier, instance, clearLastTurnToo); + } + } + } + } + + static void removeExpiringConditions( + _StateModifier _, + FigureState figure, { + Settings? settings, + }) { + if ((settings ?? getIt()).expireConditions) { + final conditions = figure._conditions; + + //handle chill separately + int nrOfChills = figure.conditions + .where((a) => a == Condition.chill) + .length; + if (nrOfChills > 0) { + //remove one if not added this turn + if (!figure.conditionsAddedThisTurn.contains(Condition.chill) || + nrOfChills > + 1 //this is a cop out: you can add more than one chill in a round, but since we store only if a condition has been added this turn, and not the amount, we have no way to tell + ) { + conditions.remove(Condition.chill); + figure._conditionsAddedPreviousTurn.add(Condition.chill); + } + } + + figure._chill = figure.conditions + .where((a) => a == Condition.chill) + .length; + + for (int i = conditions.length - 1; i >= 0; i--) { + Condition item = conditions[i]; + if (GameMethods.canExpire(item)) { + if (item != Condition.chill) { + if (!figure.conditionsAddedThisTurn.contains(item)) { + conditions.removeAt(i); + figure._conditionsAddedPreviousTurn.add(item); + } + } + } + } + } + } + + static void removeExpiringConditionsFromListItem( + _StateModifier s, + ListItemData item, + ) { + if (item is Character) { + removeExpiringConditions(s, item.characterState); + for (final summon in item.characterState._summonList) { + removeExpiringConditions(s, summon); + } + } else if (item is Monster) { + for (final instance in item._monsterInstances) { + removeExpiringConditions(s, instance); + } + } + } + + static void reapplyConditions(_StateModifier _, FigureState figure) { + for (final condition in figure.conditionsAddedPreviousTurn) { + final conditions = figure._conditions; + if (!conditions.contains(condition) || condition == Condition.chill) { + conditions.add(condition); + figure._conditionsAddedThisTurn.remove(condition); + } + if (condition == Condition.chill) { + figure._chill = figure.conditions + .where((a) => a == Condition.chill) + .length; + } + } + } + + static void reapplyConditionsFromListItem( + _StateModifier s, + ListItemData item, + ) { + if (item is Character) { + reapplyConditions(s, item.characterState); + for (final summon in item.characterState.summonList) { + reapplyConditions(s, summon); + } + } else if (item is Monster) { + for (final instance in item._monsterInstances) { + reapplyConditions(s, instance); + } + } + } + + //1 if item WAS done OR not done, then set it to current, all before to done, and all after to not done + //2 if item was current: set item to done, all before to done, next to current and rest to not done + static void setTurnDone(_StateModifier s, int index, {GameState? gameState}) { + final gs = gameState ?? getIt(); + //set all before to done. + for (int i = 0; i < index; i++) { + if (gs.currentList[i].turnState != TurnsState.done) { + gs.currentList[i]._turnState = TurnsState.done; + removeExpiringConditionsFromListItem(s, gs.currentList[i]); + } + } + //if on index is NOT current then set to current else set to done + int newIndex = index + 1; + if (gs.currentList[index].turnState == TurnsState.current) { + gs.currentList[index]._turnState = TurnsState.done; + removeExpiringConditionsFromListItem(s, gs.currentList[index]); + //remove expiring conditions + } else { + newIndex = index; + } + + //get next active item and set to current + for (; newIndex < gs.currentList.length; newIndex++) { + ListItemData data = gs.currentList[newIndex]; + if (data is Monster) { + if (data.isActive && !GameMethods.isInactiveForRule(data.type.name)) { + if (data.turnState == TurnsState.done) { + reapplyConditionsFromListItem(s, data); + } + data._turnState = TurnsState.current; + break; + } + } else if (data is Character) { + if (data.characterState.health > 0) { + if (data.turnState == TurnsState.done) { + reapplyConditionsFromListItem(s, data); + } + data._turnState = TurnsState.current; + break; + } + } + } + //set rest to not done + for (int i = newIndex + 1; i < gs.currentList.length; i++) { + if (gs.currentList[i].turnState == TurnsState.done) { + reapplyConditionsFromListItem(s, gs.currentList[i]); + } + gs.currentList[i]._turnState = TurnsState.notDone; + } + } +} -- cgit v1.3.1