summaryrefslogtreecommitdiff
path: root/server/lib/core/game_methods.dart
blob: 646a9f2ac39d1e1a6807160a2d9fc38409045b54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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>();
    final 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) {
    final 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}) {
    final 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>();
    final 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
    }
    final 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) {
            final 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) {
            final 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>();
    final 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) {
    final 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;
  }
}