summaryrefslogtreecommitdiff
path: root/server/lib/core/game_methods.dart
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-12 00:28:50 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-12 00:28:50 +0100
commit808294adad3f378ad8d66b698acf8df7f49c2302 (patch)
treecfd11a1395a8ad482311969f86abbbad97e7e0b4 /server/lib/core/game_methods.dart
parentf6955e34489c79f6d5b764cb6a39b1387366b433 (diff)
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.
Diffstat (limited to 'server/lib/core/game_methods.dart')
-rw-r--r--server/lib/core/game_methods.dart687
1 files changed, 687 insertions, 0 deletions
diff --git a/server/lib/core/game_methods.dart b/server/lib/core/game_methods.dart
new file mode 100644
index 0000000..cf43ab7
--- /dev/null
+++ b/server/lib/core/game_methods.dart
@@ -0,0 +1,687 @@
+import 'dart:math';
+
+import 'package:collection/collection.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/service_locator.dart';
+import 'package:x_haven_server/core/settings.dart';
+import 'package:x_haven_server/core/state/game_state.dart';
+
+import 'enums.dart';
+
+class GameMethods {
+ static const int _kTrapBase = 2;
+ static const int _kHazardHalveDivisor = 2;
+ static const double _kHazardLevelDivisor = 3.0;
+ static const int _kXPBase = 4;
+ static const int _kXPMultiplier = 2;
+ static const int _kCoinMaxLevel = 7;
+ static const int _kCoinMaxValue = 6;
+ static const int _kCoinBase = 2;
+ static const double _kCoinLevelDivisor = 2.0;
+ static const double _kLevelDivisor = 2.0;
+ static const int _kInactiveInitiative = 99;
+ static const int _kPerkPairCount = 2;
+ static const int _kPolarBearStandees = 4;
+ static const int _kMaxOGSoloScenario = 100;
+
+ static int getTrapValue({GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ return _kTrapBase + gs.level;
+ }
+
+ static int getHazardValue({GameState? gameState, Settings? settings}) {
+ final gs = gameState ?? getIt<GameState>();
+ final s = settings ?? getIt<Settings>();
+ if (isOgGloomEdition(gameState: gs) && !s.fhHazTerrainCalcInOGGloom) {
+ return (getTrapValue(gameState: gs) / _kHazardHalveDivisor).floor();
+ }
+
+ return 1 + (gs.level / _kHazardLevelDivisor).ceil();
+ }
+
+ static int getXPValue({GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ return _kXPBase + _kXPMultiplier * gs.level;
+ }
+
+ static int getCoinValue({GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ int level = gs.level;
+ if (level == _kCoinMaxLevel) {
+ return _kCoinMaxValue;
+ }
+
+ return _kCoinBase + (level / _kCoinLevelDivisor).floor();
+ }
+
+ static int getRecommendedLevel({GameState? gameState}) {
+ double totalLevels = 0;
+ double nrOfCharacters = 0;
+ final gs = gameState ?? getIt<GameState>();
+ for (final item in gs.currentList) {
+ if (item is Character &&
+ !GameMethods.isObjectiveOrEscort(item.characterClass)) {
+ totalLevels += item.characterState.level;
+ nrOfCharacters++;
+ }
+ }
+ if (nrOfCharacters == 0) {
+ return 1;
+ }
+ if (gs.solo) {
+ //Take the average level of all characters in the
+ // scenario, then add 1 before dividing by 2 and rounding
+ // up.
+ return ((totalLevels / nrOfCharacters + 1.0) / _kLevelDivisor).ceil();
+ }
+ //scenario level is equal to
+ //the average level of the characters divided by 2
+ //(rounded up)
+
+ return (totalLevels / nrOfCharacters / _kLevelDivisor).ceil();
+ }
+
+ static bool canDraw({GameState? gameState, Settings? settings}) {
+ final gs = gameState ?? getIt<GameState>();
+ if (gs.currentList.isEmpty) {
+ return false;
+ }
+ if ((settings ?? getIt<Settings>()).noInit) {
+ return true;
+ }
+ for (final item in gs.currentList) {
+ if (item is Character) {
+ if (item.characterState.initiative == 0) {
+ if (item.characterState.health > 0) {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+ static bool isInactiveForRule(String monsterId, {GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ final rule = gs.scenarioSpecialRules.firstWhereOrNull(
+ (rule) => rule.type == "InactiveMonster" && rule.name == monsterId,
+ );
+ if (rule != null && rule.list.contains(gs.round)) {
+ return true;
+ }
+ return false;
+ }
+
+ static MonsterAbilityState? getDeck(String name, {GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ for (MonsterAbilityState deck in gs.currentAbilityDecks) {
+ if (deck.name == name) {
+ return deck;
+ }
+ }
+
+ return null;
+ }
+
+ static int getInitiative(ListItemData item, {GameState? gameState}) {
+ if (item is Character) {
+ return item.characterState.initiative;
+ } else if (item is Monster) {
+ if (!item.isActive) {
+ return _kInactiveInitiative; //sorted last
+ }
+ final gs = gameState ?? getIt<GameState>();
+ for (final deck in gs.currentAbilityDecks) {
+ if (deck.name == item.type.deck) {
+ if (deck.discardPileIsNotEmpty) {
+ return deck.discardPileTop.initiative;
+ }
+ }
+ }
+ }
+ return 0;
+ }
+
+ static Character? getCharacterByName(String name, {GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ for (ListItemData data in gs.currentList) {
+ if (data is Character) {
+ if (data.id == name) {
+ return data;
+ }
+ }
+ }
+ return null;
+ }
+
+ static List<Character> getCurrentCharacters({GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ return getCurrentCharactersForState(gs);
+ }
+
+ static List<Character> getCurrentCharactersForState(GameState state) {
+ List<Character> characters = [];
+ for (ListItemData data in state.currentList) {
+ if (data is Character &&
+ !GameMethods.isObjectiveOrEscort(data.characterClass)) {
+ characters.add(data);
+ }
+ }
+
+ return characters;
+ }
+
+ static Character? getCurrentCharacter({GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ for (final item in gs.currentList) {
+ if (item.turnState == TurnsState.current) {
+ if (item is Character) {
+ if (!GameMethods.isObjectiveOrEscort(item.characterClass)) {
+ return item;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ static ModifierDeck getModifierDeck(final String id, GameState state) {
+ if (id == "allies") {
+ return state.modifierDeckAllies;
+ }
+ if (id.isNotEmpty) {
+ final characters = GameMethods.getCurrentCharactersForState(state);
+ for (final character in characters) {
+ if (character.id == id) {
+ return character.characterState.modifierDeck;
+ }
+ }
+ }
+
+ return state.modifierDeck;
+ }
+
+ static bool canAddPerk(Character character, int index) {
+ final deck = character.characterState.modifierDeck;
+ final perksFH = character.characterClass.perksFH;
+ final useFHPerks =
+ character.characterState.useFHPerks && perksFH.isNotEmpty;
+ final perks = useFHPerks ? perksFH : character.characterClass.perks;
+ final perk = perks[index];
+ for (final item in perk.remove) {
+ if (!deck.hasCard(item)) {
+ //check for perk cards in the deck with same id
+
+ int otherPerkCardAdded = 0;
+ //find missing card from perk list
+ for (int i = 0; i < perks.length; i++) {
+ //check if other perk added the card previously
+ if (character.characterState.perkList[i]) {
+ for (final card in perks[i].add) {
+ if (card == item) {
+ otherPerkCardAdded++;
+ }
+ }
+ //this only for specific perk cards
+ if (item.startsWith("perks/")) {
+ for (final card in perks[i].remove) {
+ if (card == item) {
+ otherPerkCardAdded--;
+ }
+ }
+ }
+ }
+ }
+ return otherPerkCardAdded > 0;
+ }
+ }
+ return true;
+ }
+
+ static bool canRemovePerk(Character character, int index) {
+ final deck = character.characterState.modifierDeck;
+ final perksFH = character.characterClass.perksFH;
+ final useFHPerks =
+ character.characterState.useFHPerks && perksFH.isNotEmpty;
+ final perks = useFHPerks ? perksFH : character.characterClass.perks;
+ final perk = perks[index];
+
+ for (final item in perk.add) {
+ if (item.startsWith("perks/")) {
+ String id = "P$index";
+ if (perk.add.length >= _kPerkPairCount && item == perk.add.last) {
+ id += "-2";
+ }
+ if (deck.hasCard(id)) {
+ return true;
+ }
+ }
+ if (!deck.hasCard(item)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static String perkGfxIdToCardId(String gfx, PerkModel perk, int index) {
+ if (gfx.startsWith("perks/")) {
+ String id = "P$index";
+ if (perk.add.length >= _kPerkPairCount && gfx == perk.add.last) {
+ id += "-2";
+ }
+ return id;
+ }
+ return gfx;
+ }
+
+ static int getCurrentCharacterAmount({GameState? gameState}) {
+ int res = 0;
+ final gs = gameState ?? getIt<GameState>();
+ for (ListItemData data in gs.currentList) {
+ if (data is Character) {
+ if (!GameMethods.isObjectiveOrEscort(data.characterClass)) {
+ res++;
+ }
+ }
+ }
+
+ return res;
+ }
+
+ static List<Monster> getCurrentMonsters({GameState? gameState}) {
+ List<Monster> monsters = [];
+ final gs = gameState ?? getIt<GameState>();
+ for (ListItemData data in gs.currentList) {
+ if (data is Monster) {
+ monsters.add(data);
+ }
+ }
+
+ return monsters;
+ }
+
+ static int getNextAvailableBnBStandee(Monster data, {GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ int nrOfStandees = data.type.count;
+ for (int i = 0; i < nrOfStandees; i++) {
+ bool isAvailable = true;
+ for (final item in data.monsterInstances) {
+ if (item.standeeNr == i + 1) {
+ isAvailable = false;
+ break;
+ }
+ }
+
+ if (isAvailable) {
+ //check for other monsters with same standees
+ for (final item in gs.currentList) {
+ if (item is Monster) {
+ if (item.id != data.id) {
+ for (final standee in item.monsterInstances) {
+ if (standee.standeeNr == i + 1) {
+ isAvailable = false;
+ break;
+ }
+ }
+ }
+ }
+ if (!isAvailable) {
+ break;
+ }
+ }
+ }
+ if (isAvailable) {
+ return i + 1;
+ }
+ }
+ return 0;
+ }
+
+ static int getRandomStandee(Monster data, {GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ int nrOfStandees = data.type.count;
+ if (data.type.name == "Polar Bear") {
+ nrOfStandees =
+ _kPolarBearStandees; //for the special case where there are only 4 standees in first printing
+ }
+ List<int> available = [];
+ for (int i = 0; i < nrOfStandees; i++) {
+ bool isAvailable = true;
+ for (final item in data.monsterInstances) {
+ if (item.standeeNr == i + 1) {
+ isAvailable = false;
+ break;
+ }
+ }
+ if (isAvailable) {
+ //check for special monsters with same standees
+ for (final item in gs.currentList) {
+ if (item is Monster) {
+ if (item.id != data.id) {
+ if (item.type.gfx == data.type.gfx) {
+ for (final standee in item.monsterInstances) {
+ if (standee.standeeNr == i + 1) {
+ isAvailable = false;
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (!isAvailable) {
+ break;
+ }
+ }
+ }
+ if (isAvailable) {
+ available.add(i + 1);
+ }
+ }
+
+ //in case we run out of standees...
+ if (available.isEmpty) {
+ return 0;
+ }
+ return available[Random().nextInt(available.length)];
+ }
+
+ static FigureState? getFigure(
+ String? ownerId,
+ String figureId, {
+ GameState? gameState,
+ }) {
+ final gs = gameState ?? getIt<GameState>();
+ for (final item in gs.currentList) {
+ if (item.id == figureId) {
+ return (item as Character).characterState;
+ }
+ if (item.id == ownerId) {
+ if (item is Monster) {
+ for (final instance in item.monsterInstances) {
+ String id =
+ instance.name + instance.gfx + instance.standeeNr.toString();
+ if (id == figureId) {
+ return instance;
+ }
+ }
+ } else if (item is Character) {
+ for (final instance in item.characterState.summonList) {
+ String id =
+ instance.name + instance.gfx + instance.standeeNr.toString();
+ if (id == figureId) {
+ return instance;
+ }
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ static String getFigureIdFromNr(
+ String ownerId,
+ int nr, {
+ GameState? gameState,
+ }) {
+ final gs = gameState ?? getIt<GameState>();
+ for (final item in gs.currentList) {
+ if (item.id == ownerId) {
+ if (item is Monster) {
+ for (final instance in item.monsterInstances) {
+ if (instance.standeeNr == nr) {
+ return instance.name +
+ instance.gfx +
+ instance.standeeNr.toString();
+ }
+ }
+ }
+ }
+ }
+ return "";
+ }
+
+ static bool isObjectiveOrEscort(CharacterClass character) {
+ return character.id == "Escort" || character.id == "Objective";
+ }
+
+ static bool shouldShowAlliesDeck({GameState? gameState, Settings? settings}) {
+ final gs = gameState ?? getIt<GameState>();
+ if (!(settings ?? getIt<Settings>()).showAmdDeck) {
+ return false;
+ }
+ if (gs.showAllyDeck) {
+ return true;
+ }
+ if (!gs.allyDeckInOGGloom && isOgGloomEdition(gameState: gs)) {
+ return false;
+ }
+ for (final item in gs.currentList) {
+ if (item is Monster) {
+ if (item.isAlly) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ static bool canExpire(Condition condition) {
+ if (
+ //don't remove bane because user need to remember to remove 10hp as well
+ condition == Condition.strengthen ||
+ condition == Condition.stun ||
+ condition == Condition.immobilize ||
+ condition == Condition.muddle ||
+ condition == Condition.invisible ||
+ condition == Condition.disarm ||
+ condition == Condition.chill ||
+ condition == Condition.impair) {
+ return true;
+ }
+ return false;
+ }
+
+ static bool isFrosthavenStyledEdition(
+ String edition, {
+ GameState? gameState,
+ }) {
+ final gs = gameState ?? getIt<GameState>();
+ String scenario = gs.scenario;
+ if (edition == "Solo") {
+ if (scenario.contains("${"#19"} ")) {
+ return false; //this is forgotten circles
+ }
+ //#100+ are og solo scenarios
+ for (int i = 1; i <= _kMaxOGSoloScenario; i++) {
+ if (scenario.contains("${"#$i"} ")) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return edition == "Frosthaven" ||
+ edition == "Buttons and Bugs" ||
+ edition == "Gloomhaven 2nd Edition" ||
+ edition == "Skulls in the Snow" ||
+ edition == "Mercenary Packs";
+ }
+
+ static bool summonDoesNotDie(String? ownerId, String id) {
+ //exempt special summons that should not be removed at 0
+ if (ownerId == "Glacial Torrent" && id == "Glacier") {
+ return true;
+ } else if (ownerId == "D.O.M.E." && id == "Barrier") {
+ return true;
+ }
+ return false;
+ }
+
+ static bool isFrosthavenStyle(
+ MonsterModel? monster, {
+ GameState? gameState,
+ Settings? settings,
+ }) {
+ final gs = gameState ?? getIt<GameState>();
+ //frosthaven monster
+ final monsterFrostHavenStyledEdition =
+ monster != null &&
+ isFrosthavenStyledEdition(monster.edition, gameState: gs);
+ if (monsterFrostHavenStyledEdition) {
+ return true;
+ }
+ final style = (settings ?? getIt<Settings>()).style;
+ //frosthaven monsters in other campaigns
+ if (monster != null) {
+ if (style != Style.frosthaven && !monsterFrostHavenStyledEdition) {
+ return false;
+ }
+ }
+ //frosthaven style settings
+ return style == Style.frosthaven ||
+ style == Style.original &&
+ isFrosthavenStyledEdition(gs.currentCampaign, gameState: gs);
+ }
+
+ static bool isCustomCampaign(String campaign) {
+ if (campaign == "Crimson Scales") {
+ return true;
+ }
+ if (campaign == "Trail of Ashes") {
+ return true;
+ }
+ if (campaign == "CCUG") {
+ return true;
+ }
+ return false;
+ }
+
+ static int? findNrFromScenarioName(String scenario) {
+ String nr = scenario.substring(1);
+ for (int i = 0; i < nr.length; i++) {
+ if (nr[i] == ' ' || nr[i] == ".") {
+ nr = nr.substring(0, i);
+ return int.tryParse(nr);
+ }
+ }
+
+ return null;
+ }
+
+ static bool isOgGloomEdition({GameState? gameState}) {
+ final gs = gameState ?? getIt<GameState>();
+ return !isFrosthavenStyledEdition(gs.currentCampaign, gameState: gs);
+ }
+
+ static bool hasLootDeck({GameState? gameState, Settings? settings}) {
+ final gs = gameState ?? getIt<GameState>();
+ bool hasLootDeck = !(settings ?? getIt<Settings>()).hideLootDeck;
+ if (gs.lootDeck.discardPileIsEmpty && gs.lootDeck.drawPileIsEmpty) {
+ hasLootDeck = false;
+ }
+ return hasLootDeck;
+ }
+
+ static List<ModifierCard> getFactionCards(String faction) {
+ List<ModifierCard> retVal = [];
+ if (faction == "Demons") {
+ retVal.add(ModifierCard(CardType.add, "Demons-perks/plus1any"));
+ retVal.add(
+ ModifierCard(CardType.add, "Demons-perks/plus1retaliate1flip"),
+ );
+ retVal.add(ModifierCard(CardType.add, "Demons-perks/plus0wardallyflip"));
+ retVal.add(ModifierCard(CardType.add, "Demons-perks/unique/fuck3"));
+ } else if (faction == "Merchant-Guild") {
+ retVal.add(ModifierCard(CardType.add, "Merchant-Guild-perks/plus1curse"));
+ retVal.add(ModifierCard(CardType.add, "Merchant-Guild-perks/plus1wound"));
+ retVal.add(
+ ModifierCard(CardType.add, "Merchant-Guild-perks/plus0heal2flip"),
+ );
+ retVal.add(
+ ModifierCard(CardType.add, "Merchant-Guild-perks/unique/fuck2"),
+ );
+ } else if (faction == "Military") {
+ retVal.add(
+ ModifierCard(CardType.add, "Military-perks/plus1strengthenally"),
+ );
+ retVal.add(ModifierCard(CardType.add, "Military-perks/plus1shield1flip"));
+ retVal.add(ModifierCard(CardType.add, "Military-perks/plus1push2flip"));
+ retVal.add(ModifierCard(CardType.add, "Military-perks/unique/fuck1"));
+ }
+ return retVal;
+ }
+
+ static bool isCardInAnyCharacterDeck(String gfx, {GameState? gameState}) {
+ final characters = getCurrentCharacters(gameState: gameState);
+ for (final item in characters) {
+ if (item.characterState.modifierDeck.hasCard(gfx)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static bool hasRetaliate(
+ Monster monster,
+ MonsterInstance figure, {
+ GameState? gameState,
+ }) {
+ return _monsterHasConditionOnCards(
+ monster,
+ figure,
+ "%retaliate%",
+ gameState: gameState,
+ );
+ }
+
+ static bool hasShield(
+ Monster monster,
+ MonsterInstance figure, {
+ GameState? gameState,
+ }) {
+ return _monsterHasConditionOnCards(
+ monster,
+ figure,
+ "%shield%",
+ gameState: gameState,
+ );
+ }
+
+ static bool _monsterHasConditionOnCards(
+ Monster monster,
+ MonsterInstance figure,
+ String condition, {
+ GameState? gameState,
+ }) {
+ bool hasCondition = false;
+ //check innate value
+
+ final level = monster.type.levels[monster.level];
+ if (figure.type == MonsterType.normal) {
+ hasCondition =
+ level.normal?.attributes.indexWhere((i) => i.contains(condition)) !=
+ -1;
+ } else if (figure.type == MonsterType.elite) {
+ hasCondition =
+ level.elite?.attributes.indexWhere((i) => i.contains(condition)) !=
+ -1;
+ } else if (figure.type == MonsterType.boss) {
+ hasCondition =
+ level.boss?.attributes.indexWhere((i) => i.contains(condition)) != -1;
+ }
+ //check ability card
+ final deck = GameMethods.getDeck(monster.type.deck, gameState: gameState);
+ if (deck != null &&
+ deck.discardPileIsNotEmpty &&
+ monster.turnState != TurnsState.notDone) {
+ if (deck.discardPileTop.lines.firstWhereOrNull(
+ (item) => item.contains(condition),
+ ) !=
+ null) {
+ return true;
+ }
+ }
+ return hasCondition;
+ }
+}