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/test/resource/action_handler_test.dart | 215 ++++ server/test/resource/game_methods_test.dart | 1292 ++++++++++++++++++++ .../resource/line_builder/line_builder_test.dart | 67 + .../resource/line_builder/stat_applier_test.dart | 284 +++++ server/test/resource/modifier_deck_test.dart | 175 +++ server/test/resource/stat_calculator_test.dart | 174 +++ server/test/resource/ui_utils_test.dart | 48 + 7 files changed, 2255 insertions(+) create mode 100644 server/test/resource/action_handler_test.dart create mode 100644 server/test/resource/game_methods_test.dart create mode 100644 server/test/resource/line_builder/line_builder_test.dart create mode 100644 server/test/resource/line_builder/stat_applier_test.dart create mode 100644 server/test/resource/modifier_deck_test.dart create mode 100644 server/test/resource/stat_calculator_test.dart create mode 100644 server/test/resource/ui_utils_test.dart (limited to 'server/test/resource') diff --git a/server/test/resource/action_handler_test.dart b/server/test/resource/action_handler_test.dart new file mode 100644 index 0000000..3137454 --- /dev/null +++ b/server/test/resource/action_handler_test.dart @@ -0,0 +1,215 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt().clearList(); + }); + + group('ActionHandler', () { + group('getCurrent', () { + test('getCurrent returns the last executed command', () { + final gs = getIt(); + final cmd = SetLevelCommand(3, null); + gs.action(cmd); + expect(gs.getCurrent(), same(cmd)); + gs.undo(); + }); + }); + + group('redo', () { + test('redo restores state after undo', () { + final gs = getIt(); + // Two actions so gameSaveStates has enough entries for redo + gs.action(SetLevelCommand(2, null)); + gs.action(SetLevelCommand(5, null)); + expect(gs.level, 5); + gs.undo(); // back to level 2 + expect(gs.level, 2); + gs.redo(); // forward to level 5 + expect(gs.level, 5); + gs.undo(); + gs.undo(); + }); + + test('redo is a no-op when there is nothing to redo', () { + final gs = getIt(); + gs.action(SetLevelCommand(4, null)); + // No undo performed, so redo should not crash and not change state + final levelBefore = gs.level; + gs.redo(); + expect(gs.level, levelBefore); + gs.undo(); + }); + + test('redo increments commandIndex', () { + final gs = getIt(); + gs.action(SetLevelCommand(2, null)); + gs.action(SetLevelCommand(3, null)); + final indexAfterActions = gs.commandIndex; + gs.undo(); + expect(gs.commandIndex, indexAfterActions - 1); + gs.redo(); + expect(gs.commandIndex, indexAfterActions); + gs.undo(); + gs.undo(); + }); + }); + + group('redo list cleanup', () { + test('new action after undo clears the redo list', () { + final gs = getIt(); + gs.action(SetLevelCommand(3, null)); + gs.action(SetLevelCommand(4, null)); + //final indexBefore = gs.commandIndex; + gs.undo(); // undo SetLevel(4), now commandIndex = indexBefore - 1 + // Do a new action — should clear SetLevel(4) from the redo list + gs.action(SetLevelCommand(5, null)); + // commands length should equal commandIndex + 1 (no redo entries) + expect(gs.commands.length - 1, gs.commandIndex); + expect(gs.commandDescriptions.length - 1, gs.commandIndex); + // Undo back to baseline + gs.undo(); + gs.undo(); + }); + }); + + group('maxUndo eviction', () { + test('commands and gameSaveStates beyond maxUndo are nulled', () { + final gs = getIt(); + final maxUndo = gs.maxUndo; + final startIndex = gs.commandIndex; + + // Execute maxUndo + 1 commands to trigger eviction + for (int i = 0; i <= maxUndo; i++) { + gs.action(SetLevelCommand((i % 7) + 1, null)); + } + // After maxUndo+1 actions, the oldest command entry should be nulled + expect(gs.commands[startIndex + 1], isNull); + // gameSaveStates at oldest entry should also be nulled + expect(gs.gameSaveStates[startIndex + 1], isNull); + + // Undo back to near the start (only valid undo states) + for (int i = 0; i < maxUndo; i++) { + gs.undo(); + } + }); + }); + + group('getCurrent edge cases', () { + test( + 'getCurrent throws when there is no valid command at current index', + () { + final gs = getIt(); + // Reset so commandIndex is -1 (no commands executed yet). + gs.commandIndex = -1; + gs.resetCommandHistory(); + // getCurrent accesses _commands[commandIndex] — either a RangeError + // (negative index) or TypeError (null-check on a null entry). Either + // way it must throw an Error so callers know to guard the call site. + expect(() => gs.getCurrent(), throwsA(isA())); + }, + ); + }); + + group('redo after maxUndo eviction', () { + test('redo from the oldest valid position does not crash', () { + final gs = getIt(); + final maxUndo = gs.maxUndo; + + // Execute maxUndo + 1 commands so the oldest save state is evicted. + for (int i = 0; i <= maxUndo; i++) { + gs.action(SetLevelCommand((i % 7) + 1, null)); + } + + // Undo all the way to the eviction boundary: + // only the last maxUndo states are guaranteed non-null. + for (int i = 0; i < maxUndo; i++) { + gs.undo(); + } + // commandIndex is now at the boundary; gameSaveStates[commandIndex + 1] + // may be null (evicted). redo() must return early without crashing. + expect(() => gs.redo(), returnsNormally); + + // Restore state for other tests. + gs.undo(); + }); + }); + + group('add monster then undo', () { + test('undo after adding a monster removes it from the list', () { + final gs = getIt(); + gs.clearList(); + gs.action( + AddMonsterCommand('Zealot', 1, false, gameState: getIt()), + ); + expect(gs.currentList.any((e) => e.id == 'Zealot'), isTrue); + gs.undo(); + expect(gs.currentList.any((e) => e.id == 'Zealot'), isFalse); + }); + }); + + group('undo with commandIndex beyond gameSaveStates (Sentry regression)', () { + // Regression test for: + // ArgumentError: RangeError (length): Invalid value: Not in inclusive range 0..1079: 1080 + // ActionHandler.undo — crash when commandIndex >= gameSaveStates.length. + // + // Cause: in the server multiplayer path, Server.updateStateFromMessage sets + // commandIndex directly, then calls save(). After a + // resetState() (history cleared) a client that was ahead can send a message + // whose index ends up beyond the current gameSaveStates length after save(). + // A subsequent "undo" message from any client then crashes at + // _gameSaveStates[commandIndex] with no upper-bound guard. + test('does not crash when commandIndex >= gameSaveStates.length', () { + final gs = getIt(); + + // Build a small amount of history. + gs.action(SetLevelCommand(3, null)); + gs.action(SetLevelCommand(4, null)); + + // Advance commandIndex past the end of gameSaveStates, simulating the + // server receiving a state message whose index was not matched by a save(). + gs.commandIndex = gs.gameSaveStates.length; // one beyond valid range + + // A client sends "undo" — the server calls undoState() → undo(). + // This must not throw a RangeError. + expect(() => gs.undo(), returnsNormally); + + // Restore a clean state for subsequent tests. + gs.commandIndex = -1; + gs.resetCommandHistory(); + }); + }); + + group('redo after connection reset in server mode', () { + // Regression test for: ArgumentError: RangeError (length): Invalid value: + // Valid value range is empty: -1 in ActionHandler.redo when a stale client + // sends "redo" after the server resets its command history on reconnect. + test('does not crash when commandIndex is -1 after connection reset', () { + final gs = getIt(); + + // Build some history so gameSaveStates has an entry to retain. + gs.action(SetLevelCommand(3, null)); + + // Simulate the server-side connection-reset sequence: + // commandIndex → -1, command/description lists cleared, last save state kept. + gs.commandIndex = -1; + gs.resetCommandHistory(); + + // Stale client sends "redo" before it has re-synced with the server. + expect(() => gs.redo(), returnsNormally); + }); + }); + }); +} diff --git a/server/test/resource/game_methods_test.dart b/server/test/resource/game_methods_test.dart new file mode 100644 index 0000000..f960ca9 --- /dev/null +++ b/server/test/resource/game_methods_test.dart @@ -0,0 +1,1292 @@ +// ignore_for_file: avoid-late-keyword, no-empty-block, no-magic-number, avoid-non-null-assertion, prefer-first + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/models/character_class.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_perk_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_character_level_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/commands/set_solo_command.dart'; +import 'package:x_haven_server/core/commands/show_ally_deck_command.dart'; +import 'package:x_haven_server/core/commands/turn_done_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() async { + await setUpGame(); + + group('GameMethods', () { + group('getTrapValue', () { + test('should return 2 + game level when level is 4', () { + // Act: Call the method we are testing. + SetLevelCommand(4, null).execute(); + String oldState = gameState.toString(); + final result = GameMethods.getTrapValue(); + + // Assert: Check if the result is what we expect. + expect(result, 6); + checkNoSideEffects([], oldState); + }); + + test('should return 2 when game level is 0', () { + SetLevelCommand(0, null).execute(); + String oldState = gameState.toString(); + // Act + final result = GameMethods.getTrapValue(); + + // Assert + expect(result, 2); + checkNoSideEffects([], oldState); + }); + + test('should return 9 when game level is 7', () { + SetLevelCommand(7, null).execute(); + String oldState = gameState.toString(); + // Act + final result = GameMethods.getTrapValue(); + + // Assert + expect(result, 9); + checkNoSideEffects([], oldState); + }); + + test('should bork when game level is out of bounds', () { + expect( + () => SetLevelCommand(77, null).execute(), + throwsA(isA()), + ); + }); + + test('should bork when game level is out of bounds low', () { + expect( + () => SetLevelCommand(-77, null).execute(), + throwsA(isA()), + ); + }); + }); + + group('getHazardValue', () { + test('should return 1 + ceil(level / 3) for Frosthaven', () { + getIt().style = Style.frosthaven; + SetLevelCommand(0, null).execute(); + expect(GameMethods.getHazardValue(), 1); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(2, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(3, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(4, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(5, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(6, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getHazardValue(), 4); + }); + + test('should return floor(trapValue / 2) for Gloomhaven', () { + SetCampaignCommand("Gloomhaven").execute(); + getIt().fhHazTerrainCalcInOGGloom = false; + + SetLevelCommand(0, null).execute(); + expect(GameMethods.getHazardValue(), 1); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getHazardValue(), 1); + SetLevelCommand(2, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(3, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(4, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(5, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(6, null).execute(); + expect(GameMethods.getHazardValue(), 4); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getHazardValue(), 4); + }); + }); + + group('getXPValue', () { + test('should return 4 + 2 * level', () { + SetLevelCommand(0, null).execute(); + expect(GameMethods.getXPValue(), 4); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getXPValue(), 6); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getXPValue(), 18); + }); + }); + + group('getCoinValue', () { + test('should return correct coin value for level', () { + SetLevelCommand(0, null).execute(); + expect(GameMethods.getCoinValue(), 2); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getCoinValue(), 2); + SetLevelCommand(2, null).execute(); + expect(GameMethods.getCoinValue(), 3); + SetLevelCommand(3, null).execute(); + expect(GameMethods.getCoinValue(), 3); + SetLevelCommand(4, null).execute(); + expect(GameMethods.getCoinValue(), 4); + SetLevelCommand(5, null).execute(); + expect(GameMethods.getCoinValue(), 4); + SetLevelCommand(6, null).execute(); + expect(GameMethods.getCoinValue(), 5); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getCoinValue(), 6); + }); + }); + + group('getRecommendedLevel', () { + test('should return 1 if no characters', () { + getIt().clearList(); + + expect(GameMethods.getRecommendedLevel(), 1); + }); + + test('should calculate recommended level for multiple characters', () { + //getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + AddCharacterCommand( + 'Banner Spear', + 'Frosthaven', + 'Banner Spear', + 1, + ).execute(); + SetCharacterLevelCommand(3, 'Blinkblade').execute(); + SetCharacterLevelCommand(5, 'Banner Spear').execute(); + + expect(GameMethods.getRecommendedLevel(), 2); + }); + + test('should calculate recommended level for solo', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + SetCharacterLevelCommand(3, 'Blinkblade').execute(); + SetSoloCommand(true).execute(); + + expect(GameMethods.getRecommendedLevel(), 2); + }); + }); + + group('canDraw', () { + test('should return false if no characters', () { + getIt().clearList(); + expect(GameMethods.canDraw(), isFalse); + }); + + test('should return true if noInit setting is true', () { + getIt().noInit = true; + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + expect(GameMethods.canDraw(), isTrue); + }); + + test('should return false if a character has no initiative', () { + getIt().noInit = false; + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + expect(GameMethods.canDraw(), isFalse); + }); + + test('should return true if all characters have initiative', () { + getIt().noInit = false; + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + SetInitCommand( + 'Blinkblade', + 25, + gameState: getIt(), + ).execute(); + expect(GameMethods.canDraw(), isTrue); + }); + }); + + //todo: + /*group('isInactiveForRule', () { + test('should return true if monster is inactive by rule', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt()).execute(); + // In scenario 1, the Guard is inactive in round 1 + expect(GameMethods.isInactiveForRule('Guard'), isTrue); + }); + + test('should return false if monster is not inactive by rule', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt()).execute(); + expect(GameMethods.isInactiveForRule('Guard'), isFalse); + }); + });*/ + + //todo: + /*group('getDeck', () { + test('should return the correct deck', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt()).execute(); + final deck = GameMethods.getDeck('Guard'); + expect(deck, isNotNull); + expect(deck!.name, 'Guard'); + }); + + test('should return null if deck does not exist', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt()).execute(); + final deck = GameMethods.getDeck('NonExistentDeck'); + expect(deck, isNull); + }); + });*/ + + group('getInitiative', () { + test('should return character initiative', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + SetInitCommand( + 'Blinkblade', + 35, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final character = getIt().currentList.first as Character; + expect(GameMethods.getInitiative(character), 35); + checkNoSideEffects([], oldState); + }); + + //todo + /*test('should return monster initiative', () { + //getIt().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt()).execute(); + AddMonsterCommand(gameState: getIt()).execute(); + DrawAbilityCardCommand().execute(); + final monster = getIt() + .currentList + .firstWhere((m) => m is Monster) as Monster; + expect(GameMethods.getInitiative(monster), isNot(99)); + expect(GameMethods.getInitiative(monster), isNot(0)); + });*/ + }); + + group('getCharacterByName', () { + test('should return the correct character', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final character = GameMethods.getCharacterByName('Blinkblade'); + expect(character, isNotNull); + expect(character!.id, 'Blinkblade'); + checkNoSideEffects([], oldState); + }); + + test('should return null if character does not exist', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final character = GameMethods.getCharacterByName( + 'NonExistentCharacter', + ); + expect(character, isNull); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentCharacters', () { + test('should return a list of current characters', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final characters = GameMethods.getCurrentCharacters(); + expect(characters.length, 2); + expect(characters[1].id, 'Blinkblade'); + expect(characters[0].id, 'Banner Spear'); + checkNoSideEffects([], oldState); + }); + + test('should return an empty list if no characters', () { + getIt().clearList(); + String oldState = gameState.toString(); + final characters = GameMethods.getCurrentCharacters(); + expect(characters, isEmpty); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentCharacter', () { + test('should return the character whose turn it is', () { + getIt().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', "", 1).execute(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + DrawCommand(gameState: getIt()).execute(); + TurnDoneCommand( + 'Blinkblade', + gameState: getIt(), + ).execute(); // It's now Banner Spear's turn + String oldState = gameState.toString(); + final character = GameMethods.getCurrentCharacter(); + expect(character, isNotNull); + expect(character!.id, 'Banner Spear'); + checkNoSideEffects([], oldState); + }); + + test('should return null if it is not a character turn', () { + getIt().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); // Adds monsters + TurnDoneCommand( + getIt().currentList.first.id, + gameState: getIt(), + ).execute(); // It's now a monster's turn + String oldState = gameState.toString(); + final character = GameMethods.getCurrentCharacter(); + expect(character, isNull); + checkNoSideEffects([], oldState); + }); + }); + + group('getModifierDeck', () { + test('should return the monster modifier deck', () { + String oldState = gameState.toString(); + final deck = GameMethods.getModifierDeck('', getIt()); + expect(deck, equals(getIt().modifierDeck)); + checkNoSideEffects([], oldState); + }); + + test('should return the allies modifier deck', () { + String oldState = gameState.toString(); + final deck = GameMethods.getModifierDeck('allies', getIt()); + expect(deck, equals(getIt().modifierDeckAllies)); + checkNoSideEffects([], oldState); + }); + + test('should return a character modifier deck', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + String oldState = gameState.toString(); + final deck = GameMethods.getModifierDeck( + 'Blinkblade', + getIt(), + ); + final character = getIt().currentList.first as Character; + expect(deck, equals(character.characterState.modifierDeck)); + checkNoSideEffects([], oldState); + }); + }); + + group('canAddPerk', () { + test('should return true if perk can be added', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + String oldState = gameState.toString(); + final character = getIt().currentList.first as Character; + expect(GameMethods.canAddPerk(character, 0), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if perk cannot be added', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + final character = getIt().currentList.first as Character; + AddPerkCommand(character.id, 0).execute(); + String oldState = gameState.toString(); + expect(GameMethods.canAddPerk(character, 0), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('canRemovePerk', () { + test('should return true if perk can be removed', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + final character = getIt().currentList.first as Character; + AddPerkCommand(character.id, 0).execute(); + String oldState = gameState.toString(); + expect(GameMethods.canRemovePerk(character, 0), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if perk cannot be removed', () { + getIt().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + final character = getIt().currentList.first as Character; + AddPerkCommand(character.id, 12).execute(); + AddPerkCommand(character.id, 13).execute(); + String oldState = gameState.toString(); + expect(GameMethods.canRemovePerk(character, 5), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('perkGfxIdToCardId', () { + test('should return the original gfx id if it is not a perk', () { + String oldState = gameState.toString(); + final id = GameMethods.perkGfxIdToCardId( + 'test', + PerkModel("", const [], const []), + 0, + ); + expect(id, 'test'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct card id for a perk', () { + String oldState = gameState.toString(); + final perk = PerkModel("", const [], const ['perks/test']); + final id = GameMethods.perkGfxIdToCardId('perks/test', perk, 0); + expect(id, 'P0'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct card id for a perk with two images', () { + String oldState = gameState.toString(); + final perk = PerkModel("", const [], const [ + 'perks/test', + 'perks/test2', + ]); + final id = GameMethods.perkGfxIdToCardId('perks/test2', perk, 0); + expect(id, 'P0-2'); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentCharacterAmount', () { + test('should return the number of characters', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + expect(GameMethods.getCurrentCharacterAmount(), 2); + checkNoSideEffects([], oldState); + }); + + test('should return 0 if no characters', () { + getIt().clearList(); + String oldState = gameState.toString(); + expect(GameMethods.getCurrentCharacterAmount(), 0); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentMonsters', () { + test('should return a list of current monsters', () { + getIt().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final monsters = GameMethods.getCurrentMonsters(); + expect(monsters.length, 3); + expect(monsters[0].id, 'Zealot'); + expect(monsters[1].id, 'Chaos Demon'); + expect(monsters[2].id, 'Blood Tumor'); + checkNoSideEffects([], oldState); + }); + + test('should return an empty list if no monsters', () { + getIt().clearList(); + String oldState = gameState.toString(); + final monsters = GameMethods.getCurrentMonsters(); + expect(monsters, isEmpty); + checkNoSideEffects([], oldState); + }); + }); + + /*group('getNextAvailableBnBStandee', () { + test('should return the next available standee number', () { + getIt().clearList(); + SetCampaignCommand('Buttons and Bugs').execute(); + //todo: + //SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt()).execute(); + final monster = getIt().currentList.first as Monster; + AddStandeeCommand(1, null, monster.id, MonsterType.normal, false, gameState: getIt()) + .execute(); + final nextStandee = GameMethods.getNextAvailableBnBStandee(monster); + expect(nextStandee, 2); + }); + });*/ + + group('getRandomStandee', () { + test('should return a valid standee number', () { + getIt().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt().currentList.first as Monster; + final standee = GameMethods.getRandomStandee(monster); + expect(standee, isNot(0)); + expect(standee, lessThanOrEqualTo(monster.type.count)); + checkNoSideEffects([], oldState); + }); + }); + + group('getFigure', () { + test('should return a character', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final figure = GameMethods.getFigure(null, 'Blinkblade'); + expect(figure, isNotNull); + expect(figure, isA()); + checkNoSideEffects([], oldState); + }); + + test('should return a monster instance', () { + getIt().clearList(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); + final monster = getIt().currentList.first as Monster; + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final figure = GameMethods.getFigure( + monster.id, + monster.monsterInstances.first.getId(), + ); + expect(figure, isNotNull); + expect(figure, isA()); + checkNoSideEffects([], oldState); + }); + }); + + group('getFigureIdFromNr', () { + test('should return the figure id', () { + getIt().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); + final monster = getIt().currentList.first as Monster; + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final id = GameMethods.getFigureIdFromNr(monster.id, 1); + expect(id, isNotNull); + expect(id, isNotEmpty); + checkNoSideEffects([], oldState); + }); + }); + + group('isObjectiveOrEscort', () { + test('should return true for Objective', () { + final cmd = AddCharacterCommand("Objective", "na", "whatever", 1); + String oldState = gameState.toString(); + expect( + GameMethods.isObjectiveOrEscort(cmd.character!.characterClass), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return true for Escort', () { + final cmd = AddCharacterCommand("Escort", "na", "whatever", 1); + String oldState = gameState.toString(); + expect( + GameMethods.isObjectiveOrEscort(cmd.character!.characterClass), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return false for other characters', () { + final cmd = AddCharacterCommand( + "Blinkblade", + "Frosthaven", + "whatever", + 1, + ); + String oldState = gameState.toString(); + expect( + GameMethods.isObjectiveOrEscort(cmd.character!.characterClass), + isFalse, + ); + checkNoSideEffects([], oldState); + }); + }); + + group('shouldShowAlliesDeck', () { + test('should return true if showAllyDeck setting is true', () { + String oldState = gameState.toString(); + getIt().showAmdDeck = true; + ShowAllyDeckCommand().execute(); + expect(GameMethods.shouldShowAlliesDeck(), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if showAmdDeck setting is false', () { + String oldState = gameState.toString(); + getIt().showAmdDeck = false; + expect(GameMethods.shouldShowAlliesDeck(), isFalse); + checkNoSideEffects([], oldState); + }); + + test('should return true if an ally monster is in play', () { + getIt().showAmdDeck = true; + getIt().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); // Adds monsters + AddMonsterCommand( + "Zealot", + 1, + true, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + expect(GameMethods.shouldShowAlliesDeck(), isTrue); + checkNoSideEffects([], oldState); + }); + }); + + group('canExpire', () { + test('should return true for conditions that expire', () { + String oldState = gameState.toString(); + expect(GameMethods.canExpire(Condition.strengthen), isTrue); + expect(GameMethods.canExpire(Condition.muddle), isTrue); + expect(GameMethods.canExpire(Condition.invisible), isTrue); + expect(GameMethods.canExpire(Condition.stun), isTrue); + expect(GameMethods.canExpire(Condition.disarm), isTrue); + expect(GameMethods.canExpire(Condition.immobilize), isTrue); + expect(GameMethods.canExpire(Condition.impair), isTrue); + expect(GameMethods.canExpire(Condition.chill), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for conditions that do not expire', () { + String oldState = gameState.toString(); + expect(GameMethods.canExpire(Condition.bane), isFalse); + expect(GameMethods.canExpire(Condition.poison), isFalse); + expect(GameMethods.canExpire(Condition.wound), isFalse); + expect(GameMethods.canExpire(Condition.regenerate), isFalse); + expect(GameMethods.canExpire(Condition.ward), isFalse); + expect(GameMethods.canExpire(Condition.brittle), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('isFrosthavenStyledEdition', () { + test('should return true for Frosthaven', () { + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Frosthaven'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return true for Buttons and Bugs', () { + String oldState = gameState.toString(); + expect( + GameMethods.isFrosthavenStyledEdition('Buttons and Bugs'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return true for Gloomhaven 2nd Edition', () { + String oldState = gameState.toString(); + expect( + GameMethods.isFrosthavenStyledEdition('Gloomhaven 2nd Edition'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return true for Mercenary Packs', () { + String oldState = gameState.toString(); + expect( + GameMethods.isFrosthavenStyledEdition('Mercenary Packs'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return false for Gloomhaven', () { + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Gloomhaven'), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('isFrosthavenStyle', () { + test('should return true for Frosthaven monster', () { + final monster = Monster('Ancient Artillery (FH)', 1, false); + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyle(monster.type), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for Gloomhaven monster', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); // Adds monsters + String oldState = gameState.toString(); + final monster = Monster('Zealot', 1, false); + getIt().style = Style.original; + expect(GameMethods.isFrosthavenStyle(monster.type), isFalse); + checkNoSideEffects([], oldState); + }); + + test('should return true if style is set to Frosthaven', () { + String oldState = gameState.toString(); + getIt().style = Style.frosthaven; + expect(GameMethods.isFrosthavenStyle(null), isTrue); + checkNoSideEffects([], oldState); + }); + }); + + group('isCustomCampaign', () { + test('should return true for Crimson Scales', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('Crimson Scales'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return true for Trail of Ashes', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('Trail of Ashes'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return true for CCUG', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('CCUG'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for Frosthaven', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('Frosthaven'), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('findNrFromScenarioName', () { + test('should return the scenario number from the name', () { + String oldState = gameState.toString(); + expect(GameMethods.findNrFromScenarioName('#1 '), 1); + expect( + GameMethods.findNrFromScenarioName('#10.0 A Sticky Situation'), + 10, + ); + expect(GameMethods.findNrFromScenarioName('#123 - Some Scenario'), 123); + checkNoSideEffects([], oldState); + }); + + test('should return null if no number is found', () { + String oldState = gameState.toString(); + expect(GameMethods.findNrFromScenarioName('Some Scenario'), isNull); + checkNoSideEffects([], oldState); + }); + }); + + group('isOgGloomEdition', () { + test('should return true for Gloomhaven', () { + SetCampaignCommand('Gloomhaven').execute(); + String oldState = gameState.toString(); + expect(GameMethods.isOgGloomEdition(), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for Frosthaven', () { + SetCampaignCommand('Frosthaven').execute(); + String oldState = gameState.toString(); + expect(GameMethods.isOgGloomEdition(), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('hasLootDeck', () { + test('should return true if loot deck has cards', () { + getIt().clearList(); + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + //DrawLootCardCommand(gameState: getIt()).execute(); + expect(GameMethods.hasLootDeck(), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if loot deck is empty', () { + //getIt().clearLootDeck(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + expect(GameMethods.hasLootDeck(), isFalse); + checkNoSideEffects([], oldState); + }); + + test('should return false if hideLootDeck setting is true', () { + String oldState = gameState.toString(); + getIt().hideLootDeck = true; + expect(GameMethods.hasLootDeck(), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('getFactionCards', () { + test('should return the correct cards for Demons', () { + String oldState = gameState.toString(); + final cards = GameMethods.getFactionCards('Demons'); + expect(cards.length, 4); + expect(cards[0].gfx, 'Demons-perks/plus1any'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct cards for Merchant-Guild', () { + String oldState = gameState.toString(); + final cards = GameMethods.getFactionCards('Merchant-Guild'); + expect(cards.length, 4); + expect(cards[0].gfx, 'Merchant-Guild-perks/plus1curse'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct cards for Military', () { + String oldState = gameState.toString(); + final cards = GameMethods.getFactionCards('Military'); + expect(cards.length, 4); + expect(cards[0].gfx, 'Military-perks/plus1strengthenally'); + checkNoSideEffects([], oldState); + }); + }); + + group('isCardInAnyCharacterDeck', () { + test('should return true if card is in a character deck', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + final character = getIt().currentList.first as Character; + AddPerkCommand(character.id, 3).execute(); // Adds a +1 card + String oldState = gameState.toString(); + expect(GameMethods.isCardInAnyCharacterDeck('P3'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if card is not in any character deck', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + expect(GameMethods.isCardInAnyCharacterDeck('P3'), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('hasRetaliate', () { + test('should return true if monster has retaliate', () { + getIt().clearList(); + AddMonsterCommand( + "Flame Demon (BnB)", + 3, + false, + gameState: getIt(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Flame Demon (BnB)", + MonsterType.boss, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasRetaliate(monster, instance), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if monster does not have retaliate', () { + getIt().clearList(); + AddMonsterCommand( + "Black Sludge", + 3, + false, + gameState: getIt(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Black Sludge", + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasRetaliate(monster, instance), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('hasShield', () { + test('should return true if monster has shield', () { + getIt().clearList(); + AddMonsterCommand( + "Black Sludge", + 3, + false, + gameState: getIt(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Black Sludge", + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasShield(monster, instance), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if monster does not have shield', () { + getIt().clearList(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasShield(monster, instance), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('canDraw - dead character bypasses initiative check', () { + test( + 'dead character (health=0) does not block draw even with no init', + () { + getIt().clearList(); + getIt().noInit = false; + AddCharacterCommand('Blinkblade', 'Frosthaven', null, 1).execute(); + // Kill the character so health = 0 + final character = getIt().currentList.first as Character; + // Reduce health to 0 via ChangeHealthCommand + ChangeHealthCommand( + -1000, + 'Blinkblade', + 'Blinkblade', + gameState: getIt(), + ).execute(); + expect(character.characterState.health, 0); + // Dead character with 0 initiative should NOT block the draw + expect(GameMethods.canDraw(), isTrue); + }, + ); + }); + + group('getInitiative - inactive monster', () { + test('inactive monster returns initiative 99', () { + getIt().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt(), + ).execute(); + final monster = getIt().currentList.first as Monster; + // Monster is inactive by default (isActive = false until ability drawn) + expect(monster.isActive, isFalse); + String oldState = gameState.toString(); + expect(GameMethods.getInitiative(monster), 99); + checkNoSideEffects([], oldState); + }); + }); + + group('summonDoesNotDie', () { + test('Glacial Torrent Glacier does not die', () { + String oldState = gameState.toString(); + expect( + GameMethods.summonDoesNotDie('Glacial Torrent', 'Glacier'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('D.O.M.E. Barrier does not die', () { + String oldState = gameState.toString(); + expect(GameMethods.summonDoesNotDie('D.O.M.E.', 'Barrier'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('arbitrary owner and id returns false', () { + String oldState = gameState.toString(); + expect( + GameMethods.summonDoesNotDie('Blinkblade', 'Jade Falcon'), + isFalse, + ); + checkNoSideEffects([], oldState); + }); + }); + + group('getFigure - character summon lookup', () { + test('returns summon instance when found via character ownerId', () { + getIt().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', null, 1).execute(); + final character = getIt().currentList.first as Character; + // Add a summon to the character + final summonData = SummonData( + 1, + 'Jade Falcon', + 3, + 2, + 2, + 0, + 'Jade Falcon', + ); + AddStandeeCommand( + 1, + summonData, + 'Blinkblade', + MonsterType.normal, + true, + gameState: getIt(), + ).execute(); + + expect(character.characterState.summonList, isNotEmpty); + final summon = character.characterState.summonList.first; + final figureId = summon.getId(); + + String oldState = gameState.toString(); + final figure = GameMethods.getFigure('Blinkblade', figureId); + expect(figure, isNotNull); + expect(figure, isA()); + checkNoSideEffects([], oldState); + }); + }); + + group('isFrosthavenStyledEdition - Solo edition', () { + test('Solo with Frosthaven scenario number is frosthaven styled', () { + // Directly set the scenario string to avoid SetScenarioCommand's loot-deck lookup + gameState.scenario = '#1 A Town Aflame'; + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Solo'), isTrue); + checkNoSideEffects(['scenario'], oldState); + }); + + test( + 'Solo with #19 scenario is NOT frosthaven styled (Forgotten Circles)', + () { + gameState.scenario = '#19 Forgotten Circles'; + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Solo'), isFalse); + checkNoSideEffects(['scenario'], oldState); + }, + ); + + test( + 'Solo with scenario not in 1-100 range is not frosthaven styled', + () { + gameState.scenario = '#200 Some Scenario'; + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Solo'), isFalse); + checkNoSideEffects(['scenario'], oldState); + }, + ); + }); + + group('hasShield - boss type', () { + test('boss type standee checks boss attribute for shield', () { + getIt().clearList(); + // Flame Demon (BnB) is a boss with retaliate; use it to test boss path + AddMonsterCommand( + 'Flame Demon (BnB)', + 3, + false, + gameState: getIt(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Flame Demon (BnB)', + MonsterType.boss, + false, + gameState: getIt(), + ).execute(); + final monster = getIt().currentList.first as Monster; + final instance = monster.monsterInstances.first; + // Boss path is exercised; result depends on actual data, just verify no crash + expect(GameMethods.hasShield(monster, instance), isA()); + expect(GameMethods.hasRetaliate(monster, instance), isA()); + }); + }); + + group('getNextAvailableBnBStandee', () { + test('returns next available standee number when one is taken', () { + getIt().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt(), + ).execute(); + final monster = getIt().currentList.first as Monster; + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + String oldState = gameState.toString(); + final next = GameMethods.getNextAvailableBnBStandee(monster); + // Standee 1 is taken; next available should be 2 + expect(next, 2); + checkNoSideEffects([], oldState); + }); + + test('returns 0 when all standees are taken', () { + getIt().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt(), + ).execute(); + final monster = getIt().currentList.first as Monster; + for (int i = 1; i <= monster.type.count; i++) { + AddStandeeCommand( + i, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + } + String oldState = gameState.toString(); + final next = GameMethods.getNextAvailableBnBStandee(monster); + expect(next, 0); + checkNoSideEffects([], oldState); + }); + }); + }); +} diff --git a/server/test/resource/line_builder/line_builder_test.dart b/server/test/resource/line_builder/line_builder_test.dart new file mode 100644 index 0000000..c6aece7 --- /dev/null +++ b/server/test/resource/line_builder/line_builder_test.dart @@ -0,0 +1,67 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/line_builder/line_builder.dart'; + +// Only the pure-logic parts of the reference `line_builder_test.dart` are +// ported: the widget/metrics tests (`createLines`, `getTopPaddingForStyle`) +// depend on Flutter classes and the unported rendering code, so they are +// skipped until the Phase 4 web client re-implements the rendering. + +void main() { + // ── isElement ───────────────────────────────────────────────────────────── + + group('LineBuilder.isElement', () { + test('"fire" is an element', () { + expect(LineBuilder.isElement('fire'), isTrue); + }); + + test('"air" is an element', () { + expect(LineBuilder.isElement('air'), isTrue); + }); + + test('"earth" is an element', () { + expect(LineBuilder.isElement('earth'), isTrue); + }); + + test('"ice" is an element', () { + expect(LineBuilder.isElement('ice'), isTrue); + }); + + test('"dark" is an element', () { + expect(LineBuilder.isElement('dark'), isTrue); + }); + + test('"light" is an element', () { + expect(LineBuilder.isElement('light'), isTrue); + }); + + test('"any" is an element', () { + expect(LineBuilder.isElement('any'), isTrue); + }); + + test('string containing element name returns true', () { + // e.g. "fire_fh" contains "fire" + expect(LineBuilder.isElement('fire_fh'), isTrue); + expect(LineBuilder.isElement('dark_half'), isTrue); + }); + + test('"attack" is not an element', () { + expect(LineBuilder.isElement('attack'), isFalse); + }); + + test('"move" is not an element', () { + expect(LineBuilder.isElement('move'), isFalse); + }); + + test('"poison" is not an element', () { + expect(LineBuilder.isElement('poison'), isFalse); + }); + + test('empty string is not an element', () { + expect(LineBuilder.isElement(''), isFalse); + }); + + test('"heal" is not an element', () { + expect(LineBuilder.isElement('heal'), isFalse); + }); + }); +} diff --git a/server/test/resource/line_builder/stat_applier_test.dart b/server/test/resource/line_builder/stat_applier_test.dart new file mode 100644 index 0000000..c87e81b --- /dev/null +++ b/server/test/resource/line_builder/stat_applier_test.dart @@ -0,0 +1,284 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/line_builder/stat_applier.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import '../../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt().clearList(); + SetLevelCommand(1, null).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt(), + ).execute(); + }); + + // Zealot level 1: normal attack=2 move=2 range=0, elite attack=3 move=2 range=0 + + Monster zealot() => + getIt().currentList.firstWhere((e) => e.id == 'Zealot') + as Monster; + + // ── plain text – no formulas ────────────────────────────────────────────── + + group('StatApplier.applyMonsterStats – plain text', () { + test('line with no formula is returned unchanged', () { + final result = StatApplier.applyMonsterStats( + 'Move 3', + '', + zealot(), + false, + ); + expect(result, equals(['Move 3'])); + }); + + test('line with pure text and token name unchanged', () { + final result = StatApplier.applyMonsterStats( + '%attack%', + '', + zealot(), + false, + ); + expect(result, equals(['%attack%'])); + }); + + test('single digit with no preceding token is treated as plain text', () { + // "3" alone at position 0 is a plain number; no token → calculateFormula("3")=3 + // but length must be >2 or formula must have lastToken; "3" alone is length 1 → not applied + final result = StatApplier.applyMonsterStats('3', '', zealot(), false); + expect(result, equals(['3'])); + }); + }); + + // ── forceShowAll=false with no standees ────────────────────────────────── + + group('StatApplier.applyMonsterStats – no standees (forceShowAll=false)', () { + test('%attack% +0 unchanged when no standees and forceShowAll=false', () { + // showNormal=false, showElite=false → line returned as-is + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + false, + ); + expect(result, equals(['%attack% +0'])); + }); + + test('%move% +1 unchanged when no standees and forceShowAll=false', () { + final result = StatApplier.applyMonsterStats( + '%move% +1', + '', + zealot(), + false, + ); + expect(result, equals(['%move% +1'])); + }); + }); + + // ── forceShowAll=true: attack formula ───────────────────────────────────── + + group('StatApplier.applyMonsterStats – forceShowAll attack', () { + test('%attack% +0 with forceShowAll splits into multiple results', () { + // normal attack=2, elite attack=3; formula "+0" → normal=2, elite=3 + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + true, + ); + expect(result.length, greaterThan(1)); + }); + + test('normal result contains the computed normal attack value', () { + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + true, + ); + // First string contains "%attack% 2/" (the normal result) + expect(result.first, contains('2')); + }); + + test('elite result contains the computed elite attack value', () { + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + true, + ); + // Second string is the elite part starting with "!" + final elite = result.firstWhere((s) => s.startsWith('!')); + expect(elite, contains('3')); + }); + + test('%attack% +1 adds 1 to both normal and elite values', () { + // normal=2+1=3, elite=3+1=4 + final result = StatApplier.applyMonsterStats( + '%attack% +1', + '', + zealot(), + true, + ); + expect(result.first, contains('3')); + final elite = result.firstWhere((s) => s.startsWith('!')); + expect(elite, contains('4')); + }); + + test('%attack% -1 subtracts 1 (clamps to 0 if negative)', () { + // normal=2-1=1, elite=3-1=2 + final result = StatApplier.applyMonsterStats( + '%attack% -1', + '', + zealot(), + true, + ); + expect(result.first, contains('1')); + final elite = result.firstWhere((s) => s.startsWith('!')); + expect(elite, contains('2')); + }); + }); + + // ── forceShowAll=true: move formula ────────────────────────────────────── + + group('StatApplier.applyMonsterStats – forceShowAll move', () { + test('%move% +0 yields Zealot move value (2)', () { + final result = StatApplier.applyMonsterStats( + '%move% +0', + '', + zealot(), + true, + ); + expect(result.first, contains('2')); + }); + + test('%move% +2 yields Zealot move+2 (4) for both', () { + // normal move=2+2=4, elite move=2+2=4 + final result = StatApplier.applyMonsterStats( + '%move% +2', + '', + zealot(), + true, + ); + expect(result.first, contains('4')); + }); + }); + + // ── with standees present (forceShowAll=false) ─────────────────────────── + + group('StatApplier.applyMonsterStats – with actual standees', () { + test('normal standee present → shows normal stat', () { + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt(), + ).execute(); + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + false, + ); + // showNormal=true, showElite=false + expect(result.first, contains('2')); + // No elite part + expect(result.every((s) => !s.contains('3')), isTrue); + getIt().undo(); + }); + + test('elite standee present → shows both normal and elite stat', () { + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.elite, + false, + gameState: getIt(), + ).execute(); + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + false, + ); + // showElite=true → split output with both values + expect(result.length, greaterThan(1)); + expect(result.any((s) => s.contains('3')), isTrue); + getIt().undo(); + }); + }); + + // ── formula without preceding token ────────────────────────────────────── + + group('StatApplier.applyMonsterStats – standalone formula', () { + test('C+L formula (≥3 chars, no token) is evaluated', () { + // With level=1 and 0 characters (C clamped to 2): C+L = 2+1 = 3 + final result = StatApplier.applyMonsterStats( + 'C+L health', + '', + zealot(), + false, + ); + expect(result.first, contains('3')); + }); + + test('plain number ≥3 digits is evaluated as formula', () { + // "100" is 3 chars and contains only digits; calculateFormula("100")=100 + final result = StatApplier.applyMonsterStats( + '100 damage', + '', + zealot(), + false, + ); + expect(result.first, contains('100')); + }); + }); + + // ── shield from attribute ───────────────────────────────────────────────── + + group('StatApplier.applyMonsterStats – shield token', () { + setUp(() { + getIt().clearList(); + SetLevelCommand(1, null).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + // Black Sludge has %shield% 1 in both normal and elite at level 1 + AddMonsterCommand( + 'Black Sludge', + 1, + false, + gameState: getIt(), + ).execute(); + }); + + Monster blackSludge() => + getIt().currentList.firstWhere((e) => e.id == 'Black Sludge') + as Monster; + + test('%shield% +0 with Black Sludge yields shield value 1', () { + final result = StatApplier.applyMonsterStats( + '%shield% +0', + '', + blackSludge(), + true, + ); + expect(result.first, contains('1')); + }); + }); +} diff --git a/server/test/resource/modifier_deck_test.dart b/server/test/resource/modifier_deck_test.dart new file mode 100644 index 0000000..bb5daa0 --- /dev/null +++ b/server/test/resource/modifier_deck_test.dart @@ -0,0 +1,175 @@ +// ignore_for_file: avoid-late-keyword, no-empty-block, no-magic-number, avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_imbue1_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue2_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_imbue_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_bless_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_curse_command.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import '../command/test_helpers.dart'; + +void main() { + late GameState gameState; + + setUpAll(() async { + // Registers the core singletons (save store, game data, settings) once; + // each test still gets a fresh [GameState] below, mirroring the + // reference app's per-test `makeGameAndSettings()`. + await setUpGame(); + }); + + setUp(() { + gameState = GameState(); + gameState.init(); + }); + + ModifierDeck deck() => gameState.modifierDeck; + + // ── draw() ──────────────────────────────────────────────────────────────── + + group('ModifierDeck.draw', () { + test('drawing multiply card sets needsShuffle', () { + bool foundMultiply = false; + for (int i = 0; i < 50; i++) { + if (deck().drawPileIsEmpty) break; + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + if (deck().discardPileContents.any( + (c) => c.type == CardType.multiply, + )) { + foundMultiply = true; + break; + } + } + if (foundMultiply) { + expect(deck().needsShuffle, isTrue); + } + }); + + test('drawing a bless card decrements bless count', () { + gameState.action(ChangeBlessCommand(1, '', '', gameState: gameState)); + gameState.action(ChangeBlessCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('bless'), 2); + + bool drewBless = false; + for (int i = 0; i < 30; i++) { + if (deck().drawPileIsEmpty) break; + final before = deck().getRemovable('bless'); + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + if (deck().getRemovable('bless') < before) { + drewBless = true; + break; + } + } + if (drewBless) { + expect(deck().getRemovable('bless'), lessThan(2)); + } + }); + + test('drawing all cards triggers reshuffle when drawPile is empty', () { + final initialSize = deck().drawPileSize; + for (int i = 0; i < initialSize; i++) { + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + } + expect(deck().drawPileIsEmpty, isTrue); + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + expect(deck().discardPileSize, greaterThan(0)); + }); + }); + + // ── setImbue1 / setImbue2 / resetImbue ─────────────────────────────────── + + group('ModifierDeck imbue', () { + test('setImbue1 sets imbuement to 1 and adds imbue cards', () { + gameState.action(AMDImbue1Command(gameState: gameState)); + expect(deck().imbuement, 1); + final hasImbueCards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue'), + ); + expect(hasImbueCards, isTrue); + }); + + test('setImbue2 sets imbuement to 2 and adds imbue2 cards', () { + gameState.action(AMDImbue2Command(gameState: gameState)); + expect(deck().imbuement, 2); + final hasImbue2Cards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue2'), + ); + expect(hasImbue2Cards, isTrue); + }); + + test('setImbue2 from scratch also applies setImbue1 first', () { + expect(deck().imbuement, 0); + gameState.action(AMDImbue2Command(gameState: gameState)); + expect(deck().imbuement, 2); + final hasImbueCards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue'), + ); + expect(hasImbueCards, isTrue); + }); + + test('resetImbue from imbue1 removes imbue cards and resets to 0', () { + gameState.action(AMDImbue1Command(gameState: gameState)); + expect(deck().imbuement, 1); + gameState.action(AMDRemoveImbueCommand(gameState: gameState)); + expect(deck().imbuement, 0); + final hasImbueCards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue'), + ); + expect(hasImbueCards, isFalse); + }); + + test('resetImbue from imbue2 restores minus2 and plus0 cards', () { + gameState.action(AMDImbue2Command(gameState: gameState)); + expect(deck().imbuement, 2); + gameState.action(AMDRemoveImbueCommand(gameState: gameState)); + expect(deck().imbuement, 0); + final hasMinus2 = deck().drawPileContents.toList().any( + (c) => c.gfx == 'minus2', + ); + expect(hasMinus2, isTrue); + }); + + test('resetImbue is a no-op when imbuement is already 0', () { + expect(deck().imbuement, 0); + final drawSizeBefore = deck().drawPileSize; + gameState.action(AMDRemoveImbueCommand(gameState: gameState)); + expect(deck().imbuement, 0); + expect(deck().drawPileSize, drawSizeBefore); + }); + }); + + // ── _handleRemovableCards ───────────────────────────────────────────────── + + group('ModifierDeck removable cards', () { + test('adding a curse increases curse count and inserts card', () { + final before = deck().getRemovable('curse'); + gameState.action(ChangeCurseCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('curse'), before + 1); + final curseInDeck = deck().drawPileContents + .toList() + .where((c) => c.gfx == 'curse') + .length; + expect(curseInDeck, before + 1); + }); + + test( + 'removing a curse decreases curse count and removes card from deck', + () { + gameState.action(ChangeCurseCommand(1, '', '', gameState: gameState)); + gameState.action(ChangeCurseCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('curse'), 2); + gameState.action(ChangeCurseCommand(-1, '', '', gameState: gameState)); + expect(deck().getRemovable('curse'), 1); + }, + ); + + test('adding a bless increases bless count in deck', () { + final before = deck().getRemovable('bless'); + gameState.action(ChangeBlessCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('bless'), before + 1); + }); + }); +} diff --git a/server/test/resource/stat_calculator_test.dart b/server/test/resource/stat_calculator_test.dart new file mode 100644 index 0000000..f80c0fb --- /dev/null +++ b/server/test/resource/stat_calculator_test.dart @@ -0,0 +1,174 @@ +// ignore_for_file: avoid-late-keyword, no-empty-block, no-magic-number, avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/stat_calculator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt().clearList(); + SetLevelCommand(1, null).execute(); + }); + + // ── eval / Parser ──────────────────────────────────────────────────────── + + group('StatCalculator.eval', () { + test('parses a plain integer string', () { + expect(StatCalculator.eval('5'), 5); + }); + + test('parses addition', () { + expect(StatCalculator.eval('3+2'), 5); + }); + + test('parses subtraction', () { + expect(StatCalculator.eval('7-3'), 4); + }); + + test('parses multiplication with *', () { + expect(StatCalculator.eval('3*4'), 12); + }); + + test('parses multiplication with x', () { + // 'x' is an alternative multiplication operator + expect(StatCalculator.eval('3x4'), 12); + }); + + test('parses division with / (ceiling)', () { + // 7 / 2 = 3.5 → ceil → 4 + expect(StatCalculator.eval('7/2'), 4); + }); + + test('parses division with d (floor)', () { + // 7 d 2 = 3.5 → floor → 3 + expect(StatCalculator.eval('7d2'), 3); + }); + + test('parses parenthesised expression', () { + expect(StatCalculator.eval('(2+3)*4'), 20); + }); + + test('parses unary minus', () { + // Unary minus applied to a number; result is negative + // StatCalculator stores as int so -5 + expect(StatCalculator.eval('0-5'), -5); + }); + + test('returns null for malformed expression', () { + expect(StatCalculator.eval('abc'), isNull); + }); + + test('returns null for expression with trailing characters', () { + // '5 extra' has trailing non-parseable chars after the number + expect(StatCalculator.eval('5extra'), isNull); + }); + + test('parses condition less-than (true → 1)', () { + expect(StatCalculator.eval('2<3'), 1); + }); + + test('parses condition less-than (false → 0)', () { + expect(StatCalculator.eval('3<2'), 0); + }); + + test('parses condition greater-than (true → 1)', () { + expect(StatCalculator.eval('5>4'), 1); + }); + + test('parses condition greater-than (false → 0)', () { + expect(StatCalculator.eval('1>2'), 0); + }); + + test('parses condition equals (true → 1)', () { + expect(StatCalculator.eval('4=4'), 1); + }); + + test('parses condition equals (false → 0)', () { + expect(StatCalculator.eval('4=5'), 0); + }); + + test('ceil division: exact division gives no rounding', () { + expect(StatCalculator.eval('6/2'), 3); + }); + + test('floor division: exact division gives no rounding', () { + expect(StatCalculator.eval('6d2'), 3); + }); + + test('operator precedence: multiplication before addition', () { + // 2 + 3 * 4 = 14 only if * has higher precedence + // The parser is left-to-right for same level; + and * are different levels + // parseTerm handles * so it should be: 2 + (3*4) = 14 + expect(StatCalculator.eval('2+3*4'), 14); + }); + }); + + // ── calculateFormula ──────────────────────────────────────────────────── + + group('StatCalculator.calculateFormula', () { + test('returns int directly when passed an int', () { + expect(StatCalculator.calculateFormula(7), 7); + }); + + test('substitutes C with character count (clamped to 2 minimum)', () { + // No characters added → count = 0, clamped to 2 + expect(StatCalculator.calculateFormula('C'), 2); + }); + + test('substitutes C with actual character count when ≥ 2', () { + AddCharacterCommand('Blinkblade', 'Frosthaven', null, 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', null, 1).execute(); + AddCharacterCommand('Hail', 'Mercenary Packs', null, 1).execute(); + // 3 characters → C = 3 + expect(StatCalculator.calculateFormula('C'), 3); + }); + + test('substitutes L with current level', () { + SetLevelCommand(4, null).execute(); + expect(StatCalculator.calculateFormula('L'), 4); + }); + + test('evaluates compound formula with C and L', () { + // With 0 chars (C=2) and level 3: C+L = 2+3 = 5 + SetLevelCommand(3, null).execute(); + expect(StatCalculator.calculateFormula('C+L'), 5); + }); + + test('returns null for invalid formula string', () { + expect(StatCalculator.calculateFormula('??'), isNull); + }); + }); + + // ── evaluateCondition ──────────────────────────────────────────────────── + + group('StatCalculator.evaluateCondition', () { + test('returns true when formula evaluates to 1', () { + // '1' evaluates to 1 → true + expect(StatCalculator.evaluateCondition('1'), isTrue); + }); + + test('returns false when formula evaluates to 0', () { + expect(StatCalculator.evaluateCondition('0'), isFalse); + }); + + test('returns false when formula evaluates to something other than 1', () { + expect(StatCalculator.evaluateCondition('2'), isFalse); + }); + + test('evaluates condition expression correctly', () { + // '2<3' → 1 → true + expect(StatCalculator.evaluateCondition('2<3'), isTrue); + // '3<2' → 0 → false + expect(StatCalculator.evaluateCondition('3<2'), isFalse); + }); + }); +} diff --git a/server/test/resource/ui_utils_test.dart b/server/test/resource/ui_utils_test.dart new file mode 100644 index 0000000..fc44c02 --- /dev/null +++ b/server/test/resource/ui_utils_test.dart @@ -0,0 +1,48 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/ui_utils.dart'; + +import '../command/test_helpers.dart'; + +/// The reference `ui_utils_test.dart` has no `reducePowerEnabled` group — +/// its groups (`hasGHVersion`, text-style helpers, dialog/toast widget +/// functions) all exercise unported widget code. This file instead covers +/// the single ported `ui_utils` function, `reducePowerEnabled`, mirroring +/// the reference implementation's documented semantics. +void main() { + setUpAll(() async { + await setUpGame(); + }); + + // ── reducePowerEnabled ──────────────────────────────────────────────────── + + group('reducePowerEnabled', () { + test('returns false by default (PowerMode.normal)', () { + expect(reducePowerEnabled(), isFalse); + }); + + test('returns true when powerMode is reducePower', () { + getIt().powerMode = PowerMode.reducePower; + expect(reducePowerEnabled(), isTrue); + getIt().powerMode = PowerMode.normal; + }); + + test('returns false for dimWhenIdle (top tier only)', () { + getIt().powerMode = PowerMode.dimWhenIdle; + expect(reducePowerEnabled(), isFalse); + getIt().powerMode = PowerMode.normal; + }); + + test('honors an explicitly passed Settings instance', () { + final settings = Settings(); + settings.powerMode = PowerMode.reducePower; + expect(reducePowerEnabled(settings: settings), isTrue); + settings.powerMode = PowerMode.normal; + expect(reducePowerEnabled(settings: settings), isFalse); + }); + }); +} -- cgit v1.3.1