« get me outta code hell

index.js - csb-game - Pixelly spin-off of the Command Synergy Battle system used in Final Fantasy XIII
summary refs log tree commit diff
path: root/index.js
blob: 955fcb7f8f845451f2c13e028f6bda9ac79b5239 (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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
'use strict'

const canvas = document.getElementById('canvas')

const last = arr => arr[arr.length - 1]
const pickRandom = arr => arr[randomIndex(arr)]
const randomIndex = arr => Math.floor(Math.random() * arr.length)

const chainDatabase = {
  fire: ['fire', 'fira', 'firaga'],
  cure: ['cure'],
  blizz: ['blizz', 'blizzara', 'blizzaga']
}

const actionDatabase = {
  fire: {id: 'fire',     chain: 'fire', label: 'Fire',   size: 1, target: 'enemy', color: '#F77', damage: 20, stun: 0.1},
  fira: {id: 'fira',     chain: 'fire', label: 'Fira',   size: 2, target: 'enemy', color: '#F77', damage: 40, stun: 0.2},
  firaga: {id: 'firaga', chain: 'fire', label: 'Firaga', size: 3, target: 'enemy', color: '#F77', damage: 60, stun: 0.3},

  cure: {id: 'cure', chain: 'cure', label: 'Cure', size: 1, target: 'ally', color: '#AFA', heal: 80},

  blizz: {id: 'blizz',       chain: 'blizz', label: 'Blizz',    size: 1, target: 'enemy', color: '#AAF', damage: 15, stun: 0.2},
  blizzara: {id: 'blizzara', chain: 'blizz', label: 'Blizzara', size: 2, target: 'enemy', color: '#AAF', damage: 30, stun: 0.35},
  blizzaga: {id: 'blizzaga', chain: 'blizz', label: 'Blizzaga', size: 3, target: 'enemy', color: '#AAF', damage: 45, stun: 0.5},

  aqua: {id: 'aqua',     chain: 'aqua', label: 'Aqua',   size: 1, target: 'enemy', color: '#33F', damage: 30, stun: 0},
  aquara: {id: 'aquara', chain: 'aqua', label: 'Aquara', size: 2, target: 'enemy', color: '#33F', damage: 60, stun: 0},
  aquaga: {id: 'aquaga', chain: 'aqua', label: 'Aquaga', size: 3, target: 'enemy', color: '#33F', damage: 90, stun: 0},

  manasvinSwipe: {id: 'manasvinSwipe', label: 'Swipe', size: 3, target: 'enemy', color: '#CCC', damage: 125, stun: 1.25, cooldown: 1},
  manasvinRecover: {id: 'manasvinRecover', label: 'Recover', size: 6, target: 'ally', color: '#AFA', heal: 175, cooldown: 2}
}

class Sprite {
  constructor() {
    this.x = 0
    this.y = 0
    this.canvas = document.createElement('canvas')
    this.image = document.createElement('img')
  }

  update(dt) {}

  draw() {
    if (this.image.complete) {
      this.canvas.width = this.image.width
      this.canvas.height = this.image.height
      const ctx = this.canvas.getContext('2d')
      this.applySpriteEffects(ctx)
      ctx.drawImage(this.image, 0, 0)
    }
  }

  applySpriteEffects(ctx) {}
}

class Backdrop extends Sprite {
  constructor() {
    super()
    this.image.src = 'img/bg.png'
  }
}

class ATBBar {
  constructor(battleCharacter) {
    // Parts

    this.battleCharacter = battleCharacter
    this.battle = this.battleCharacter.battle

    // State

    this.progress = 0
    this.visualProgress = 0
    this.segmentCount = 6
    this.queuedActions = []

    // Drawing

    this.canvas = document.createElement('canvas')
    this.canvas.width = 200
    this.canvas.height = 13
  }

  draw() {
    const ctx = this.canvas.getContext('2d')
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
    ctx.save()

    ctx.beginPath()
    ctx.rect(0, 0, Math.round(this.canvas.width * this.visualProgress), this.canvas.height)
    ctx.clip()

    if (this.battleCharacter.stunIsSignificant) {
      ctx.fillStyle = '#888'
    } else {
      ctx.fillStyle = '#77F'
    }
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)

    ctx.restore()
    ctx.strokeStyle = '#000'
    ctx.strokeRect(0.5, 0.5, this.canvas.width - 1, this.canvas.height - 1)

    const segmentWidth = this.canvas.width / this.segmentCount

    for (let i = 1; i < this.segmentCount; i++) {
      const x = Math.round(segmentWidth * i) + 0.5
      ctx.beginPath()
      ctx.moveTo(x, 0)
      ctx.lineTo(x, this.canvas.height)
      ctx.stroke()
    }

    {
      let i = 0
      for (const action of this.queuedActions) {
        const rectX = Math.round(segmentWidth * i) + 2
        const rectW = Math.round(segmentWidth * (i + action.size)) - rectX - 2 - (i + action.size === this.segmentCount ? 1 : 0) // Ternary so it doesn't touch the right-edge of the entire ATB gauge box
        const textX = Math.round(rectX + rectW / 2)
        const rectH = this.canvas.height - 5
        const text = action.label
        const actionFilled = this.progress * this.segmentCount >= i + action.size
        if (actionFilled) {
          ctx.fillStyle = 'gold'
        } else {
          ctx.fillStyle = 'white'
        }
        ctx.fillRect(rectX, 2, rectW, rectH)
        ctx.strokeStyle = 'black'
        ctx.strokeRect(rectX + 0.5, 2.5, rectW, rectH)
        ctx.textAlign = 'center'
        ctx.fillStyle = 'black'
        ctx.font = '5px pixel-font'
        ctx.fillText(text, textX, this.canvas.height / 2 + 2.5)
        i += action.size
      }
    }

    if (this.battleCharacter.stunIsSignificant) {
      ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'
      ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
      ctx.textAlign = 'left'
      ctx.fillStyle = 'black'
      ctx.font = '5px pixel-font'
      ctx.fillText('Stunned!', 2, this.canvas.height / 2 + 2.5)
    }
  }

  update(dt) {
    if (this.battle.playerCharacter !== this.battleCharacter) {
      this.aiUpdate(dt)
    }

    // Decrease stun time
    if (this.battleCharacter.stunTime) {
      this.battleCharacter.stunTime -= dt
      if (this.battleCharacter.stunTime <= 0) {
        this.battleCharacter.stunTime = 0
        this.battleCharacter.stunIsSignificant = null
      }
    }

    if (this.battleCharacter.stunIsSignificant) {
      // Ow! Clear queued actions.
      this.queuedActions.splice(0)
    } else {
      // ATB gauge progressing
      if (!this.battleCharacter.isExecutingChain) {
        this.progress = Math.min(1, this.progress + dt * 1.5 / this.segmentCount)
      }

      // Start action chain once user has confirmed (willExecuteChain = true) and IP gauge is full enough to execute all actions
      if (this.battleCharacter.willExecuteChain && this.progress >= 1 - this.getRemainingSpace() / this.segmentCount) {
        this.battleCharacter.willExecuteChain = false
        this.battleCharacter.isExecutingChain = true // Will be acknowledged by next if statement
      }

      // Action chaining
      if (this.battleCharacter.isExecutingChain && !this.battleCharacter.isExecutingAction) {
        if (this.queuedActions.length) {
          const action = this.queuedActions.shift()
          this.battleCharacter.executeAction(action)
          this.progress -= 1 / this.segmentCount * action.size
        } else {
          this.battleCharacter.isExecutingChain = false
          if (this.battle.playerCharacter === this.battleCharacter && !this.battle.currentMenu) {
            this.battle.showActionMenu({direction: 1})
          }
        }
      }
    }

    // ATB gauge visual update
    this.visualProgress += 8 * dt * (this.progress - this.visualProgress)
  }

  aiUpdate(dt) {
    if (this.battleCharacter.stunIsSignificant) {
      return
    }

    // Determine a target
    // TODO: AI logic for when to change target
    // TODO: Maybe need to bump the Math.random() chances.
    if (!this.battleCharacter.isExecutingChain && !this.battleCharacter.willExecuteChain && (this.battleCharacter.aiID === 'manasvinWarmech' || !this.battleCharacter.targetCharacter)) {
      if (this.battleCharacter.aiID === 'manasvinWarmech' && Math.random() < (1 - this.battleCharacter.hp / this.battleCharacter.maxHP) / 2) {
        this.battleCharacter.determineNewTarget('ally')
      } else {
        this.battleCharacter.determineNewTarget('enemy')
      }
    }

    // ATB gauge not full? Try to queue actions
    if (!this.battleCharacter.isExecutingChain && this.battleCharacter.targetCharacter && this.getRemainingSpace() >= 0) {
      // TODO: Actual AI logic here
      enqueueActions: while (this.getRemainingSpace()) {
        const actions = this.battleCharacter.knownActions
          .map(actionID => actionDatabase[actionID])
          .filter(a => a.target === this.battleCharacter.targetType)
        while (actions.length) {
          const index = randomIndex(actions)
          const action = actions[index]
          actions.splice(index, 1)
          if (this.enqueue(action)) {
            continue enqueueActions
          }
        }
        break
      }

      this.battleCharacter.willExecuteChain = true
    }
  }

  getRemainingSpace() {
    return this.segmentCount - this.queuedActions.reduce((acc, { size }) => acc + size, 0)
  }

  dequeue() {
    if (this.queuedActions.length) {
      const action = this.queuedActions.pop()

      if (action.cooldown) {
        delete this.battleCharacter.cooldownTimers[action.id] // Or set to 0, either works
      }
    }
  }

  enqueue(action) {
    if (this.stunIsSignificant) {
      return false
    } else if (this.getRemainingSpace() < action.size) {
      return false
    } else if (action.cooldown && this.battleCharacter.cooldownTimers[action.id]) {
      return false
    } else {
      if (action.cooldown) {
        this.battleCharacter.cooldownTimers[action.id] = action.cooldown * this.segmentCount
        this.battleCharacter.cooldownTimers[action.id] -= this.segmentCount - this.getRemainingSpace()
      }
      this.queuedActions.push(action)
      return true
    }
  }

  activate() {
    if (this.queuedActions.length) {
      // Cut off the actions that we don't have enough ATB charge for
      const cutoff = this.getCutoff()
      if (cutoff === 0) {
        // If we don't have enough charge to execute even one action, just don't do anything
        return
      }
      this.queuedActions.splice(cutoff)

      this.battle.hideCurrentMenu()
      this.battleCharacter.isExecutingChain = true
    }
  }

  activateOnceGaugeFull() {
    this.battle.hideCurrentMenu()
    this.battleCharacter.willExecuteChain = true
  }

  getCutoff() {
    // Cutoff point in the action queue where ATB does not fill the action
    let cutoff = 0, segment = 0
    while (cutoff < this.queuedActions.length) {
      segment += this.queuedActions[cutoff].size
      if (segment > this.progress * this.segmentCount) {
        break
      }
      cutoff++
    }
    return cutoff
  }
}

class HPBar {
  // Unlike ATBBar, HPBar does not actually deal with any logic.

  constructor(battleCharacter) {
    // Parts

    this.battleCharacter = battleCharacter

    // State

    this.progress = 0
    this.visualProgress = 0

    // Drawing

    this.canvas = document.createElement('canvas')
    this.canvas.width = 80
    this.canvas.height = 5

    this.labelCanvas = document.createElement('canvas')
    this.labelCanvas.height = 7
    // Label canvas width is determined during draw
  }

  draw() {
    const ctx = this.canvas.getContext('2d')
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
    ctx.save()

    ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
    ctx.save()

    ctx.beginPath()
    ctx.rect(1, 1, Math.ceil((this.canvas.width - 2) * this.visualProgress), this.canvas.height - 2)
    ctx.clip()

    ctx.fillStyle = '#5E5'
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)

    ctx.restore()
    ctx.strokeStyle = '#000'
    ctx.strokeRect(0.5, 0.5, this.canvas.width - 1, this.canvas.height - 1)

    this.drawLabel()
  }

  drawLabel() {
    const text = this.battleCharacter.name
    const ctx = this.labelCanvas.getContext('2d')
    ctx.font = '5px pixel-font'
    this.labelCanvas.width = ctx.measureText(text).width + 2
    ctx.fillStyle = 'rgba(128, 128, 128, 0.2)'
    ctx.fillRect(0, 0, this.labelCanvas.width, this.labelCanvas.height)
    ctx.font = '5px pixel-font' // It gets reset for some reason??
    ctx.fillStyle = 'white'
    ctx.fillText(text, 1, 6)
  }

  update(dt) {
    this.progress = this.battleCharacter.hp / this.battleCharacter.maxHP
    this.visualProgress += 8 * dt * (this.progress - this.visualProgress)
  }
}

class BaseBattleMenu {
  constructor({options}) {
    this.canvas = document.createElement('canvas')

    this.options = options
    this.currentOptionIndex = 0

    // Button height is 9, with a margin of 1 between each plus 1 at the top and bottom.
    const visibleButtonCount = 3
    this.canvas.height = 9 * visibleButtonCount + 1 * (visibleButtonCount - 1) + 2

    // Should be the width of a 3-segment ATB bar.
    this.canvas.width = 100
  }

  draw() {
    const ctx = this.canvas.getContext('2d')
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)

    if (this.options.length === 0) {
      // ..Well..
      return
    }

    this.keepCurrentIndexInBounds()

    this.drawY = 1

    if (this.options.length > 3) {
      const startIndex = this.currentOptionIndex - 1
      const endIndex = startIndex + 3
      const len = this.options.length
      for (let i = startIndex; i < endIndex; i++) {
        const option = this.options[i === -1 ? len - 1 : i === len ? 0 : i]
        this.drawOption(option, ctx)
      }
    } else {
      for (const option of this.options) {
        this.drawOption(option, ctx)
      }
    }
  }

  drawOption(option, ctx) {
    const rectW = this.getOptionW(option)
    if (option === this.options[this.currentOptionIndex]) {
      const mul = Math.sin(Date.now() / 200) * 0.125 + 0.875
      ctx.fillStyle = `rgb(${mul * 255}, ${mul * 127}, 0)`
    } else {
      ctx.fillStyle = 'white'
    }
    ctx.fillRect(1, this.drawY, rectW, 9)
    ctx.strokeStyle = 'black'
    ctx.strokeRect(1.5, this.drawY + 0.5, rectW - 1, 8)
    ctx.textAlign = 'center'
    ctx.fillStyle = 'black'
    ctx.font = '5px pixel-font'
    ctx.fillText(option.label, 1 + Math.round(rectW / 2), this.drawY + 2 + 9 / 2)
    this.drawY += 10
  }

  getOptionW(option) {
    return this.canvas.width - 2
  }

  keepCurrentIndexInBounds() {
    this.currentOptionIndex = Math.min(this.options.length - 1, this.currentOptionIndex)
  }

  getCurrentOption() {
    this.keepCurrentIndexInBounds()
    return this.options[this.currentOptionIndex]
  }

  downOption() {
    this.currentOptionIndex++

    if (this.currentOptionIndex >= this.options.length) {
      this.currentOptionIndex = 0
    }
  }

  upOption() {
    this.currentOptionIndex--

    if (this.currentOptionIndex <= -1) {
      this.currentOptionIndex = this.options.length - 1
    }
  }
}

class ActionMenu extends BaseBattleMenu {
  constructor({battle, battleCharacter, targetType}) {
    super({options: []})

    this.battle = battle
    this.battleCharacter = battleCharacter
    this.targetType = targetType
    this.uiLevel = 1 // 1-3 -- which of "fire", "fira", "firaga" is selected.
  }

  buildOptions() {
    const chains = {}
    const otherAbilities = []

    for (const action of this.battleCharacter.knownActions.map(actionID => actionDatabase[actionID]).filter(action => action.target === this.targetType)) {
      if (action.chain) {
        if (chains[action.chain]) {
          chains[action.chain]++
        } else {
          chains[action.chain] = 1
        }
      } else {
        otherAbilities.push(action)
      }
    }

    this.options = [
      ...Object.entries(chains).map(([ chainID, numLearned ]) => chainDatabase[chainID].slice(0, numLearned).map(actionID => actionDatabase[actionID])),
      ...otherAbilities.map(ability => [ability])
    ].map(chain => ({chain}))
  }

  drawOption(option, ctx) {
    const maxLevel = this.getMaxLevel(option)
    const effectiveLevel = this.getEffectiveLevel(option)
    option.label = option.chain[effectiveLevel - 1].label
    if (effectiveLevel < maxLevel) {
      const ghostRectW = this.getLevelW(maxLevel)
      ctx.fillStyle = 'rgba(255, 255, 255, 0.3)'
      ctx.fillRect(1.5, this.drawY + 0.5, ghostRectW, 8)
      ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)'
      ctx.strokeRect(1.5, this.drawY + 0.5, ghostRectW, 8)
    }
    super.drawOption(option, ctx)
  }

  getOptionW(option) {
    return this.getLevelW(this.getEffectiveLevel(option))
  }

  getEffectiveLevel(option) {
    return Math.min(this.getMaxLevel(option), this.uiLevel)
  }

  getMaxLevel(option) {
    return option.chain.length
  }

  getLevelW(level) {
    return Math.floor((this.canvas.width - 2) / 3 * level)
  }

  increaseLevel() {
    this.uiLevel++
    if (this.uiLevel > 3) {
      this.uiLevel = 3
    }
  }

  decreaseLevel() {
    this.uiLevel--
    if (this.uiLevel < 1) {
      this.uiLevel = 1
    }
  }

  queueTo(atbBar) {
    const option = this.options[this.currentOptionIndex]
    const maxLevel = this.getMaxLevel(option)
    const effectiveLevel = Math.min(maxLevel, this.uiLevel)
    const remainingSpace = atbBar.getRemainingSpace()

    if (effectiveLevel <= remainingSpace) {
      atbBar.enqueue(option.chain[effectiveLevel - 1])

      if (effectiveLevel === remainingSpace) {
        this.battle.showTargetMenu()
      }
    } else {
      // TODO: Feedback
    }
  }
}

class TargetMenu extends BaseBattleMenu {
  constructor(battle) {
    super({options: []})
    this.battle = battle
  }

  buildOptions(targetType) {
    this.options = this.battle.playerCharacter.getValidTargets(targetType)
      .map(char => ({label: char.name, battleCharacter: char}))

    // If the top action is a 'cure' action, pick the character with the least health by default.
    // TODO: Some property like "healsAlive" on the action itself, so things like potions (which target one) are also affected by this
    if (last(this.battle.playerCharacter.atbBar.queuedActions).chain === 'cure') {
      const allies = this.battle.playerCharacter.team.characters
      const aliveCharacter = allies.find(c => !c.dead)
      const mostHurtCharacter = allies.reduce((a, b) => (b.hp < a.hp && !b.dead ? b : a), aliveCharacter)
      this.currentOptionIndex = this.options.findIndex(opt => opt.battleCharacter === mostHurtCharacter)
    }
  }
}

class BattleCharacter extends Sprite {
  constructor({team, battle}) {
    super()

    // Parts

    this.team = team
    this.battle = battle
    this.atbBar = new ATBBar(this)
    this.image.src = 'img/char.png'

    this.targetAllyActionMenu = new ActionMenu({battle, battleCharacter: this, targetType: 'ally'})
    this.targetEnemyActionMenu = new ActionMenu({battle, battleCharacter: this, targetType: 'enemy'})

    // State

    this.isExecutingChain = false
    this.isExecutingAction = false
    this.actionExecuteTime = 0
    this.actionBeingExecuted = null

    this.targetType = null // ally or enemy
    this.targetCharacter = null
    this.targetEnemyCharacter = null // Last enemy the character targeted, should never be set directly

    this.name = 'Unnamed'

    this.hp = 500
    this.maxHP = 500
    this.dead = false

    this.hpBar = new HPBar(this)

    // "Stun" is not an actual status effect of paralysis, but refers to how
    // long a character is prevented from acting after having been hit.
    // Effects during when stunTime is non-zero:
    // * The character cannot execute any actions. Enqueued actions are delayed
    //   until stun time ends.
    // * The character's ATB gauge continues progressing UNLESS the stun is
    //   "significant" (see stunIsSignificant).
    // * The character's actionExecuteTime continues decreasing. Therefore,
    //   if a character is hit by a strong attack and stunned for some time,
    //   they will immediately activate the next queued action once the stun
    //   time has passed (assuming actionExecuteTime has reached zero).
    // * The character can still input (enqueue) actions UNLESS the stun is
    //   "significant". Newly-queued actions will not be executed until the
    //   stun time has passed.
    // The property stunTime usually should not be set directly. Instead, use
    // the addStunTime function, which contains additional accounting for
    // stunIsSignificant.
    this.stunTime = 0

    // This property refers to whether a character's stun time is considered
    // "significant". If a stun is significant, the character's ATB gauge will
    // not progress during the stun. Furthermore, the character's queued
    // actions will all be removed (but the ATB gauge itself will not be
    // reset), and the character will be prevented from enqueueing any actions
    // until the stun has passed. Significant stuns create an effect of the
    // character "losing focus", and give incentive to avoid heavy blows.
    // A stun will automatically be considered significant if the stun time
    // passes a certain threshold. For example, while a single light attack may
    // not significantly stun a character, a persistent barrage may be able to.
    this.stunIsSignificant = null

    // Array of action IDs.
    this.knownActions = []

    // Cooldown timers for each action with a cooldown. If an action's cooldown
    // is greater than zero, it can't be queued. A unit of "1" on the cooldown
    // means one full ATB gauge of executed actions. So if the ATB gauge length
    // is 3 and a size-2 action is executed, all timers go down by 2/3.
    // Note, however, that on this particular object a unit of 1 refers to one
    // individual ATB segment; however, the cooldown property on an action
    // object behaves as described above. The reason 1 refers to a single ATB
    // segment here is to avoid decimal rounding issues; 3 - 2 is 1 but that's
    // not so certain with math similar to 1 - 2/3.
    // If an action can successfully be enqueued (i.e. its cooldown timer is
    // already zero), its cooldown timer is immediately set according to its
    // cooldown property. This is so that it cannot be enqueued twice within
    // a single queue. If it is dequeued, its cooldown timer is reset to 0.
    // A cooldown timer of 1 means "can't be executed more than once in a
    // single queue", but will be able to be enqueued and executed during the
    // next queue (there is no number of queues that must be waited).
    // Technically this behavior is surprising since, if a move with cooldown
    // is executed at the end of a queue, it can enqueued immediately again
    // in the next queue - after less than its cooldown timer has passed.
    // To implement this, the cooldown timer is initially offset by the number
    // of ATB segments before where its action is enqueued to. So in our 2-size
    // action with a cooldown of 1 being enqueued to the end of a 3-ATB gauge
    // queue, its cooldown timer is initially offset by -1/3, so that only 2/3,
    // or 2 ATB segments, must pass before it can be enqueued again. Since the
    // move with cooldown itself is a 2-size move, it will account for the
    // remaining ATB space.
    // As of this writing there is no designed special behavior for what should
    // happen if an action with cooldown is executed as part of a queue that is
    // not entirely filled. My understanding is that its cooldown timer would
    // not be fully cleared since, even taking into account the initial offset,
    // not enough actions would have been executed after the cooldown action.
    // Thus another ATB gauge would have to be waited until the timer reaches
    // zero. This is not an issue for AI-controlled characters (i.e. enemies),
    // though, since they usually fill their queue as full as possible; and AI-
    // controlled characters are the ones which the cooldown mechanic was
    // designed for in the first place.
    this.cooldownTimers = {}
  }

  update(dt) {
    this.hpBar.update(dt)

    if (this.dead) {
      this.deadUpdate(dt)
    } else {
      this.aliveUpdate(dt)
    }
  }

  aliveUpdate(dt) {
    this.atbBar.update(dt)

    if (this.targetCharacter && this.targetCharacter.team !== this.team) {
      this.targetEnemyCharacter = this.targetCharacter
    }

    if (this.isExecutingChain && !this.isExecutingAction) {
      // It's okay to be executing a chain but not any particular action if we
      // are significantly stunned.
      if (!this.stunIsSignificant) {
        throw new Error('Executing chain but not action for more than one update.. ATB Bar should have queued an action or ended the chain')
      }
    }

    if (this.actionExecuteTime) {
      this.actionExecuteTime -= dt

      if (this.actionExecuteTime <= 0) {
        this.actionExecuteTime = 0
        this.isExecutingAction = false
        this.actionBeingExecuted = null
      }
    }
  }

  deadUpdate(dt) {
    // Do nothing, for now.
  }

  applySpriteEffects(ctx) {
    let filter = ''
    if (this.dead) {
      filter += 'grayscale(100%) '
    }
    // TODO: Just for debugging, change this later
    if (false && this.stunTime) {
      if (this.stunIsSignificant) {
        filter += 'blur(2px) '
      } else {
        filter += 'blur(1px) '
      }
    }
    ctx.filter = filter.trim()
  }

  executeAction(action) {
    if (this.isExecutingActions) {
      throw new Error('Called executeAction while already executing actions')
    }

    this.isExecutingChain = true
    this.isExecutingAction = true
    this.actionExecuteTime = 0.4 + 0.2 * action.size
    this.actionBeingExecuted = action

    for (const [ actionID, remainingSegments ] of Object.entries(this.cooldownTimers)) {
      if (remainingSegments > action.size) {
        this.cooldownTimers[actionID] -= action.size
      } else {
        delete this.cooldownTimers[actionID] // Or set to 0, either works
      }
    }

    if (this.targetCharacter) {
      this.battle.animationEntities.push(new MagicProjectile(this, this.targetCharacter, action))
    }
  }

  determineNewTarget(targetType) {
    const targets = this.getValidTargets(targetType)
    this.targetType = targetType
    if (targets.length) {
      // TODO: Some sort of "follow the leader" mechanic
      this.targetCharacter = pickRandom(targets)
    } else {
      this.targetCharacter = null
    }
  }

  getValidTargets(targetType) {
    return battle.getAllBattleCharacters()
      .filter(char =>
        targetType === 'enemy' && char.team !== this.team ||
        targetType === 'ally' && char.team === this.team)
      .filter(char => !char.dead)
  }

  takeDamage(damage) {
    if (!this.dead) {
      this.hp -= damage
      if (this.hp <= 0) {
        this.died()
      }
    }
  }

  recoverHP(amount) {
    if (!this.dead) {
      this.hp = Math.min(this.maxHP, this.hp + amount)
    }
  }

  died() {
    this.hp = 0
    this.dead = true

    this.stunTime = 0
    this.stunIsSignificant = null

    for (const battleCharacter of this.battle.getAllBattleCharacters()) {
      if (battleCharacter.targetCharacter === this) {
        battleCharacter.determineNewTarget('enemy') // TODO: battleCharacter.targetType
      }
    }
  }

  addStunTime(time, forceSignificant = false) {
    // Takes the optional argument forceSignificant. This should almost always
    // be left as false, even if a move seems like it should be considered
    // "heavy" (e.g. getting whacked by the swipe of a huge claw). Instead, let
    // the logic in this function decide whether a stun is significant. Doing
    // so lets the character's own stun threshold be taken into account.

    this.stunTime += time

    // TODO: Generate this somehow.
    const significantStunThreshold = 1

    if (forceSignificant || this.stunTime >= significantStunThreshold) {
      // Only set stunIsSignificant here. ATBBar will control the resulting
      // effects of having been significantly stunned.
      this.stunIsSignificant = true
    } else {
      this.stunIsSignificant = false
    }
  }
}

class Battle {
  constructor({teamData}) {
    // Parts

    this.teams = teamData.map(obj => new Team(Object.assign({battle: this}, obj)))

    this.playerCharacter = this.teams[0].characters[0]

    this.targetMenu = new TargetMenu(this)

    this.targetTypeMenu = new BaseBattleMenu({options: [
      {label: 'Aggression', targetType: 'enemy'},
      {label: 'Reinforcement', targetType: 'ally'}
    ]})

    this.backdrop = new Backdrop()

    this.camera = new BattleCamera()
    this.camera.follow(this.playerCharacter)

    this.slideacrossMessage = new SlideacrossMessage()

    this.animationEntities = []

    this.canvas = document.createElement('canvas')
    // State

    this.gameState = 'battle' // battle, pre-win, win, pre-lose, lose

    this.currentMenu = this.targetTypeMenu
    this.changeMenuAnim = {time: 1, direction: 1, old: null}
    this.preEndAnim = null
  }

  draw() {
    const ctx = canvas.getContext('2d')

    const overlayHPBars = []

    const addOverlayHPBarFor = battleCharacter => {
      if (battleCharacter) {
        if (!overlayHPBars.find(o => o.battleCharacter === battleCharacter)) {
          overlayHPBars.push({x: 0, y: 0, battleCharacter})
        }
      }
    }

    addOverlayHPBarFor(this.playerCharacter.targetEnemyCharacter)

    if (this.currentMenu !== this.targetMenu) {
      addOverlayHPBarFor(this.playerCharacter.targetCharacter)
    }

    if (this.currentMenu === this.targetMenu) {
      const option = this.currentMenu.getCurrentOption()
      if (option) {
        addOverlayHPBarFor(option.battleCharacter)
      }
    }

    ctx.save() // Begin camera-translated drawing
    ctx.translate(Math.round(-camera.x), Math.round(-camera.y))
    for (const sprite of [this.backdrop, ...this.getAllBattleCharacters(), ...this.animationEntities]) {
      const x = Math.round(sprite.x - sprite.canvas.width / 2)
      const y = Math.round(sprite.y - sprite.canvas.height / 2)
      sprite.draw()
      ctx.drawImage(sprite.canvas, x, y)

      const overlayHPBar = overlayHPBars.find(o => o.battleCharacter === sprite)
      if (overlayHPBar) {
        overlayHPBar.x = sprite.x - camera.x
        overlayHPBar.y = y - camera.y
      }
    }

    for (const battleCharacter of this.getAllBattleCharacters()) {
      if (battleCharacter.isExecutingAction) {
        const sprite = battleCharacter
        const { label } = battleCharacter.actionBeingExecuted

        ctx.font = '5px pixel-font'
        const width = ctx.measureText(label).width + 4
        const x = Math.round(sprite.x - sprite.canvas.width / 2 - width / 2)
        const y = Math.round(sprite.y - sprite.canvas.height / 2)

        let textFillStyle
        if (battleCharacter.team === this.playerCharacter.team) {
          ctx.fillStyle = 'rgba(45, 128, 255, 0.3)'
          ctx.strokeStyle = 'rgb(30, 85, 170)'
        } else {
          ctx.fillStyle = 'rgba(255, 45, 45, 0.3)'
          ctx.strokeStyle = 'rgb(170, 30, 30)'
        }
        ctx.fillRect(x, y, width, 9)
        ctx.strokeRect(x + 0.5, y + 0.5, width, 8)
        ctx.font = '5px pixel-font' // It gets reset for some reason?
        ctx.fillStyle = 'white'
        ctx.textAlign = 'left'
        ctx.fillText(label, x + 3, y + 7)
      }
    }
    ctx.restore() // End camera-translated drawing

    const { atbBar } = this.playerCharacter

    ctx.save()
    if (this.preEndAnim || this.gameState === 'win' || this.gameState === 'lose') {
      const { time } = this.preEndAnim || {time: 0}
      ctx.translate(0, Math.floor(-20 * (time - 1)))
      ctx.filter = `opacity(${time * 100}%)`
    }

    // TODO: transition y for menus.. let targetY
    let y = canvas.height - 20
    if (this.changeMenuAnim && this.changeMenuAnim.old) {
      const { old: oldMenu, time, direction } = this.changeMenuAnim
      oldMenu.draw()
      ctx.save()
      ctx.translate(Math.floor(10 * (time - 1) * direction), 0)
      ctx.filter = `opacity(${time * 100}%)`
      ctx.drawImage(oldMenu.canvas, 20, y - oldMenu.canvas.height)
      ctx.restore()
    }
    if (this.currentMenu) {
      this.currentMenu.draw()
      ctx.save()
      if (this.changeMenuAnim) {
        const { time, direction } = this.changeMenuAnim
        ctx.translate(Math.floor(10 * time * direction), 0)
        ctx.filter = `opacity(${(1 - time) * 100}%)`
      }
      ctx.drawImage(this.currentMenu.canvas, 20, y - this.currentMenu.canvas.height)
      ctx.restore()
    }
    const targetOffset = this.currentMenu ? this.currentMenu.canvas.height : 0
    const oldOffset = (this.changeMenuAnim && this.changeMenuAnim.old) ? this.changeMenuAnim.old.canvas.height : 0
    y -= oldOffset + (targetOffset - oldOffset) * (this.changeMenuAnim ? 1 - this.changeMenuAnim.time : 1)
    y -= 2
    atbBar.draw()
    ctx.drawImage(atbBar.canvas, 20, y - atbBar.canvas.height)

    y = canvas.height - 20
    for (const { hpBar } of this.playerCharacter.team.characters) {
      y -= hpBar.canvas.height
      hpBar.draw()
      const x = canvas.width - 20 - hpBar.canvas.width
      ctx.drawImage(hpBar.canvas, x, y)
      ctx.drawImage(hpBar.labelCanvas, x - hpBar.labelCanvas.width - 2, y - 1)
      y -= 4
    }

    for (const { x, y, battleCharacter } of overlayHPBars) {
      const hpBar = battleCharacter.hpBar
      const drawX = x - hpBar.canvas.width / 2
      const drawY = y - hpBar.canvas.height
      hpBar.draw()
      ctx.drawImage(hpBar.canvas, drawX, drawY)
      ctx.drawImage(hpBar.labelCanvas, drawX - hpBar.labelCanvas.width - 2, drawY - 1)
    }

    this.slideacrossMessage.canvas.width = this.canvas.width
    this.slideacrossMessage.canvas.height = this.canvas.height
    this.slideacrossMessage.draw()
    ctx.drawImage(this.slideacrossMessage.canvas, 0, 0)

    ctx.restore()
  }

  update(dt) {
    if (this.gameState === 'battle') {
      this.battleUpdate(dt)
    } else if (this.gameState === 'pre-win') {
      this.preWinUpdate(dt)
    } else if (this.gameState === 'pre-lose') {
      this.preLoseUpdate(dt)
    }
  }

  battleUpdate(dt) {
    for (const team of this.teams) {
      team.update(dt)
    }

    this.camera.update(dt)

    if (this.changeMenuAnim) {
      this.changeMenuAnim.time -= 5 * dt
      if (this.changeMenuAnim.time <= 0) {
        this.changeMenuAnim = null
      }
    }

    for (const entity of this.animationEntities) {
      entity.update(dt)
    }

    this.animationEntities = this.animationEntities.filter(e => !e.discarded)

    this.slideacrossMessage.update(dt)

    // Assign a new player character if the current one died
    if (this.playerCharacter.dead) {
      const newCharacter = this.playerCharacter.team.characters.find(c => !c.dead)
      if (newCharacter) {
        this.playerCharacter = newCharacter
        this.camera.follow(newCharacter)
        newCharacter.atbBar.queuedActions.splice(0)
        newCharacter.isExecutingChain = false
        this.showTargetTypeMenu()
        this.slideacrossMessage.showMessage('Leader changed: ' + newCharacter.name)
      }
    }

    // SOMEHOW managed to have all teams die in the same instant? Player wins :)
    if (!this.getAllBattleCharacters().find(c => c.team !== this.playerCharacter.team && !c.dead)) {
      this.gameState = 'pre-win'
      this.preEndAnim = {time: 1}
    } else if (!this.playerCharacter.team.characters.find(c => !c.dead)) {
      this.gameState = 'pre-lose'
      this.preEndAnim = {time: 1}
    }
  }

  preWinUpdate(dt) {
    this.preEndUpdate(dt, 'win')
  }

  preLoseUpdate(dt) {
    this.preEndUpdate(dt, 'lose')
  }

  preEndUpdate(dt, nextGameState) {
    this.preEndAnim.time -= dt * 3
    if (this.preEndAnim.time <= 0) {
      this.preEndAnim = null
      this.gameState = nextGameState
    }
  }

  showTargetTypeMenu() {
    this.changeMenuAnim = {old: this.currentMenu, direction: -1, time: 1}
    this.currentMenu = this.targetTypeMenu
  }

  showActionMenu({direction}) {
    this.changeMenuAnim = {old: this.currentMenu, direction, time: 1}
    if (this.playerCharacter.targetType === 'enemy') {
      this.currentMenu = this.playerCharacter.targetEnemyActionMenu
    } else {
      this.currentMenu = this.playerCharacter.targetAllyActionMenu
    }
    this.currentMenu.buildOptions()
  }

  showTargetMenu() {
    this.changeMenuAnim = {old: this.currentMenu, direction: 1, time: 1}
    this.currentMenu = this.targetMenu
    this.targetMenu.buildOptions(this.playerCharacter.targetType)
  }

  hideCurrentMenu() {
    this.changeMenuAnim = {old: this.currentMenu, direction: 1, time: 1}
    this.currentMenu = null
  }

  getAllBattleCharacters() {
    return this.teams.reduce((acc, team) => acc.concat(team.characters), [])
  }

  get actionMenu() {
    return this.playerCharacter.targetType === 'enemy' ? this.targetEnemyActionMenu : this.targetAllyActionMenu
  }
}

class Team {
  constructor({battle, characterData = []}) {
    if (!battle) {
      throw new Error('Team created without being passed a Battle')
    }

    this.battle = battle
    this.characters = characterData.map(obj => Object.assign(new BattleCharacter({battle, team: this}), obj))
  }

  update(dt) {
    for (const character of this.characters) {
      character.update(dt)
    }
  }
}

class Camera extends Sprite {
  constructor() {
    super()

    this.spriteToFollow = null
    this.width = 200
    this.height = 200
  }

  update(dt) {
    if (this.spriteToFollow) {
      const target = this.getCenteredCoords(this.getSpriteFollowCoords(this.spriteToFollow))
      this.x += 5 * dt * (target.x - this.x)
      this.y += 5 * dt * (target.y - this.y)
    }
  }

  follow(sprite) {
    this.spriteToFollow = sprite
  }

  warpTo(sprite) {
    const target = this.getCenteredCoords(this.getSpriteFollowCoords(sprite))
    this.x = target.x
    this.y = target.y
  }

  getSpriteFollowCoords(sprite) {
    return {x: sprite.x, y: sprite.y}
  }

  getCenteredCoords(sprite) {
    return {
      x: sprite.x - this.width / 2,
      y: sprite.y - this.height / 2
    }
  }
}

class BattleCamera extends Camera {
  constructor() {
    super()

    this.battlefieldCenterX = 20
    this.battlefieldCenterY = 220
  }

  getSpriteFollowCoords(sprite) {
    const bx = this.battlefieldCenterX
    const by = this.battlefieldCenterY
    return {x: bx + (sprite.x - bx) / 5, y: by + (sprite.y - by) / 5}
  }
}

class MagicProjectile {
  constructor(caster, target, action) {
    this.x = caster.x
    this.y = caster.y

    this.target = target
    this.action = action

    this.canvas = document.createElement('canvas')
    this.canvas.width = 8
    this.canvas.height = 8
  }

  update(dt) {
    // TODO: Good animation, make distance affect acceleration, not velocity
    this.x += dt * 5 * (this.target.x - this.x)
    this.y += dt * 5 * (this.target.y - this.y)

    if (Math.abs(this.target.x - this.x) <= 5 && Math.abs(this.target.y - this.y) <= 5) {
      if (this.action.target === 'enemy') {
        if (this.action.damage) this.target.takeDamage(this.action.damage)
        if (this.action.stun) this.target.addStunTime(this.action.stun || 0)
      } else if (this.action.target === 'ally') {
        if (this.action.heal) this.target.recoverHP(this.action.heal)
      }
      this.discarded = true
    }
  }

  draw() {
    const ctx = this.canvas.getContext('2d')
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
    ctx.fillStyle = this.action.color
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)
  }
}

class SlideacrossMessage {
  constructor() {
    this.text = null
    this.anim = null

    this.canvas = document.createElement('canvas')
    // Width/height should be set externally!
  }

  update(dt) {
    if (this.anim) {
      this.anim.time -= 0.5 * dt

      if (this.anim.time <= 0) {
        this.anim = null
      }
    }
  }

  draw() {
    const ctx = this.canvas.getContext('2d')
    ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)

    if (this.anim) {
      let x = 0
      if (this.anim.time <= 0.5) {
        x = this.canvas.width + 0.5 * this.canvas.width * Math.sin(-(this.anim.time * Math.PI))
      } else {
        x = 0.5 * this.canvas.width * Math.sin(this.anim.time * Math.PI)
      }
      ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
      ctx.fillRect(0, this.canvas.height / 2 - 8, this.canvas.width, 16)

      ctx.font = '5px pixel-font'
      ctx.fillStyle = 'white'
      ctx.textAlign = 'center'
      ctx.fillText(this.text, x, this.canvas.height / 2)
    }
  }

  showMessage(text) {
    this.text = text
    this.anim = {time: 1}
  }
}

const battle = new Battle({
  teamData: [
    {characterData: [
      {x: -75, y: 190, name: 'Ren', hp: 400, maxHP: 400, knownActions: ['fire', 'fira', 'firaga', 'blizz', 'blizzara', 'cure']},
      {x: -95, y: 225, name: 'Fie', hp: 375, maxHP: 375, knownActions: ['fire', 'blizz', 'blizzara', 'blizzaga', 'aqua', 'aquara']}
    ]},
    {characterData: [
      {x: 100, y: 200, aiID: 'manasvinWarmech', name: 'Manasvin Warmech', hp: 1600, maxHP: 1600, knownActions: ['aqua', 'aquaga', 'manasvinSwipe', 'manasvinRecover']}
    ]}
  ]
})

battle.teams[0].characters[0].atbBar.segmentCount = 4
battle.teams[0].characters[1].atbBar.segmentCount = 4
battle.teams[1].characters[0].image.src = 'img/warmech.png'

const camera = battle.camera
camera.width = canvas.width
camera.height = canvas.height
camera.warpTo(battle.playerCharacter)

battle.canvas.width = canvas.width
battle.canvas.height = canvas.height

battle.backdrop.y = 300 / 2

let lastTime = Date.now()

function drawLoop() {
  const dt = (Date.now() - lastTime) / 1000
  lastTime = Date.now()

  battle.update(dt)

  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.fillStyle = '#EEE'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  battle.draw()
  if (battle.preEndAnim) {
    ctx.filter = `grayscale(${(1 - battle.preEndAnim.time) * 100}%)`
  } else if (battle.gameState === 'win' || battle.gameState === 'lose') {
    ctx.filter = 'grayscale(100%)'
  }
  ctx.drawImage(battle.canvas, 0, 0)

  ctx.font = '5px pixel-font'
  ctx.fillStyle = 'white'
  ctx.textAlign = 'center'
  if (battle.gameState === 'win') {
    ctx.fillText('You won!', canvas.width / 2, canvas.height / 2)
  } else if (battle.gameState === 'lose') {
    ctx.fillText('You lost.', canvas.width / 2, canvas.height / 2)
  }

  requestAnimationFrame(drawLoop)
}

canvas.addEventListener('keypress', evt => {
  if (battle.gameState !== 'battle') {
    return
  }

  const { targetTypeMenu, actionMenu, targetMenu, currentMenu } = battle
  const { atbBar } = battle.playerCharacter

  if (currentMenu) {
    if (evt.keyCode === 38) {
      currentMenu.upOption()
    } else if (evt.keyCode === 40) {
      currentMenu.downOption()
    }
  }

  if (currentMenu === targetTypeMenu) {
    if (evt.keyCode === 13 || evt.which === 32) {
      const newTargetType = targetTypeMenu.getCurrentOption().targetType
      if (battle.playerCharacter.targetType !== newTargetType) {
        battle.playerCharacter.targetType = newTargetType
        atbBar.queuedActions.splice(0) // Changed target type, empty queue
      }
      battle.showActionMenu({direction: 1})
    } else if (evt.keyCode === 8 && battle.playerCharacter.targetType) {
      if (battle.playerCharacter.isExecutingChain || battle.playerCharacter.willExecuteChain) {
        battle.hideCurrentMenu()
      } else {
        battle.showActionMenu({direction: 1})
      }
    }
  } else if (!battle.playerCharacter.isExecutingChain && battle.currentMenu) {
    if (currentMenu instanceof ActionMenu) {
      if (evt.keyCode === 37) {
        currentMenu.decreaseLevel()
      } else if (evt.keyCode === 39) {
        currentMenu.increaseLevel()
      } else if (evt.which === 32) {
        currentMenu.queueTo(atbBar)
      } else if (evt.keyCode === 8) {
        if (atbBar.queuedActions.length) {
          atbBar.dequeue()
        } else {
          battle.showTargetTypeMenu()
        }
      } else if (evt.keyCode === 9) {
        battle.showTargetTypeMenu()
      } else if (evt.keyCode === 13 || evt.key.toLowerCase() === 'e') {
        if (battle.playerCharacter.atbBar.queuedActions.length) {
          battle.showTargetMenu()
        }
      }
    } else if (currentMenu instanceof TargetMenu) {
      if (evt.keyCode === 13 || evt.key.toLowerCase() === 'e' || evt.which === 32) {
        battle.playerCharacter.targetCharacter = currentMenu.getCurrentOption().battleCharacter
        if (evt.key.toLowerCase() === 'e') {
          atbBar.activate()
        } else {
          atbBar.activateOnceGaugeFull()
        }
      } else if (evt.keyCode === 8) {
        battle.showActionMenu({direction: -1})
      }
    }
  } else if (battle.playerCharacter.willExecuteChain) {
    if (evt.keyCode === 8) {
      battle.playerCharacter.willExecuteChain = false
      battle.showTargetMenu()
    } else if (evt.key.toLowerCase() === 'e') {
      if (atbBar.getCutoff() > 0) {
        battle.playerCharacter.willExecuteChain = false
        atbBar.activate()
      } else {
        atbBar.queuedActions.splice(1)
      }
    } else if (evt.keyCode === 9) {
      battle.showTargetTypeMenu()
    }
  } else if (battle.playerCharacter.isExecutingChain) {
    if (evt.keyCode === 8) {
      atbBar.queuedActions.splice(0)
      battle.playerCharacter.isExecutingChain = false
      battle.showActionMenu({direction: -1})
    } else if (evt.keyCode === 9) {
      battle.showTargetTypeMenu()
    }
  }

  if (evt.keyCode === 9) { // Capture tab, but not everything else (like ctrl-R)
    evt.preventDefault()
  } else if (evt.keyCode === 8) { // Apparently backspace does browser things we don't want
    evt.preventDefault()
  }
})

canvas.focus()

requestAnimationFrame(drawLoop)