summaryrefslogtreecommitdiff
path: root/server/lib/core/methods/round_methods.dart
blob: 4ad146d8c075802b8b4b64d851a6503148da25b2 (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
part of '../state/game_state.dart';

// ignore_for_file: library_private_types_in_public_api

class RoundMethods {
  static const int _kMaxLevel = 7;
  static const int _kMinLevel = 0;
  static void setRoundState(
    _StateModifier _,
    RoundState state, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    gs._roundState = state;
  }

  static void setRound(_StateModifier _, int round, {GameState? gameState}) {
    final gs = gameState ?? getIt<GameState>();
    gs._round = round;
    gs._totalRounds++;
  }

  static void resetRound(
    _StateModifier _,
    int round,
    bool resetTotal, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    gs._round = round;
    if (resetTotal) {
      gs._totalRounds = round;
    }
  }

  static void sortCharactersFirst(_StateModifier _, {GameState? gameState}) {
    final gs = gameState ?? getIt<GameState>();
    gs._currentList.sort(_compareForCharactersFirst);
    // Sorting compares note rows as initiative 0, scattering them; re-glue any
    // linked notes back under their target. Callers that notify via
    // updateList.notify() (e.g. DrawCommand) bypass _notifyCurrentList, so the
    // reflow must happen here rather than only in _notifyCurrentList.
    gs._reflowNoteRows();
  }

  static int _compareForCharactersFirst(ListItemData a, ListItemData b) {
    final deadResult = _compareDeadCharacters(a, b);
    if (deadResult != null) return deadResult;

    final aIsChar = a is Character;
    final bIsChar = b is Character;
    if (aIsChar && bIsChar) return 0;
    if (bIsChar) return 1;
    if (aIsChar) return -1;

    // both are monsters — inactive at bottom
    if (a is Monster && b is Monster) {
      if (a.isActive && !b.isActive) return -1;
      if (!a.isActive && b.isActive) return 1;
    }
    return -1;
  }

  // Returns a sort result if either figure is a dead character (dead go last),
  // or null if neither is dead and the caller should continue comparing.
  static int? _compareDeadCharacters(ListItemData a, ListItemData b) {
    final aIsDead = a is Character && a.characterState.health == 0;
    final bIsDead = b is Character && b.characterState.health == 0;
    if (!aIsDead && bIsDead) return -1;
    if (aIsDead && !bIsDead) return 1;
    if (aIsDead) return -1; // both dead characters
    return null;
  }

  static void sortItemToPlace(
    _StateModifier _,
    String id,
    int initiative, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    final newList = gs.currentList.toList();
    ListItemData? item;
    int currentTurnItemIndex = 0;
    for (int i = 0; i < newList.length; i++) {
      if (newList[i].turnState == TurnsState.current) {
        currentTurnItemIndex = i;
      }
      if (newList[i].id == id) {
        item = newList.removeAt(i);
      }
    }
    if (item == null) {
      return;
    }

    int init = 0;
    for (int i = 0; i < newList.length; i++) {
      ListItemData currentItem = newList[i];
      int currentItemInitiative = GameMethods.getInitiative(currentItem);
      if (currentItemInitiative > initiative && currentItemInitiative > init) {
        if (i > currentTurnItemIndex) {
          newList.insert(i, item);
          gs._currentList = newList;
          gs._notifyCurrentList();
          return;
        } else {
          //in case initiative is earlier than current turn, ignore anything current turn, and earlier and place later
          int insertIndex = currentTurnItemIndex + 1;
          for (int j = currentTurnItemIndex + 1; j < newList.length; j++) {
            if (GameMethods.getInitiative(newList[j]) >= initiative) {
              insertIndex = j;
              break;
            }
          }
          if (insertIndex > newList.length) {
            newList.add(item);
          } else {
            newList.insert(insertIndex, item);
          }

          gs._currentList = newList;
          gs._notifyCurrentList();
          return;
        }
      }
      init =
          currentItemInitiative; //this check is for the case user has moved items around the order may be off
    }

    newList.add(item);
    gs._currentList = newList;
    gs._notifyCurrentList();
  }

  static void sortByInitiative(_StateModifier _, {GameState? gameState}) {
    final gs = gameState ?? getIt<GameState>();
    gs._currentList.sort((a, b) {
      final deadResult = _compareDeadCharacters(a, b);
      if (deadResult != null) return deadResult;

      int aInitiative = 0;
      int bInitiative = 0;
      if (a is Character) {
        aInitiative = a.characterState.initiative;
      } else if (a is Monster) {
        if (!a.isActive) {
          if (b is Monster && !b.isActive) {
            return -1;
          }
          return 1; //inactive at bottom
        }

        //find the deck
        for (final item in gs.currentAbilityDecks) {
          if (item.name == a.type.deck && item.discardPileIsNotEmpty) {
            aInitiative = item.discardPileTop.initiative;
          }
        }
      }
      if (b is Character) {
        bInitiative = b.characterState.initiative;
      } else if (b is Monster) {
        if (!b.isActive) {
          if (a is Monster && !a.isActive) {
            return 1;
          }
          return -1; //inactive at bottom
        }
        //find the deck
        for (final item in gs.currentAbilityDecks) {
          if (item.name == b.type.deck && item.discardPileIsNotEmpty) {
            bInitiative = item.discardPileTop.initiative;
          }
        }
      }
      return aInitiative.compareTo(bInitiative);
    });
    // Re-glue linked note rows after the initiative sort (see sortCharactersFirst).
    gs._reflowNoteRows();
  }

  static void sortMonsterInstances(
    _StateModifier _,
    List<MonsterInstance> instances,
  ) {
    instances.sort((a, b) {
      if (a.type == MonsterType.elite && b.type != MonsterType.elite) {
        return -1;
      }
      if (b.type == MonsterType.elite && a.type != MonsterType.elite) {
        return 1;
      }
      return a.standeeNr.compareTo(b.standeeNr);
    });
  }

  static void addToMainList(
    _StateModifier _,
    int? index,
    ListItemData item, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    final newList = gs.currentList.toList();
    if (index != null) {
      newList.insert(index, item);
    } else {
      newList.add(item);
    }
    gs._currentList = newList;
    gs._notifyCurrentList();
  }

  static void reorderMainList(
    _StateModifier _,
    int newIndex,
    int oldIndex, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    gs._currentList.insert(newIndex, gs._currentList.removeAt(oldIndex));
    gs._notifyCurrentList();
  }

  static void removeFromMainList(
    _StateModifier _,
    String id, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    gs._currentList = gs._currentList.where((item) => item.id != id).toList();
    gs._notifyCurrentList();
  }

  /// Deletes any note rows tied to a specific standee ([standeeNr] > 0) of the
  /// monster [linkedId] — called when that standee is defeated so its note goes
  /// with it. Notes for the whole group (standeeNr 0) are left alone.
  static void removeNoteRowsForStandee(
    _StateModifier _,
    String linkedId,
    int standeeNr, {
    GameState? gameState,
  }) {
    if (standeeNr <= 0) return;
    final gs = gameState ?? getIt<GameState>();
    final filtered = gs._currentList
        .where(
          (item) =>
              !(item is NoteRow &&
                  item.linkedId == linkedId &&
                  item.standeeNr == standeeNr),
        )
        .toList();
    if (filtered.length != gs._currentList.length) {
      gs._currentList = filtered;
      gs._notifyCurrentList();
    }
  }

  static void updateForSpecialRules(
    _StateModifier _, {
    GameState? gameState,
    GameData? gameData,
  }) {
    final gs = gameState ?? getIt<GameState>();
    final gd = gameData ?? getIt<GameData>();
    List<SpecialRule>? rules =
        gd.modelData[gs.currentCampaign]?.scenarios[gs.scenario]?.specialRules;
    if (rules != null) {
      for (SpecialRule rule in rules) {
        if (rule.type == "Objective" || rule.type == "Escort") {
          Character? character =
              gs.currentList.firstWhereOrNull(
                    (element) => element.id == rule.name,
                  )
                  as Character?;
          if (character != null) {
            int? newHealth = StatCalculator.calculateFormula(
              rule.health.toString(),
            );
            if (newHealth != character.characterState.maxHealth &&
                newHealth != null) {
              character.characterState._maxHealth = newHealth;
              character.characterState._health = newHealth;
            }
          }
        } else if (rule.type == "LevelAdjust") {
          Monster? monster =
              gs.currentList.firstWhereOrNull(
                    (element) => element.id == rule.name,
                  )
                  as Monster?;
          if (monster != null) {
            if (gs.level == monster.level) {
              int newLevel = (monster.level + rule.level).clamp(
                _kMinLevel,
                _kMaxLevel,
              );
              monster._level = newLevel;
              for (MonsterInstance instance in monster._monsterInstances) {
                instance._setLevel(monster);
              }
            }
          }
        }
      }
    }
  }

  static void clearTurnStateConditions(
    _StateModifier _,
    FigureState figure,
    bool clearLastTurnToo,
  ) {
    if (!clearLastTurnToo) {
      figure._conditionsAddedPreviousTurn.clear();
      figure._conditionsAddedPreviousTurn.addAll(
        figure.conditionsAddedThisTurn.toSet(),
      );
    } else {
      figure._conditionsAddedPreviousTurn.clear();
    }

    figure._conditionsAddedThisTurn.clear();

    figure._chill = figure.conditions.where((a) => a == Condition.chill).length;
  }

  static void clearTurnState(
    _StateModifier stateModifier,
    bool clearLastTurnToo, {
    GameState? gameState,
  }) {
    final gs = gameState ?? getIt<GameState>();
    for (final item in gs._currentList) {
      item._turnState = TurnsState.notDone;
      if (item is Character) {
        clearTurnStateConditions(
          stateModifier,
          item.characterState,
          clearLastTurnToo,
        );
        for (final instance in item.characterState._summonList) {
          clearTurnStateConditions(stateModifier, instance, clearLastTurnToo);
        }
      } else if (item is Monster) {
        for (final instance in item._monsterInstances) {
          clearTurnStateConditions(stateModifier, instance, clearLastTurnToo);
        }
      }
    }
  }

  static void removeExpiringConditions(
    _StateModifier _,
    FigureState figure, {
    Settings? settings,
  }) {
    if ((settings ?? getIt<Settings>()).expireConditions) {
      final conditions = figure._conditions;

      //handle chill separately
      int nrOfChills = figure.conditions
          .where((a) => a == Condition.chill)
          .length;
      if (nrOfChills > 0) {
        //remove one if not added this turn
        if (!figure.conditionsAddedThisTurn.contains(Condition.chill) ||
            nrOfChills >
                1 //this is a cop out: you can add more than one chill in a round, but since we store only if a condition has been added this turn, and not the amount, we have no way to tell
                ) {
          conditions.remove(Condition.chill);
          figure._conditionsAddedPreviousTurn.add(Condition.chill);
        }
      }

      figure._chill = figure.conditions
          .where((a) => a == Condition.chill)
          .length;

      for (int i = conditions.length - 1; i >= 0; i--) {
        Condition item = conditions[i];
        if (GameMethods.canExpire(item)) {
          if (item != Condition.chill) {
            if (!figure.conditionsAddedThisTurn.contains(item)) {
              conditions.removeAt(i);
              figure._conditionsAddedPreviousTurn.add(item);
            }
          }
        }
      }
    }
  }

  static void removeExpiringConditionsFromListItem(
    _StateModifier s,
    ListItemData item,
  ) {
    if (item is Character) {
      removeExpiringConditions(s, item.characterState);
      for (final summon in item.characterState._summonList) {
        removeExpiringConditions(s, summon);
      }
    } else if (item is Monster) {
      for (final instance in item._monsterInstances) {
        removeExpiringConditions(s, instance);
      }
    }
  }

  static void reapplyConditions(_StateModifier _, FigureState figure) {
    for (final condition in figure.conditionsAddedPreviousTurn) {
      final conditions = figure._conditions;
      if (!conditions.contains(condition) || condition == Condition.chill) {
        conditions.add(condition);
        figure._conditionsAddedThisTurn.remove(condition);
      }
      if (condition == Condition.chill) {
        figure._chill = figure.conditions
            .where((a) => a == Condition.chill)
            .length;
      }
    }
  }

  static void reapplyConditionsFromListItem(
    _StateModifier s,
    ListItemData item,
  ) {
    if (item is Character) {
      reapplyConditions(s, item.characterState);
      for (final summon in item.characterState.summonList) {
        reapplyConditions(s, summon);
      }
    } else if (item is Monster) {
      for (final instance in item._monsterInstances) {
        reapplyConditions(s, instance);
      }
    }
  }

  //1 if item WAS done OR not done, then set it to current, all before to done, and all after to not done
  //2 if item was current: set item to done, all before to done, next to current and rest to not done
  static void setTurnDone(_StateModifier s, int index, {GameState? gameState}) {
    final gs = gameState ?? getIt<GameState>();
    //set all before to done.
    for (int i = 0; i < index; i++) {
      if (gs.currentList[i].turnState != TurnsState.done) {
        gs.currentList[i]._turnState = TurnsState.done;
        removeExpiringConditionsFromListItem(s, gs.currentList[i]);
      }
    }
    //if on index is NOT current then set to current else set to done
    int newIndex = index + 1;
    if (gs.currentList[index].turnState == TurnsState.current) {
      gs.currentList[index]._turnState = TurnsState.done;
      removeExpiringConditionsFromListItem(s, gs.currentList[index]);
      //remove expiring conditions
    } else {
      newIndex = index;
    }

    //get next active item and set to current
    for (; newIndex < gs.currentList.length; newIndex++) {
      ListItemData data = gs.currentList[newIndex];
      if (data is Monster) {
        if (data.isActive && !GameMethods.isInactiveForRule(data.type.name)) {
          if (data.turnState == TurnsState.done) {
            reapplyConditionsFromListItem(s, data);
          }
          data._turnState = TurnsState.current;
          break;
        }
      } else if (data is Character) {
        if (data.characterState.health > 0) {
          if (data.turnState == TurnsState.done) {
            reapplyConditionsFromListItem(s, data);
          }
          data._turnState = TurnsState.current;
          break;
        }
      }
    }
    //set rest to not done
    for (int i = newIndex + 1; i < gs.currentList.length; i++) {
      if (gs.currentList[i].turnState == TurnsState.done) {
        reapplyConditionsFromListItem(s, gs.currentList[i]);
      }
      gs.currentList[i]._turnState = TurnsState.notDone;
    }
  }
}