gotchi-battler-game-logic 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1378 @@
1
+ const seedrandom = require('seedrandom')
2
+ const Validator = require('jsonschema').Validator
3
+ const v = new Validator()
4
+ const teamSchema = require('../../schemas/team.json')
5
+
6
+ const { GameError } = require('../../utils/errors')
7
+
8
+ let {
9
+ PASSIVES,
10
+ BUFF_MULT_EFFECTS,
11
+ BUFF_FLAT_EFFECTS,
12
+ DEBUFF_MULT_EFFECTS,
13
+ DEBUFF_FLAT_EFFECTS,
14
+ DEBUFFS,
15
+ BUFFS,
16
+ MULTS
17
+ } = require('./constants')
18
+
19
+ // Get only alive gotchis in a team
20
+ const getAlive = (team, row) => {
21
+ if (row) {
22
+ return team.formation[row].filter(x => x).filter(x => x.health > 0)
23
+ }
24
+
25
+ return [...team.formation.front, ...team.formation.back].filter(x => x).filter(x => x.health > 0)
26
+ }
27
+
28
+ /**
29
+ * Get the formation position of a gotchi
30
+ * @param {Object} team1 An in-game team object
31
+ * @param {Object} team2 An in-game team object
32
+ * @param {Number} gotchiId The id of the gotchi
33
+ * @returns {Object} position The formation position of the gotchi
34
+ * @returns {Number} position.team The team the gotchi is on
35
+ * @returns {String} position.row The row the gotchi is on
36
+ * @returns {Number} position.position The position of the gotchi in the row
37
+ * @returns {null} position null if the gotchi is not found
38
+ **/
39
+ const getFormationPosition = (team1, team2, gotchiId) => {
40
+ const team1FrontIndex = team1.formation.front.findIndex(x => x && x.id === gotchiId)
41
+
42
+ if (team1FrontIndex !== -1) return {
43
+ team: 1,
44
+ row: 'front',
45
+ position: team1FrontIndex,
46
+ name: team1.formation.front[team1FrontIndex].name
47
+ }
48
+
49
+ const team1BackIndex = team1.formation.back.findIndex(x => x && x.id === gotchiId)
50
+
51
+ if (team1BackIndex !== -1) return {
52
+ team: 1,
53
+ row: 'back',
54
+ position: team1BackIndex,
55
+ name: team1.formation.back[team1BackIndex].name
56
+ }
57
+
58
+ const team2FrontIndex = team2.formation.front.findIndex(x => x && x.id === gotchiId)
59
+
60
+ if (team2FrontIndex !== -1) return {
61
+ team: 2,
62
+ row: 'front',
63
+ position: team2FrontIndex,
64
+ name: team2.formation.front[team2FrontIndex].name
65
+ }
66
+
67
+ const team2BackIndex = team2.formation.back.findIndex(x => x && x.id === gotchiId)
68
+
69
+ if (team2BackIndex !== -1) return {
70
+ team: 2,
71
+ row: 'back',
72
+ position: team2BackIndex,
73
+ name: team2.formation.back[team2BackIndex].name
74
+ }
75
+
76
+ return null
77
+ }
78
+
79
+ /**
80
+ * Get the leader gotchi of a team
81
+ * @param {Object} team An in-game team object
82
+ * @returns {Object} gotchi The leader gotchi
83
+ * @returns {Number} leader.id The id of the gotchi
84
+ * @returns {String} leader.special The special object of the gotchi
85
+ * @returns {String} leader.special.class The class of the special
86
+ **/
87
+ const getLeaderGotchi = (team) => {
88
+ const leader = [...team.formation.front, ...team.formation.back].find(x => x && x.id === team.leader)
89
+
90
+ if (!leader) throw new Error('Leader not found')
91
+
92
+ return leader
93
+ }
94
+
95
+ /**
96
+ * Get the next gotchi to act
97
+ * @param {Object} team1 An in-game team object
98
+ * @param {Object} team2 An in-game team object
99
+ * @param {Function} rng The random number generator
100
+ * @returns {Object} position The formation position of the gotchi
101
+ **/
102
+ const getNextToAct = (team1, team2, rng) => {
103
+ const aliveGotchis = [...getAlive(team1), ...getAlive(team2)]
104
+
105
+ aliveGotchis.sort((a, b) => a.actionDelay - b.actionDelay)
106
+
107
+ let toAct = aliveGotchis.filter(gotchi => gotchi.actionDelay === aliveGotchis[0].actionDelay)
108
+
109
+ // If only one gotchi can act then return it
110
+ if (toAct.length === 1) return getFormationPosition(team1, team2, toAct[0].id)
111
+
112
+ // Lowest speeds win tiebreaker
113
+ toAct.sort((a, b) => a.speed - b.speed)
114
+ toAct = toAct.filter(gotchi => gotchi.speed === toAct[0].speed)
115
+
116
+ // If only one gotchi can act then return it
117
+
118
+ if (toAct.length === 1) return getFormationPosition(team1, team2, toAct[0].id)
119
+
120
+ // If still tied then randomly choose
121
+ const randomIndex = Math.floor(rng() * toAct.length)
122
+
123
+ if (!toAct[randomIndex]) throw new Error(`No gotchi found at index ${randomIndex}`)
124
+
125
+ toAct = toAct[randomIndex]
126
+ return getFormationPosition(team1, team2, toAct.id)
127
+ }
128
+
129
+ const getTarget = (defendingTeam, rng) => {
130
+ // Check for taunt gotchis
131
+ const taunt = [...getAlive(defendingTeam, 'front'), ...getAlive(defendingTeam, 'back')].filter(gotchi => gotchi.statuses && gotchi.statuses.includes("taunt"))
132
+
133
+ if (taunt.length) {
134
+ if (taunt.length === 1) return taunt[0]
135
+
136
+ // If multiple taunt gotchis then randomly choose one
137
+ return taunt[Math.floor(rng() * taunt.length)]
138
+ }
139
+
140
+ // Target gotchis in the front row first
141
+ const frontRow = getAlive(defendingTeam, 'front')
142
+
143
+ if (frontRow.length) {
144
+ return frontRow[Math.floor(rng() * frontRow.length)]
145
+ }
146
+
147
+ // If no gotchis in front row then target back row
148
+ const backRow = getAlive(defendingTeam, 'back')
149
+
150
+ if (backRow.length) {
151
+ return backRow[Math.floor(rng() * backRow.length)]
152
+ }
153
+
154
+ throw new Error('No gotchis to target')
155
+ }
156
+
157
+ const applySpeedPenalty = (gotchi, penalty) => {
158
+ const speedPenalty = (gotchi.speed - 100) * penalty
159
+
160
+ return {
161
+ ...gotchi,
162
+ magic: gotchi.magic - speedPenalty,
163
+ physical: gotchi.physical - speedPenalty
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Get the damage of an attack
169
+ * @param {Object} attackingTeam The attacking team
170
+ * @param {Object} defendingTeam The defending team
171
+ * @param {Object} attackingGotchi The gotchi attacking
172
+ * @param {Object} defendingGotchi The gotchi defending
173
+ * @param {Number} multiplier The damage multiplier
174
+ * @param {Boolean} ignoreArmor Whether to ignore armor
175
+ * @param {Number} speedPenalty The speed penalty to apply
176
+ * @returns {Number} damage The damage of the attack
177
+ **/
178
+ const getDamage = (attackingTeam, defendingTeam, attackingGotchi, defendingGotchi, multiplier, ignoreArmor, speedPenalty) => {
179
+
180
+ const attackerWithSpeedPenalty = speedPenalty ? applySpeedPenalty(attackingGotchi, speedPenalty) : attackingGotchi
181
+
182
+ // Apply any status effects
183
+ const modifiedAttackingsGotchi = getModifiedStats(attackerWithSpeedPenalty)
184
+ const modifiedDefendingGotchi = getModifiedStats(defendingGotchi)
185
+
186
+ let attackValue = attackingGotchi.attack === 'magic' ? modifiedAttackingsGotchi.magic : modifiedAttackingsGotchi.physical
187
+
188
+ // If attacking gotchi is in the front row and physical attack then apply front row physical attack bonus
189
+ if (getFormationPosition(attackingTeam, defendingTeam, attackingGotchi.id).row === 'front' && attackingGotchi.attack === 'physical') {
190
+ attackValue = Math.round(attackValue * MULTS.FRONT_ROW_PHY_ATK)
191
+ }
192
+
193
+ let defenseValue = attackingGotchi.attack === 'magic' ? modifiedDefendingGotchi.magic : modifiedDefendingGotchi.physical
194
+
195
+ // If defending gotchi is in the front row and the attack is physical then apply front row physical defence penalty
196
+ if (getFormationPosition(attackingTeam, defendingTeam, defendingGotchi.id).row === 'front' && attackingGotchi.attack === 'physical') {
197
+ defenseValue = Math.round(defenseValue * MULTS.FRONT_ROW_PHY_DEF)
198
+ }
199
+
200
+ // Add armor to defense value
201
+ if (!ignoreArmor) defenseValue += modifiedDefendingGotchi.armor
202
+
203
+ // Calculate damage
204
+ let damage = Math.round((attackValue / defenseValue) * 100)
205
+
206
+ // Apply multiplier
207
+ if (multiplier) damage = Math.round(damage * multiplier)
208
+
209
+ // check for environment effects
210
+ if (defendingGotchi.environmentEffects && defendingGotchi.environmentEffects.length > 0) {
211
+ damage = Math.round(damage * (1 + (defendingGotchi.environmentEffects.length * 0.5)))
212
+ }
213
+
214
+ return damage
215
+ }
216
+
217
+ /**
218
+ * Apply status effects to a gotchi
219
+ * @param {Object} gotchi An in-game gotchi object
220
+ * @returns {Object} gotchi An in-game gotchi object with modified stats
221
+ */
222
+ const getModifiedStats = (gotchi) => {
223
+ const statMods = {}
224
+
225
+ gotchi.statuses.forEach(status => {
226
+ const statusStatMods = {}
227
+
228
+ // apply any modifier from BUFF_MULT_EFFECTS
229
+ if (BUFF_MULT_EFFECTS[status]) {
230
+ Object.keys(BUFF_MULT_EFFECTS[status]).forEach(stat => {
231
+ const modifier = Math.round(gotchi[stat] * BUFF_MULT_EFFECTS[status][stat])
232
+
233
+ statusStatMods[stat] = modifier
234
+ })
235
+ }
236
+
237
+ // apply any modifier from BUFF_FLAT_EFFECTS
238
+ if (BUFF_FLAT_EFFECTS[status]) {
239
+ Object.keys(BUFF_FLAT_EFFECTS[status]).forEach(stat => {
240
+ if (statusStatMods[stat]) {
241
+ // If a mod for this status already exists, only add if the new mod is greater
242
+ if (BUFF_FLAT_EFFECTS[status][stat] > statusStatMods[stat]) statusStatMods[stat] = BUFF_FLAT_EFFECTS[status][stat]
243
+ } else {
244
+ statusStatMods[stat] = BUFF_FLAT_EFFECTS[status][stat]
245
+ }
246
+ })
247
+ }
248
+
249
+ // apply any modifier from DEBUFF_MULT_EFFECTS
250
+ if (DEBUFF_MULT_EFFECTS[status]) {
251
+ Object.keys(DEBUFF_MULT_EFFECTS[status]).forEach(stat => {
252
+ const modifier = Math.round(gotchi[stat] * DEBUFF_MULT_EFFECTS[status][stat])
253
+
254
+ statusStatMods[stat] = -modifier
255
+ })
256
+ }
257
+
258
+ // apply any modifier from DEBUFF_FLAT_EFFECTS
259
+ if (DEBUFF_FLAT_EFFECTS[status]) {
260
+ Object.keys(DEBUFF_FLAT_EFFECTS[status]).forEach(stat => {
261
+ if (statusStatMods[stat]) {
262
+ // If a mod for this status already exists, only add if the new mod is greater
263
+ if (DEBUFF_FLAT_EFFECTS[status][stat] < statusStatMods[stat]) statusStatMods[stat] = DEBUFF_FLAT_EFFECTS[status][stat]
264
+ } else {
265
+ statusStatMods[stat] = -DEBUFF_FLAT_EFFECTS[status][stat]
266
+ }
267
+ })
268
+ }
269
+
270
+ // apply status mods
271
+ Object.keys(statusStatMods).forEach(stat => {
272
+ statMods[stat] = statMods[stat] ? statMods[stat] + statusStatMods[stat] : statusStatMods[stat]
273
+ })
274
+ })
275
+
276
+ const modifiedGotchi = {
277
+ ...gotchi
278
+ }
279
+
280
+ // apply stat mods
281
+ Object.keys(statMods).forEach(stat => {
282
+ if (statMods[stat] < 0) {
283
+ modifiedGotchi[stat] = modifiedGotchi[stat] + statMods[stat] < 0 ? 0 : modifiedGotchi[stat] + statMods[stat]
284
+ } else {
285
+ modifiedGotchi[stat] += statMods[stat]
286
+ }
287
+
288
+ })
289
+
290
+ return modifiedGotchi
291
+ }
292
+
293
+ const calculateActionDelay = (gotchi) => {
294
+ // Calculate action delay and round to 3 decimal places
295
+ return Math.round(((100 / getModifiedStats(gotchi).speed) + Number.EPSILON) * 1000) / 1000
296
+ }
297
+
298
+ const getNewActionDelay = (gotchi) => {
299
+ // Calculate new action delay and round to 3 decimal places
300
+ return Math.round((gotchi.actionDelay + calculateActionDelay(gotchi) + Number.EPSILON) * 1000) / 1000
301
+ }
302
+
303
+ /**
304
+ * Simplify a team object for storage
305
+ * @param {Object} team An in-game team object
306
+ * @returns {Object} simplifiedTeam A simplified team object
307
+ */
308
+ const simplifyTeam = (team) => {
309
+ return {
310
+ name: team.name,
311
+ owner: team.owner,
312
+ leaderId: team.leader,
313
+ rows: [
314
+ {
315
+ slots: team.formation.front.map((x) => {
316
+ return {
317
+ isActive: x ? true : false,
318
+ id: x ? x.id : null
319
+ }
320
+ })
321
+ },
322
+ {
323
+ slots: team.formation.back.map((x) => {
324
+ return {
325
+ isActive: x ? true : false,
326
+ id: x ? x.id : null
327
+ }
328
+ })
329
+ }
330
+ ],
331
+ uiOrder: getUiOrder(team)
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Get the UI order of a team (used for the front end)
337
+ * @param {Object} team An in-game team object
338
+ * @returns {Array} uiOrder An array of gotchi ids in the order they should be displayed
339
+ **/
340
+ const getUiOrder = (team) => {
341
+ const uiOrder = []
342
+
343
+ if (team.formation.front[0]) uiOrder.push(team.formation.front[0].id)
344
+ if (team.formation.back[0]) uiOrder.push(team.formation.back[0].id)
345
+ if (team.formation.front[1]) uiOrder.push(team.formation.front[1].id)
346
+ if (team.formation.back[1]) uiOrder.push(team.formation.back[1].id)
347
+ if (team.formation.front[2]) uiOrder.push(team.formation.front[2].id)
348
+ if (team.formation.back[2]) uiOrder.push(team.formation.back[2].id)
349
+ if (team.formation.front[3]) uiOrder.push(team.formation.front[3].id)
350
+ if (team.formation.back[3]) uiOrder.push(team.formation.back[3].id)
351
+ if (team.formation.front[4]) uiOrder.push(team.formation.front[4].id)
352
+ if (team.formation.back[4]) uiOrder.push(team.formation.back[4].id)
353
+
354
+ return uiOrder
355
+ }
356
+
357
+ /**
358
+ * Add the leader statuses to a team
359
+ * @param {Object} team An in-game team object
360
+ **/
361
+ const addLeaderToTeam = (team) => {
362
+ // Add passive leader abilities
363
+ const teamLeader = getLeaderGotchi(team)
364
+
365
+ team.leaderPassive = teamLeader.special.id
366
+
367
+ // Apply leader passive statuses
368
+ switch (team.leaderPassive) {
369
+ case 1:
370
+ // Sharpen blades - all allies gain 'sharp_blades' status
371
+ getAlive(team).forEach(x => {
372
+ x.statuses.push(PASSIVES[team.leaderPassive - 1])
373
+ })
374
+ break
375
+ case 2:
376
+ // Cloud of Zen - Leader get 'cloud_of_zen' status
377
+ teamLeader.statuses.push(PASSIVES[team.leaderPassive - 1])
378
+ break
379
+ case 3:
380
+ // Frenzy - all allies get 'frenzy' status
381
+ getAlive(team).forEach(x => {
382
+ x.statuses.push(PASSIVES[team.leaderPassive - 1])
383
+ })
384
+ break
385
+ case 4:
386
+ // All allies get 'fortify' status
387
+ getAlive(team).forEach(x => {
388
+ x.statuses.push(PASSIVES[team.leaderPassive - 1])
389
+ })
390
+
391
+ break
392
+ case 5:
393
+ // Spread the fear - all allies get 'spread_the_fear' status
394
+ getAlive(team).forEach(x => {
395
+ x.statuses.push(PASSIVES[team.leaderPassive - 1])
396
+ })
397
+ break
398
+ case 6:
399
+ // Cleansing aura - every healer ally and every tank ally gets 'cleansing_aura' status
400
+ getAlive(team).forEach(x => {
401
+ if (x.special.id === 6 || x.special.id === 4) x.statuses.push(PASSIVES[team.leaderPassive - 1])
402
+ })
403
+ break
404
+ case 7:
405
+ // Arcane thunder - every mage ally gets 'arcane_thunder' status
406
+ getAlive(team).forEach(x => {
407
+ if (x.special.id === 7) x.statuses.push(PASSIVES[team.leaderPassive - 1])
408
+ })
409
+ break
410
+ case 8:
411
+ // Clan momentum - every Troll ally gets 'clan_momentum' status
412
+ getAlive(team).forEach(x => {
413
+ if (x.special.id === 8) x.statuses.push(PASSIVES[team.leaderPassive - 1])
414
+ })
415
+ break
416
+ }
417
+ }
418
+
419
+ const removeLeaderPassivesFromTeam = (team) => {
420
+ let statusesRemoved = []
421
+ if (!team.leaderPassive) return statusesRemoved
422
+
423
+ // Remove leader passive statuses from team
424
+ getAlive(team).forEach(x => {
425
+ // add effects for each status removed
426
+ x.statuses.forEach(status => {
427
+ if (status === PASSIVES[team.leaderPassive - 1]) {
428
+ statusesRemoved.push({
429
+ target: x.id,
430
+ status: status
431
+ })
432
+ }
433
+ })
434
+
435
+ x.statuses = x.statuses.filter(x => x !== PASSIVES[team.leaderPassive - 1])
436
+ })
437
+
438
+ team.leaderPassive = null
439
+
440
+ return statusesRemoved
441
+ }
442
+
443
+ const getExpiredStatuses = (team1, team2) => {
444
+ // If leader is dead, remove leader passive
445
+ let statusesExpired = []
446
+ if (team1.leaderPassive && !getAlive(team1).find(x => x.id === team1.leader)) {
447
+ // Remove leader passive statuses
448
+ statusesExpired = removeLeaderPassivesFromTeam(team1)
449
+ }
450
+ if (team2.leaderPassive && !getAlive(team2).find(x => x.id === team2.leader)) {
451
+ // Remove leader passive statuses
452
+ statusesExpired = removeLeaderPassivesFromTeam(team2)
453
+ }
454
+
455
+ return statusesExpired
456
+ }
457
+
458
+ /**
459
+ * Add a status to a gotchi
460
+ * @param {Object} gotchi An in-game gotchi object
461
+ * @param {String} status The status to add
462
+ * @returns {Boolean} success A boolean to determine if the status was added
463
+ **/
464
+ const addStatusToGotchi = (gotchi, status) => {
465
+ // Check that gotchi doesn't already have max number of statuses
466
+ if (gotchi.statuses.filter(item => item === status).length >= MULTS.MAX_STATUSES) return false
467
+
468
+ gotchi.statuses.push(status)
469
+
470
+ return true
471
+ }
472
+
473
+ const scrambleGotchiIds = (allAliveGotchis, team1, team2) => {
474
+ // check there's no duplicate gotchis
475
+ const gotchiIds = allAliveGotchis.map(x => x.id)
476
+
477
+ if (gotchiIds.length !== new Set(gotchiIds).size) {
478
+ // scramble gotchi ids
479
+ allAliveGotchis.forEach(x => {
480
+ const newId = Math.floor(Math.random() * 10000000)
481
+
482
+ // find gotchi in team1 or team2
483
+ const position = getFormationPosition(team1, team2, x.id)
484
+
485
+ // change gotchi id
486
+ if (position) {
487
+ if (position.team === 1) {
488
+ if (x.id === team1.leader) team1.leader = newId
489
+ team1.formation[position.row][position.position].id = newId
490
+ } else {
491
+ if (x.id === team2.leader) team2.leader = newId
492
+ team2.formation[position.row][position.position].id = newId
493
+ }
494
+ } else {
495
+ throw new Error('Gotchi not found in team1 or team2')
496
+ }
497
+ })
498
+
499
+ // check again
500
+ const newGotchiIds = allAliveGotchis.map(x => x.id)
501
+ if (newGotchiIds.length !== new Set(newGotchiIds).size) {
502
+ // Scramble again
503
+ scrambleGotchiIds(allAliveGotchis, team1, team2)
504
+ }
505
+ }
506
+ }
507
+
508
+ /**
509
+ * Prepare teams for battle
510
+ * @param {Array} allAliveGotchis An array of all alive gotchis
511
+ * @param {Object} team1 An in-game team object
512
+ * @param {Object} team2 An in-game team object
513
+ **/
514
+ const prepareTeams = (allAliveGotchis, team1, team2) => {
515
+ // check there's no duplicate gotchis
516
+ scrambleGotchiIds(allAliveGotchis, team1, team2);
517
+
518
+ allAliveGotchis.forEach(x => {
519
+ // Add statuses property to all gotchis
520
+ x.statuses = []
521
+
522
+ // Calculate initial action delay for all gotchis
523
+ x.actionDelay = calculateActionDelay(x)
524
+
525
+ // Calculate attack type
526
+ x.attack = x.magic > x.physical ? 'magic' : 'physical'
527
+
528
+ // Add original stats to all gotchis
529
+ // Do a deep copy of the gotchi object to avoid modifying the original object
530
+ x.originalStats = JSON.parse(JSON.stringify(x))
531
+
532
+ // Add environmentEffects to all gotchis
533
+ x.environmentEffects = []
534
+ })
535
+
536
+ // Add leader passive to team
537
+ addLeaderToTeam(team1)
538
+ addLeaderToTeam(team2);
539
+ }
540
+
541
+ /**
542
+ * Get log gotchi object for battle logs
543
+ * @param {Array} allAliveGotchis An array of all alive gotchis
544
+ * @returns {Array} logGotchis An array of gotchi objects for logs
545
+ */
546
+ const getLogGotchis = (allAliveGotchis) => {
547
+ const logGotchis = JSON.parse(JSON.stringify(allAliveGotchis))
548
+
549
+ logGotchis.forEach(x => {
550
+ // Change gotchi.special.class to gotchi.special.gotchiClass to avoid conflicts with class keyword
551
+ x.special.gotchiClass = x.special.class
552
+
553
+ // Remove unnecessary properties to reduce log size
554
+ delete x.special.class
555
+ delete x.snapshotBlock
556
+ delete x.onchainId
557
+ delete x.brs
558
+ delete x.nrg
559
+ delete x.agg
560
+ delete x.spk
561
+ delete x.brn
562
+ delete x.eyc
563
+ delete x.eys
564
+ delete x.kinship
565
+ delete x.xp
566
+ delete x.actionDelay
567
+ delete x.attack
568
+ delete x.originalStats
569
+ delete x.environmentEffects
570
+ })
571
+
572
+ return logGotchis
573
+ }
574
+
575
+ /**
576
+ * Run a battle between two teams
577
+ * @param {Object} team1 An in-game team object
578
+ * @param {Object} team2 An in-game team object
579
+ * @param {String} seed A seed for the random number generator
580
+ * @param {Boolean} debug A boolean to determine if the logs should include debug information
581
+ * @returns {Object} logs The battle logs
582
+ */
583
+ const gameLoop = (team1, team2, seed, debug) => {
584
+ if (!team1) throw new Error("Team 1 not found")
585
+ if (!team2) throw new Error("Team 2 not found")
586
+ if (!seed) throw new Error("Seed not found")
587
+
588
+ // Validate team objects
589
+ const team1Validation = v.validate(team1, teamSchema)
590
+ if (team1Validation.errors.length) {
591
+ console.error('Team 1 validation failed: ', JSON.stringify(team1Validation.errors))
592
+ throw new Error(`Team 1 validation failed`)
593
+ }
594
+ const team2Validation = v.validate(team2, teamSchema)
595
+ if (team2Validation.errors.length) {
596
+ console.error('Team 2 validation failed: ', team2Validation.errors)
597
+ throw new Error(`Team 2 validation failed`)
598
+ }
599
+
600
+ const rng = seedrandom(seed)
601
+
602
+ const allAliveGotchis = [...getAlive(team1), ...getAlive(team2)]
603
+
604
+ prepareTeams(allAliveGotchis, team1, team2)
605
+
606
+ const logs = {
607
+ gotchis: getLogGotchis(allAliveGotchis),
608
+ layout: {
609
+ teams: [
610
+ simplifyTeam(team1),
611
+ simplifyTeam(team2)
612
+ ]
613
+ },
614
+ turns: []
615
+ };
616
+
617
+ // Used for turn by turn health and status summaries
618
+ // Deleted if not in development or no errors
619
+ logs.debug = []
620
+
621
+ let turnCounter = 0
622
+ let draw = false
623
+
624
+ try {
625
+ while (getAlive(team1).length && getAlive(team2).length) {
626
+ // Check if turnCounter is ready for environment effects (99,149,199, etc)
627
+ let isEnvironmentTurn = [99, 149, 199, 249, 299].includes(turnCounter)
628
+ if (isEnvironmentTurn) {
629
+ allAliveGotchis.forEach(x => {
630
+ x.environmentEffects.push('damage_up')
631
+ })
632
+ }
633
+
634
+ const turnLogs = executeTurn(team1, team2, rng)
635
+
636
+ // Check if turnCounter is ready for environment effects (99,149,199, etc)
637
+ if (isEnvironmentTurn) turnLogs.environmentEffects = ['damage_up']
638
+
639
+ if (MULTS.EXPIRE_LEADERSKILL) {
640
+ turnLogs.statusesExpired = [...turnLogs.statusesExpired, ...getExpiredStatuses(team1, team2)]
641
+ }
642
+
643
+ logs.turns.push({index: turnCounter, ...turnLogs})
644
+
645
+ if (debug) {
646
+ logs.debug.push({
647
+ turn: turnCounter,
648
+ user: logs.turns[logs.turns.length - 1].action.user,
649
+ move: logs.turns[logs.turns.length - 1].action.name,
650
+ team1: getAlive(team1).map((x) => {
651
+ return `Id: ${x.id}, Name: ${x.name}, Health: ${x.health}, Statuses: ${x.statuses}`
652
+ }),
653
+ team2: getAlive(team2).map((x) => {
654
+ return `Id: ${x.id}, Name: ${x.name}, Health: ${x.health}, Statuses: ${x.statuses}`
655
+ })
656
+ })
657
+ }
658
+
659
+ turnCounter++
660
+ }
661
+ } catch (e) {
662
+ console.error(e)
663
+ throw new GameError('Game loop failed', logs)
664
+ }
665
+
666
+ if (draw) {
667
+ logs.result = {
668
+ winner: 0,
669
+ loser: 0,
670
+ winningTeam: [],
671
+ numOfTurns: logs.turns.length
672
+ }
673
+ } else {
674
+ logs.result = {
675
+ winner: getAlive(team1).length ? 1 : 2,
676
+ loser: getAlive(team1).length ? 2 : 1,
677
+ winningTeam: getAlive(team1).length ? getAlive(team1) : getAlive(team2),
678
+ numOfTurns: logs.turns.length
679
+ }
680
+
681
+ // trim winning team objects
682
+ logs.result.winningTeam = logs.result.winningTeam.map((gotchi) => {
683
+ return {
684
+ id: gotchi.id,
685
+ name: gotchi.name,
686
+ brs: gotchi.brs,
687
+ health: gotchi.health
688
+ }
689
+ })
690
+ }
691
+
692
+ if (!debug) delete logs.debug
693
+
694
+ return logs
695
+ }
696
+
697
+ /**
698
+ * Attack one or more gotchis. This mutates the defending gotchis health
699
+ * @param {Object} attackingGotchi The attacking gotchi object
700
+ * @param {Array} attackingTeam A team object for the attacking team
701
+ * @param {Array} defendingTeam A team object for the defending team
702
+ * @param {Array} defendingTargets An array of gotchis to attack
703
+ * @param {Function} rng The random number generator
704
+ * @param {Object} options An object of options
705
+ * @param {Boolean} options.ignoreArmor Ignore the defending gotchi's defense
706
+ * @param {Boolean} options.multiplier A multiplier to apply to the damage
707
+ * @param {Boolean} options.statuses An array of status effects to apply
708
+ * @param {Boolean} options.cannotBeEvaded A boolean to determine if the attack can be evaded
709
+ * @param {Boolean} options.cannotBeResisted A boolean to determine if the attack can be resisted
710
+ * @param {Boolean} options.cannotBeCountered A boolean to determine if the attack can be countered
711
+ * @param {Boolean} options.noPassiveStatuses A boolean to determine if passive statuses should be inflicted
712
+ * @param {Number} options.critMultiplier Override the crit multiplier
713
+ * @returns {Array} effects An array of effects to apply
714
+ */
715
+ const attack = (attackingGotchi, attackingTeam, defendingTeam, defendingTargets, rng, options) => {
716
+ if (!options) options = {}
717
+ if (!options.ignoreArmor) options.ignoreArmor = false
718
+ if (!options.multiplier) options.multiplier = 1
719
+ if (!options.statuses) options.statuses = []
720
+ if (!options.cannotBeEvaded) options.cannotBeEvaded = false
721
+ if (!options.critCannotBeEvaded) options.critCannotBeEvaded = false
722
+ if (!options.cannotBeResisted) options.cannotBeResisted = false
723
+ if (!options.cannotBeCountered) options.cannotBeCountered = false
724
+ if (!options.noPassiveStatuses) options.noPassiveStatuses = false
725
+ if (!options.speedPenalty) options.speedPenalty = 0
726
+ if (!options.noResistSpeedPenalty) options.noResistSpeedPenalty = false
727
+ if (!options.critMultiplier) options.critMultiplier = null
728
+
729
+ // If passive statuses are allowed then add leaderPassive status effects to attackingGotchi
730
+ if (!options.noPassiveStatuses) {
731
+ // If attacking gotchi has 'sharp_blades' status, add 'bleed' to statuses
732
+ if (attackingGotchi.statuses.includes('sharp_blades')) {
733
+ if (rng() < MULTS.SHARP_BLADES_BLEED_CHANCE) options.statuses.push('bleed')
734
+ }
735
+
736
+ // If attacking gotchi has 'spread_the_fear' status, add 'fear' to statuses
737
+ if (attackingGotchi.statuses.includes('spread_the_fear')) {
738
+ // Reduce the chance to spread the fear if attacking gotchi has speed over 100
739
+ const spreadTheFearChance = attackingGotchi.speed > 100 ? MULTS.SPREAD_THE_FEAR_CHANCE - MULTS.SPREAD_THE_FEAR_SPEED_PENALTY : MULTS.SPREAD_THE_FEAR_CHANCE
740
+ if (rng() < spreadTheFearChance) options.statuses.push('fear')
741
+ }
742
+ }
743
+
744
+ const effects = []
745
+
746
+ defendingTargets.forEach((defendingGotchi) => {
747
+ // Check attacking gotchi hasn't been killed by a counter
748
+ if (attackingGotchi.health <= 0) return
749
+
750
+ const modifiedAttackingGotchi = getModifiedStats(attackingGotchi)
751
+ const modifiedDefendingGotchi = getModifiedStats(defendingGotchi)
752
+
753
+ // Check for crit
754
+ const isCrit = rng() < modifiedAttackingGotchi.crit / 100
755
+ if (isCrit) {
756
+ if (options.critMultiplier) {
757
+ options.multiplier *= options.critMultiplier
758
+ } else {
759
+ // Apply different crit multipliers for -nrg and +nrg gotchis
760
+ if (attackingGotchi.speed <= 100) {
761
+ options.multiplier *= MULTS.CRIT_MULTIPLIER_SLOW
762
+ } else {
763
+ options.multiplier *= MULTS.CRIT_MULTIPLIER_FAST
764
+ }
765
+ }
766
+ }
767
+
768
+ let canEvade = true
769
+ if (options.cannotBeEvaded) canEvade = false
770
+ if (isCrit && options.critCannotBeEvaded) canEvade = false
771
+
772
+ const damage = getDamage(attackingTeam, defendingTeam, attackingGotchi, defendingGotchi, options.multiplier, options.ignoreArmor, options.speedPenalty)
773
+
774
+ let effect = {
775
+ target: defendingGotchi.id,
776
+ }
777
+
778
+ // Check for miss
779
+ if (rng() > modifiedAttackingGotchi.accuracy / 100) {
780
+ effect.outcome = 'miss'
781
+ effects.push(effect)
782
+ } else if (canEvade && rng() < modifiedDefendingGotchi.evade / 100){
783
+ effect.outcome = 'evade'
784
+ effects.push(effect)
785
+ } else {
786
+ if (!options.cannotBeResisted) {
787
+ // Check for status effect from the move
788
+ options.statuses.forEach((status) => {
789
+ if (rng() > modifiedDefendingGotchi.resist / 100) {
790
+ // Attempt to add status to defending gotchi
791
+ if (addStatusToGotchi(defendingGotchi, status)) {
792
+ // If status added, add to effect
793
+ if (!effect.statuses) {
794
+ effect.statuses = [status]
795
+ } else {
796
+ effect.statuses.push(status)
797
+ }
798
+ }
799
+ }
800
+ })
801
+ }
802
+
803
+ // Handle damage
804
+ defendingGotchi.health -= damage
805
+ effect.damage = damage
806
+ effect.outcome = isCrit ? 'critical' : 'success'
807
+ effects.push(effect)
808
+
809
+ // Check for counter attack
810
+ if (
811
+ defendingGotchi.statuses.includes('taunt')
812
+ && defendingGotchi.health > 0
813
+ && !options.cannotBeCountered) {
814
+
815
+ // Chance to counter based on speed over 100
816
+ let chanceToCounter = defendingGotchi.speed - 100
817
+
818
+ if (chanceToCounter < MULTS.COUNTER_CHANCE_MIN) chanceToCounter = MULTS.COUNTER_CHANCE_MIN
819
+
820
+ // Add a higher chance to counter if gotchi has 'fortify' status
821
+ if (defendingGotchi.statuses.includes('fortify')) {
822
+ chanceToCounter += MULTS.FORTIFY_COUNTER_CHANCE
823
+
824
+ }
825
+
826
+ // Add a higher chance to counter if gotchi is fast
827
+ if (defendingGotchi.speed > 100) {
828
+ chanceToCounter += MULTS.COUNTER_SPEED_BONUS
829
+
830
+
831
+ }
832
+
833
+ if (rng() < chanceToCounter / 100) {
834
+ const counterDamage = getDamage(defendingTeam, attackingTeam, defendingGotchi, attackingGotchi, MULTS.COUNTER_DAMAGE, false, 0)
835
+
836
+ attackingGotchi.health -= counterDamage
837
+
838
+ effects.push({
839
+ target: attackingGotchi.id,
840
+ source: defendingGotchi.id,
841
+ damage: counterDamage,
842
+ outcome: 'counter'
843
+ })
844
+ }
845
+ }
846
+ }
847
+ })
848
+
849
+ return effects
850
+ }
851
+
852
+ // Deal with start of turn status effects
853
+ const handleStatusEffects = (attackingGotchi, attackingTeam, defendingTeam, rng) => {
854
+ const statusEffects = []
855
+ const passiveEffects = []
856
+
857
+ const modifiedAttackingGotchi = getModifiedStats(attackingGotchi)
858
+
859
+ // Check for cleansing_aura
860
+ // if (attackingGotchi.statuses.includes('cleansing_aura')) {
861
+ // // Remove all debuffs from all allies
862
+ // const aliveAllies = getAlive(attackingTeam)
863
+ // aliveAllies.forEach((ally) => {
864
+ // ally.statuses.forEach((status) => {
865
+ // if (DEBUFFS.includes(status)) {
866
+ // passiveEffects.push({
867
+ // source: attackingGotchi.id,
868
+ // target: ally.id,
869
+ // status,
870
+ // damage: 0,
871
+ // remove: true
872
+ // })
873
+ // }
874
+ // })
875
+
876
+ // // Remove status effects
877
+ // ally.statuses = ally.statuses.filter((status) => !DEBUFFS.includes(status))
878
+ // })
879
+ // }
880
+
881
+ // Check for global status effects
882
+ const allAliveGotchis = [...getAlive(attackingTeam), ...getAlive(defendingTeam)]
883
+
884
+ allAliveGotchis.forEach((gotchi) => {
885
+ if (gotchi.statuses && gotchi.statuses.length) {
886
+ gotchi.statuses.forEach((status) => {
887
+ // Handle cleansing_aura (health regen)
888
+ if (status === 'cleansing_aura') {
889
+ let amountToHeal
890
+
891
+ // Check if healer
892
+ if (gotchi.special.id === 6) {
893
+ amountToHeal = Math.round(gotchi.resist * MULTS.CLEANSING_AURA_REGEN)
894
+ } else {
895
+ amountToHeal = MULTS.CLEANSING_AURA_NON_HEALER_REGEN
896
+ }
897
+
898
+ // Don't allow amountToHeal to be more than the difference between current health and max health
899
+ if (amountToHeal > gotchi.originalStats.health - gotchi.health) {
900
+ amountToHeal = gotchi.originalStats.health - gotchi.health
901
+ }
902
+
903
+ // if amountToHeal > 0, add status effect
904
+ if (amountToHeal) {
905
+ // Add status effect
906
+ statusEffects.push({
907
+ target: gotchi.id,
908
+ status,
909
+ damage: -Math.abs(amountToHeal),
910
+ remove: false
911
+ })
912
+
913
+ gotchi.health += amountToHeal
914
+ }
915
+ }
916
+
917
+ /*
918
+ * Handle damage effect at the bottom of the loop
919
+ */
920
+
921
+ // Handle bleed
922
+ if (status === 'bleed') {
923
+ let damage = MULTS.BLEED_DAMAGE
924
+
925
+ gotchi.health -= damage
926
+ if (gotchi.health <= 0) gotchi.health = 0
927
+
928
+ // Add status effect
929
+ statusEffects.push({
930
+ target: gotchi.id,
931
+ status,
932
+ damage,
933
+ remove: false
934
+ })
935
+ }
936
+ })
937
+ }
938
+ })
939
+
940
+ let skipTurn = null
941
+
942
+ // Check if gotchi is dead
943
+ if (attackingGotchi.health <= 0) {
944
+ return {
945
+ statusEffects,
946
+ passiveEffects,
947
+ skipTurn: 'ATTACKER_DEAD'
948
+ }
949
+ }
950
+
951
+ // Check if a whole team is dead
952
+ if (getAlive(attackingTeam).length === 0 || getAlive(defendingTeam).length === 0) {
953
+ return {
954
+ statusEffects,
955
+ passiveEffects,
956
+ skipTurn: 'TEAM_DEAD'
957
+ }
958
+ }
959
+
960
+ // Check for turn skipping statuses
961
+ for (let i = 0; i < attackingGotchi.statuses.length; i++) {
962
+ const status = attackingGotchi.statuses[i]
963
+ // Fear - skip turn
964
+ if (status === 'fear') {
965
+ // Skip turn
966
+ statusEffects.push({
967
+ target: attackingGotchi.id,
968
+ status,
969
+ damage: 0,
970
+ remove: true
971
+ })
972
+
973
+ skipTurn = 'FEAR'
974
+
975
+ // Remove fear first instance of fear
976
+ attackingGotchi.statuses.splice(i, 1)
977
+
978
+ break
979
+ }
980
+
981
+ // Stun
982
+ if (status === 'stun') {
983
+ // Skip turn
984
+ statusEffects.push({
985
+ target: attackingGotchi.id,
986
+ status,
987
+ damage: 0,
988
+ remove: true
989
+ })
990
+
991
+ skipTurn = 'STUN'
992
+
993
+ // Remove first instance of stun
994
+ attackingGotchi.statuses.splice(i, 1)
995
+
996
+ break
997
+ }
998
+ }
999
+
1000
+ return {
1001
+ statusEffects,
1002
+ passiveEffects,
1003
+ skipTurn
1004
+ }
1005
+ }
1006
+
1007
+ const executeTurn = (team1, team2, rng) => {
1008
+ const nextToAct = getNextToAct(team1, team2, rng)
1009
+
1010
+ const attackingTeam = nextToAct.team === 1 ? team1 : team2
1011
+ const defendingTeam = nextToAct.team === 1 ? team2 : team1
1012
+
1013
+ const attackingGotchi = attackingTeam.formation[nextToAct.row][nextToAct.position]
1014
+
1015
+ let { statusEffects, passiveEffects, skipTurn } = handleStatusEffects(attackingGotchi, attackingTeam, defendingTeam, rng)
1016
+ let statusesExpired = []
1017
+
1018
+ let effects = []
1019
+ if (skipTurn) {
1020
+ // Increase actionDelay
1021
+ attackingGotchi.actionDelay = getNewActionDelay(attackingGotchi)
1022
+
1023
+ return {
1024
+ skipTurn,
1025
+ action: {
1026
+ user: attackingGotchi.id,
1027
+ name: 'auto',
1028
+ effects
1029
+ },
1030
+ passiveEffects,
1031
+ statusEffects,
1032
+ statusesExpired
1033
+ }
1034
+ }
1035
+
1036
+ let specialDone = false
1037
+ // Check if special attack is ready
1038
+ if (attackingGotchi.special.cooldown === 0) {
1039
+ // TODO: Check if special attack should be used
1040
+
1041
+ // Execute special attack
1042
+ const specialResults = specialAttack(attackingGotchi, attackingTeam, defendingTeam, rng)
1043
+
1044
+ effects = specialResults.effects
1045
+ statusesExpired = specialResults.statusesExpired
1046
+
1047
+ // Reset cooldown
1048
+ attackingGotchi.special.cooldown = 2
1049
+
1050
+ if (specialResults.specialNotDone) {
1051
+ // Do nothing which will lead to an auto attack
1052
+ } else {
1053
+ specialDone = true
1054
+ }
1055
+
1056
+ } else {
1057
+ // Decrease cooldown
1058
+ attackingGotchi.special.cooldown--
1059
+ }
1060
+
1061
+ if (!specialDone) {
1062
+ // Do an auto attack
1063
+ const target = getTarget(defendingTeam, rng)
1064
+
1065
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, [target], rng)
1066
+ }
1067
+
1068
+ // Increase actionDelay
1069
+ attackingGotchi.actionDelay = getNewActionDelay(attackingGotchi)
1070
+
1071
+ return {
1072
+ skipTurn,
1073
+ action: {
1074
+ user: attackingGotchi.id,
1075
+ name: specialDone ? attackingGotchi.special.name : 'auto',
1076
+ effects
1077
+ },
1078
+ passiveEffects,
1079
+ statusEffects,
1080
+ statusesExpired
1081
+ }
1082
+ }
1083
+
1084
+ /**
1085
+ * Execute a special attack
1086
+ * @param {Object} attackingGotchi The attacking gotchi object
1087
+ * @param {Array} attackingTeam An array of gotchis to attack
1088
+ * @param {Array} defendingTeam An array of gotchis to attack
1089
+ * @param {Function} rng The random number generator
1090
+ * @returns {Array} effects An array of effects to apply
1091
+ **/
1092
+ const specialAttack = (attackingGotchi, attackingTeam, defendingTeam, rng) => {
1093
+ const specialId = attackingGotchi.special.id
1094
+ let effects = []
1095
+ let statusesExpired = []
1096
+ let specialNotDone = false
1097
+
1098
+ const modifiedAttackingGotchi = getModifiedStats(attackingGotchi)
1099
+
1100
+ switch (specialId) {
1101
+ case 1:
1102
+ // Spectral Strike - ignore armor and appply bleed status
1103
+ // get single target
1104
+ const ssTarget = getTarget(defendingTeam, rng)
1105
+
1106
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, [ssTarget], rng, {
1107
+ multiplier: MULTS.SPECTRAL_STRIKE_DAMAGE,
1108
+ ignoreArmor: true,
1109
+ statuses: ['bleed'],
1110
+ cannotBeCountered: true,
1111
+ cannotBeEvaded: true,
1112
+ noPassiveStatuses: true,
1113
+ noResistSpeedPenalty: true
1114
+ })
1115
+ break
1116
+ case 2:
1117
+ // Meditate - Boost own speed, magic, physical by 30%
1118
+ // If gotchi already has 2 power_up statuses, do nothing
1119
+ if (!addStatusToGotchi(attackingGotchi, 'power_up_2')) {
1120
+ specialNotDone = true
1121
+ break
1122
+ }
1123
+
1124
+ effects = [
1125
+ {
1126
+ target: attackingGotchi.id,
1127
+ outcome: 'success',
1128
+ statuses: ['power_up_2']
1129
+ }
1130
+ ]
1131
+
1132
+ // Check for leaderPassive 'Cloud of Zen'
1133
+ if (attackingGotchi.statuses.includes(PASSIVES[specialId - 1])) {
1134
+ // Increase allies speed, magic and physical by 15% of the original value
1135
+
1136
+ const cloudOfZenGotchis = getAlive(attackingTeam)
1137
+
1138
+ cloudOfZenGotchis.forEach((gotchi) => {
1139
+ if (addStatusToGotchi(gotchi, 'power_up_1')) {
1140
+ effects.push({
1141
+ target: gotchi.id,
1142
+ outcome: 'success',
1143
+ statuses: ['power_up_1']
1144
+ })
1145
+ }
1146
+ })
1147
+ }
1148
+
1149
+ break
1150
+ case 3:
1151
+ // Cleave - attack all enemies in a row (that have the most gotchis) for 75% damage
1152
+ // Find row with most gotchis
1153
+ const cleaveRow = getAlive(defendingTeam, 'front').length > getAlive(defendingTeam, 'back').length ? 'front' : 'back'
1154
+
1155
+ // Attack all gotchis in that row for 75% damage
1156
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, getAlive(defendingTeam, cleaveRow), rng, {
1157
+ multiplier: MULTS.CLEAVE_DAMAGE,
1158
+ cannotBeCountered: true,
1159
+ noPassiveStatuses: true
1160
+ })
1161
+ break
1162
+ case 4:
1163
+ // Taunt - add taunt status to self
1164
+
1165
+ // Check if gotchi already has taunt status
1166
+ if (attackingGotchi.statuses.includes('taunt')) {
1167
+ specialNotDone = true
1168
+ break
1169
+ }
1170
+
1171
+ if (!addStatusToGotchi(attackingGotchi, 'taunt')) {
1172
+ specialNotDone = true
1173
+ break
1174
+ }
1175
+
1176
+ effects = [
1177
+ {
1178
+ target: attackingGotchi.id,
1179
+ outcome: 'success',
1180
+ statuses: ['taunt']
1181
+ }
1182
+ ]
1183
+ break
1184
+ case 5:
1185
+ // Curse - attack random enemy for 50% damage, apply fear status and remove all buffs
1186
+
1187
+ const curseTarget = getTarget(defendingTeam, rng)
1188
+
1189
+ const curseTargetStatuses = ['fear']
1190
+
1191
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, [curseTarget], rng, {
1192
+ multiplier: MULTS.CURSE_DAMAGE,
1193
+ statuses: curseTargetStatuses,
1194
+ cannotBeCountered: true,
1195
+ noPassiveStatuses: true,
1196
+ speedPenalty: MULTS.CURSE_SPEED_PENALTY,
1197
+ noResistSpeedPenalty: true
1198
+ })
1199
+
1200
+ const removeRandomBuff = (target) => {
1201
+ const modifiedTarget = getModifiedStats(target)
1202
+
1203
+ if (rng() > modifiedTarget.resist / 100) {
1204
+ const buffsToRemove = target.statuses.filter((status) => BUFFS.includes(status))
1205
+
1206
+ if (buffsToRemove.length) {
1207
+ const randomBuff = buffsToRemove[Math.floor(rng() * buffsToRemove.length)]
1208
+ statusesExpired.push({
1209
+ target: target.id,
1210
+ status: randomBuff
1211
+ })
1212
+
1213
+ // Remove first instance of randomBuff (there may be multiple)
1214
+ const index = target.statuses.indexOf(randomBuff)
1215
+ target.statuses.splice(index, 1)
1216
+ }
1217
+ }
1218
+ }
1219
+
1220
+ if (effects[0] && effects[0].outcome === 'success') {
1221
+ // 1 chance to remove a random buff
1222
+ removeRandomBuff(curseTarget)
1223
+
1224
+ } else if (effects[0] && effects[0].outcome === 'critical') {
1225
+ // 2 chances to remove a random buff
1226
+ removeRandomBuff(curseTarget)
1227
+ removeRandomBuff(curseTarget)
1228
+ }
1229
+
1230
+ break
1231
+ case 6:
1232
+ // Blessing - Heal all non-healer allies and remove all debuffs
1233
+
1234
+ // Get all alive non-healer allies on the attacking team
1235
+ const gotchisToHeal = getAlive(attackingTeam).filter(x => x.special.id !== 6)
1236
+
1237
+ // Heal all allies for multiple of healers resistance
1238
+ gotchisToHeal.forEach((gotchi) => {
1239
+ let amountToHeal
1240
+
1241
+ // If gotchi has 'cleansing_aura' status, increase heal amount
1242
+ if (attackingGotchi.statuses.includes('cleansing_aura')) {
1243
+ amountToHeal = Math.round(modifiedAttackingGotchi.resist * MULTS.CLEANSING_AURA_HEAL)
1244
+ } else {
1245
+ amountToHeal = Math.round(modifiedAttackingGotchi.resist * MULTS.BLESSING_HEAL)
1246
+ }
1247
+
1248
+ // Check for crit
1249
+ const isCrit = rng() < modifiedAttackingGotchi.crit / 100
1250
+ if (isCrit) {
1251
+ amountToHeal = Math.round(amountToHeal * MULTS.BLESSING_HEAL_CRIT_MULTIPLIER)
1252
+ }
1253
+
1254
+ // Apply speed penalty
1255
+ const speedPenalty = (modifiedAttackingGotchi.speed - 100) * MULTS.BLESSING_HEAL_SPEED_PENALTY
1256
+ if (speedPenalty > 0) amountToHeal -= speedPenalty
1257
+
1258
+ // Don't allow amountToHeal to be more than the difference between current health and max health
1259
+ if (amountToHeal > gotchi.originalStats.health - gotchi.health) {
1260
+ amountToHeal = gotchi.originalStats.health - gotchi.health
1261
+ }
1262
+
1263
+ gotchi.health += amountToHeal
1264
+
1265
+ if (amountToHeal) {
1266
+ effects.push({
1267
+ target: gotchi.id,
1268
+ outcome: isCrit ? 'critical' : 'success',
1269
+ damage: -Math.abs(amountToHeal)
1270
+ })
1271
+ }
1272
+
1273
+ // Remove all debuffs
1274
+ // Add removed debuffs to statusesExpired
1275
+ gotchi.statuses.forEach((status) => {
1276
+ if (DEBUFFS.includes(status)) {
1277
+ statusesExpired.push({
1278
+ target: gotchi.id,
1279
+ status
1280
+ })
1281
+ }
1282
+ })
1283
+
1284
+ // Remove all debuffs from gotchi
1285
+ gotchi.statuses = gotchi.statuses.filter((status) => !DEBUFFS.includes(status))
1286
+ })
1287
+
1288
+ // If no allies have been healed and no debuffs removed, then special attack not done
1289
+ if (!effects.length && !statusesExpired.length) {
1290
+ specialNotDone = true
1291
+ break
1292
+ }
1293
+
1294
+ break
1295
+ case 7:
1296
+ // Thunder - Attack all enemies for 50% damage and apply stun status
1297
+
1298
+ const thunderTargets = getAlive(defendingTeam)
1299
+
1300
+ // Check if leader passive is 'arcane_thunder' then apply stun status
1301
+ if (attackingGotchi.statuses.includes(PASSIVES[specialId - 1])) {
1302
+ let stunStatuses = []
1303
+ if (rng() < MULTS.CHANNEL_THE_COVEN_DAMAGE_CHANCE) stunStatuses.push('stun')
1304
+
1305
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, thunderTargets, rng, {
1306
+ multiplier: modifiedAttackingGotchi.speed > 100 ? MULTS.CHANNEL_THE_COVEN_DAMAGE_FAST : MULTS.CHANNEL_THE_COVEN_DAMAGE_SLOW,
1307
+ statuses: stunStatuses,
1308
+ cannotBeCountered: true,
1309
+ noPassiveStatuses: true,
1310
+ critMultiplier: MULTS.CHANNEL_THE_COVEN_CRIT_MULTIPLIER
1311
+ })
1312
+ } else {
1313
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, thunderTargets, rng, {
1314
+ multiplier: modifiedAttackingGotchi.speed > 100 ? MULTS.THUNDER_DAMAGE_FAST : MULTS.THUNDER_DAMAGE_SLOW,
1315
+ cannotBeCountered: true,
1316
+ noPassiveStatuses: true
1317
+ })
1318
+ }
1319
+
1320
+ break
1321
+ case 8:
1322
+ // Devestating Smash - Attack random enemy for 200% damage
1323
+
1324
+ const smashTarget = getTarget(defendingTeam, rng)
1325
+
1326
+ effects = attack(attackingGotchi, attackingTeam, defendingTeam, [smashTarget], rng, {
1327
+ multiplier: MULTS.DEVESTATING_SMASH_DAMAGE,
1328
+ cannotBeCountered: true,
1329
+ noPassiveStatuses: true
1330
+ })
1331
+
1332
+ // If crit then attack again
1333
+ if (effects[0].outcome === 'critical') {
1334
+ const aliveEnemies = getAlive(defendingTeam)
1335
+
1336
+ if (aliveEnemies.length) {
1337
+ const target = getTarget(defendingTeam, rng)
1338
+
1339
+ effects.push(...attack(attackingGotchi, attackingTeam, defendingTeam, [target], rng, {
1340
+ multiplier: MULTS.DEVESTATING_SMASH_DAMAGE,
1341
+ cannotBeCountered: true,
1342
+ noPassiveStatuses: true
1343
+ }))
1344
+ }
1345
+ }
1346
+
1347
+ // If leader passive is 'Clan momentum', attack again
1348
+ if (attackingGotchi.statuses.includes(PASSIVES[specialId - 1])) {
1349
+ // Check if any enemies are alive
1350
+ const aliveEnemies = getAlive(defendingTeam)
1351
+
1352
+ if (aliveEnemies.length) {
1353
+ // Do an extra devestating smash
1354
+ const target = getTarget(defendingTeam, rng)
1355
+
1356
+ effects.push(...attack(attackingGotchi, attackingTeam, defendingTeam, [target], rng, {
1357
+ multiplier: MULTS.CLAN_MOMENTUM_DAMAGE,
1358
+ cannotBeCountered: true,
1359
+ noPassiveStatuses: true
1360
+ }))
1361
+ }
1362
+ }
1363
+
1364
+ break
1365
+ }
1366
+
1367
+ return {
1368
+ effects,
1369
+ statusesExpired,
1370
+ specialNotDone
1371
+ }
1372
+ }
1373
+
1374
+ module.exports = {
1375
+ getFormationPosition,
1376
+ getModifiedStats,
1377
+ gameLoop
1378
+ }