summaryrefslogtreecommitdiff
path: root/server/lib/core/line_builder/stat_applier.dart
blob: 436e7ef9fd8f3245e1e78e33c7848ed534eeb7c9 (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
import 'package:collection/collection.dart';

import '../enums.dart';
import '../models/monster.dart';
import '../settings.dart';
import '../stat_calculator.dart';
import '../state/game_state.dart';
import 'package:x_haven_server/core/service_locator.dart';

class StatApplier {
  static const int _kLookback2 = 2;
  static const int _kMinFormulaLength = 1;
  static const int _kMinFormulaLengthLong = 2;
  static const int _kTokenEndOffset = 2;
  static const int _kRangeZero = 0;
  static const int _kResultFloor = 0;
  static List<String> applyMonsterStats(
    final String lineInput,
    String sizeToken,
    Monster monster,
    bool forceShowAll, [
    Settings? settings,
  ]) {
    bool showElite = false;
    final noStandees = (settings ?? getIt<Settings>()).noStandees;
    if ((noStandees && monster.isActive) ||
        monster.monsterInstances.firstWhereOrNull(
              (element) => element.type == MonsterType.elite,
            ) !=
            null) {
      showElite = true;
    }
    bool showNormal = false;
    if ((noStandees && monster.isActive) ||
        monster.monsterInstances.firstWhereOrNull(
              (element) => element.type != MonsterType.elite,
            ) !=
            null) {
      showNormal = true;
    }
    if (forceShowAll) {
      showElite = true;
      showNormal = true;
    }
    String line = lineInput;
    List<String> retVal = [];

    //get the data
    final normalTokens = _getStatTokens(monster, false);
    final eliteTokens = _getStatTokens(monster, true);

    RegExp regExpNumbers = RegExp(r'^[\d ()xCL/*+-]+$');
    //first pass fix values only
    String lastToken =
        ""; //turn this into move or attack or whatever, then apply correct monster stat
    bool isInToken = false;
    int tokenStartIndex = 0;
    for (int i = 0; i < line.length; i++) {
      if (line[i] == "%") {
        if (!isInToken) {
          isInToken = true;
          tokenStartIndex = i + 1;
        } else {
          isInToken = false;
          lastToken = line.substring(tokenStartIndex, i);
        }
      }
      if (!isInToken &&
              (line[i] == '+' ||
                  line[i] == '-' ||
                  line[i] == 'C' ||
                  line[i] == 'L') ||
          line[i] ==
              'X' || //hax: X doesn't work in formula, but if a formula starts wit X it should bork. Hopefully there are no wild 'X's anywhere.
          (line[i].contains(regExpNumbers) &&
                  lastToken
                      .isEmpty) //plain numbers cant be calculated for tokens (e.g. attack 1 is not same as attack +1)
              &&
              (i == 0 ||
                  line[i - 1] ==
                      ' ') //supposing there is always a leading whitespace to any formula
              ) {
        String formula = line[i];
        int startIndex = i;
        int endIndex = i;

        for (int j = i + 1; j < lineInput.length; j++) {
          String val = lineInput[j];
          if (val.contains(regExpNumbers) || val == "d") {
            if (val != ' ') formula += val;
            endIndex = j;
          } else {
            i = j; //skip ahead
            if (lineInput[i - 1] == ' ') {
              i = j - 1; //restore any skipped whitespace
              endIndex = endIndex - 1;
            }
            //hack for when a formula is followed by " (..."
            if (i > 0 && lineInput[i - 1] == '(') {
              i = j - 1; //restore any skipped (
              endIndex = endIndex - 1;
              formula = formula.substring(0, formula.length - 1);
              if (i > _kMinFormulaLength && lineInput[i - _kLookback2] == ' ') {
                i = j - 1; //restore any skipped whitespace
                endIndex = endIndex - 1;
              }
            }
            break;
          }
        }
        if (formula.length > _kMinFormulaLength && lastToken.isNotEmpty ||
            formula.length > _kMinFormulaLengthLong) {
          //this disallows a single digit or C,L. single C or L could be part of regular text
          //for a formula to work (outside of plain C or L) it must either be modifying a token value or be 3+ chars long

          if (lastToken.isNotEmpty) {
            retVal = _applyStatForToken(
              formula,
              line,
              sizeToken,
              startIndex,
              endIndex,
              monster,
              showNormal,
              showElite,
              lastToken,
              normalTokens,
              eliteTokens,
            );
            lastToken = "";
            if (retVal.isNotEmpty) {
              return retVal;
            }
          } else {
            int? result = StatCalculator.calculateFormula(formula);
            if (result != null) {
              if (result < 0) {
                //just some nicety. probably never applies
                result = 0;
              }
              line = line.replaceRange(
                startIndex,
                endIndex + 1,
                result.toString(),
              );
            }
          }
        }
      }
    }

    return [line];
  }

  static Map<String, int> _getStatTokens(Monster monster, bool isElite) {
    final map = <String, int>{};
    MonsterStatsModel data;
    final level = monster.type.levels[monster.level];
    final boss = level.boss;
    final elite = level.elite;
    final normal = level.normal;
    if (boss != null) {
      //is boss
      if (isElite) {
        return map;
      }
      data = boss;
    } else {
      final effectiveData = isElite ? elite : normal;
      if (effectiveData == null) return map;
      data = effectiveData;
    }
    for (String item in data.attributes) {
      //remove size modifiers (only used for immobilize since it's so long it overflows.)
      String sizeMod = (item.substring(0, 1));
      if (sizeMod == "^" || sizeMod == "*" && item.length > 1) {
        item = item.substring(1);
      }
      if (item.substring(0, 1) == "%") {
        //expects token to be first in line. is this ok?
        //parse item and then parse number;
        for (int i = 1; i < item.length; i++) {
          if (item[i] == '%') {
            String token = item.substring(1, i);
            int number = 0;
            if (i != item.length - 1) {
              for (int j = i + _kTokenEndOffset; j < item.length; j++) {
                if (item[j] == ' ' || j == item.length - 1) {
                  //need to find end of nr and ignore the rest
                  String nr = item.substring(i + 1, j + 1);
                  int? res = StatCalculator.calculateFormula(nr);
                  if (res != null) {
                    number = res;
                  } else {
                    // ignore: avoid_print
                    print(
                      "failed calculation for formula: $nr"
                      "for token: $token",
                    );
                  }
                  break;
                }
              }
            }

            if (token == "target" && number == 0) {
              //target needs a nr
              continue;
            }
            map[token] = number;
            break; //only one token added per line
          }
        }
      }
    }
    return map;
  }

  static List<String> _applyStatForToken(
    String formula,
    String line,
    String sizeModifier,
    int startIndex,
    int endIndex,
    Monster monster,
    bool showNormal,
    bool showElite,
    String lastToken,
    Map<String, int> normalTokens,
    Map<String, int> eliteTokens,
  ) {
    if (!showElite && !showNormal) {
      return [line];
    }

    List<String> retVal = [];
    List<String> tokens = [];
    List<String> eTokens = [];
    int normalValue = 0;
    int eliteValue = 0;
    bool skipCalculation = false; //in case un-calculable
    final level = monster.type.levels[monster.level];
    MonsterStatsModel? normal = level.boss ?? level.normal;
    MonsterStatsModel? elite = level.elite;
    if (lastToken == "attack") {
      if (normal == null) return [];
      int? calc = StatCalculator.calculateFormula(normal.attack);
      if (calc != null) {
        normalValue = calc;
      } else {
        skipCalculation = true;
      }
      if (elite != null) {
        calc = StatCalculator.calculateFormula(elite.attack);
        if (calc != null) {
          eliteValue = calc;
        }
      }

      RegExp regEx = RegExp(
        r"(?=.*[a-z])",
      ); //not sure why I do this. only letters?
      for (final item in normalTokens.keys) {
        if (regEx.hasMatch(item)) {
          if (item != "shield" &&
              item != "retaliate" &&
              item != "range" &&
              item != "heal" &&
              item != "jump") {
            tokens.add("%$item%");
          }
        }
      }
      for (final item in eliteTokens.keys) {
        if (regEx.hasMatch(item)) {
          if (item != "shield" &&
              item != "retaliate" &&
              item != "range" &&
              item != "heal" &&
              item != "jump") {
            eTokens.add("%$item%");
          }
        }
      }
    } else if (lastToken == "range") {
      if (normal?.range != _kRangeZero) {
        normalValue = normal?.range ?? 0;
        if (elite != null) {
          eliteValue = elite.range;
        }
      }
    } else if (lastToken == "move") {
      normalValue =
          StatCalculator.calculateFormula(normal?.move ?? StatValue.zero) ?? 0;
      if (elite != null) {
        eliteValue = StatCalculator.calculateFormula(elite.move) ?? 0;
      }
    } else if (lastToken == "shield") {
      int? value = normalTokens["shield"];
      int? eValue = eliteTokens["shield"];
      if (elite != null && eValue != null) {
        eliteValue = eValue;
      }
      if (normal != null && value != null) {
        normalValue = value;
      }
    } else if (lastToken == "retaliate") {
      int? value = normalTokens["retaliate"];
      int? eValue = eliteTokens["retaliate"];
      if (elite != null && eValue != null) {
        eliteValue = eValue;
      }
      if (normal != null && value != null) {
        normalValue = value;
      }
    }

    String normalResult = formula;
    if (!skipCalculation) {
      int? res = StatCalculator.calculateFormula("$formula+$normalValue");

      if (res != null && res < 0) {
        res = 0; //needed for blood tumor: has 0 move and a -1 move card
      }
      if (res == null) {
        skipCalculation = true;
      } else {
        normalResult = res.toString();
      }
    }

    String newStartOfLine = line.substring(0, startIndex);
    if (showNormal) {
      newStartOfLine += normalResult;
      if (!skipCalculation) {
        for (final item in tokens) {
          newStartOfLine += "|$item";
          //add nr if applicable
          String key = item.substring(1, item.length - 1);
          int value = normalTokens[key] ?? 0;
          if (value > 0) {
            newStartOfLine += "$value";
          }
        }
      }
    }

    //special case for incalculable and only elites (heed the pigs)
    if (elite != null && skipCalculation && showElite && !showNormal) {
      newStartOfLine += normalResult;
    }

    if (elite != null && !skipCalculation && showElite) {
      if (showNormal) {
        newStartOfLine += "/";
      }
      retVal.add(newStartOfLine);

      int eliteResult =
          StatCalculator.calculateFormula("$formula+$eliteValue") ?? 0;
      if (eliteResult < _kResultFloor) {
        eliteResult = _kResultFloor;
      }
      String eliteString = "!$sizeModifier£$eliteResult";
      for (final item in eTokens) {
        eliteString += "|$item";

        //add nr if applicable
        String key = item.substring(1, item.length - 1);
        int value = eliteTokens[key]!;
        if (value > 0) {
          eliteString += "$value";
        }
      }
      retVal.add(eliteString);
    } else {
      retVal.add(newStartOfLine);
    }
    if (endIndex < line.length) {
      String leftOver =
          "!$sizeModifier${line.substring(endIndex + 1, line.length)}";

      retVal.add(leftOver);
    }
    return retVal;
  }
}