« 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: 7665129ef4673ced19894fe2f1b22f82c5a17c13 (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
'use strict'

const canvas = document.getElementById('canvas')

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()

    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
      }
    }
  }

  update(dt) {
    // ATB gauge progressing
    if (!this.battleCharacter.isExecutingChain) {
      this.progress = Math.min(1, this.progress + dt * 1.5 / this.segmentCount)
    }

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

    // 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
        this.battle.changeMenuAnim = {old: null, direction: 1, time: 1}
        this.battle.currentMenu = this.battle.actionMenu
      }
    }
  }

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

  dequeue() {
    this.queuedActions.pop()
  }

  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
  }

  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)
  }

  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
    }

    const startIndex = this.currentOptionIndex - 1
    const endIndex = startIndex + 3

    const len = this.options.length

    this.drawY = 1
    for (let i = startIndex; i < endIndex; i++) {
      const option = this.options[i === -1 ? len - 1 : i === len ? 0 : i]
      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
  }

  getCurrentOption() {
    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) {
    super({options: [
      ['Fire', 'Fira', 'Firaga'],
      ['Blizz', 'Blizza', 'Blizzaga'],
      ['Aero', 'Aerora', 'Aeroga'],
      ['Zap', 'Zappa', 'Zappaga'],
      ['Bio', 'Biora'],
      ['Stun', 'Stunra', 'Stunga']
    ].map(arr => ({levelTexts: arr}))})

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

  drawOption(option, ctx) {
    const maxLevel = this.getMaxLevel(option)
    const effectiveLevel = this.getEffectiveLevel(option)
    option.label = option.levelTexts[effectiveLevel - 1]
    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(option.levelTexts.length, this.uiLevel)
  }

  getMaxLevel(option) {
    return option.levelTexts.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.queuedActions.push({
        label: option.levelTexts[effectiveLevel - 1],
        size: effectiveLevel
      })

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

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

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

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'

    // State

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

    this.targetCharacter = null

    this.name = 'Unnamed'

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

    this.hpBar = new HPBar(this)
  }

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

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

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

    if (this.isExecutingChain && !this.isExecutingAction) {
      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
      }
    }
  }

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

  applySpriteEffects(ctx) {
    if (this.dead) {
      ctx.filter = 'grayscale(100%)'
    }
  }

  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

    if (this.targetCharacter) {
      this.targetCharacter.takeDamage(action.size * 60)

      if (this.targetCharacter.dead) {
        this.determineNewOffenseTarget()
      }
    }
  }

  determineNewOffenseTarget() {
    const targets = this.getValidOffenseTargets()
    if (targets.length) {
      this.targetCharacter = targets[0]
    } else {
      this.targetCharacter = null
    }
  }

  getValidOffenseTargets() {
    return battle.getAllBattleCharacters()
      .filter(char => char.team !== battle.playerCharacter.team)
      .filter(char => !char.dead)
  }

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

class Battle {
  constructor() {
    // Parts

    this.teams = [
      new Team({battle: this}),
      new Team({battle: this})
    ]

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

    this.actionMenu = new ActionMenu(this)
    this.targetMenu = new TargetMenu(this)

    this.backdrop = new Backdrop()

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

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

    // State

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

    this.currentMenu = this.actionMenu
    this.changeMenuAnim = {time: 1, direction: 1, old: null}
    this.preWinAnim = null
  }

  draw() {
    const ctx = canvas.getContext('2d')
    let targetX = 0, targetY = 0
    const targetCharacter = (
      this.currentMenu === this.targetMenu && this.targetMenu.getCurrentOption() && this.targetMenu.getCurrentOption().battleCharacter ||
      this.playerCharacter.targetCharacter)

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

      if (targetCharacter === sprite) {
        targetX = sprite.x - camera.x
        targetY = y - camera.y
      }
    }
    ctx.restore()

    const { atbBar } = this.playerCharacter

    // 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
    ctx.save()
    if (this.preWinAnim || this.gameState === 'win') {
      const { time } = this.preWinAnim || {time: 0}
      ctx.translate(0, Math.floor(-20 * (time - 1)))
      ctx.filter = `opacity(${time * 100}%)`
    }
    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()
      ctx.drawImage(hpBar.canvas, canvas.width - 20 - hpBar.canvas.width, y)
      y -= 2
    }
    ctx.restore()

    if (targetCharacter) {
      const hpBar = targetCharacter.hpBar
      const x = targetX - hpBar.canvas.width / 2
      const y = targetY - hpBar.canvas.height
      hpBar.draw()
      ctx.drawImage(hpBar.canvas, x, y)
    }
  }

  update(dt) {
    if (this.gameState === 'battle') {
      this.battleUpdate(dt)
    } else if (this.gameState === 'pre-win') {
      this.preWinUpdate(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
      }
    }

    if (!this.getAllBattleCharacters().find(c => c.team !== this.playerCharacter.team && !c.dead)) {
      this.gameState = 'pre-win'
      this.preWinAnim = {time: 1}
    }
  }

  preWinUpdate(dt) {
    this.preWinAnim.time -= dt * 3
    if (this.preWinAnim.time <= 0) {
      this.preWinAnim = null
      this.gameState = 'win'
    }
  }

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

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

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

class Team {
  constructor({battle}) {
    this.battle = battle
    this.characters = [
      new BattleCharacter({team: this, battle}),
      new BattleCharacter({team: this, battle}),
      new BattleCharacter({team: this, battle})
    ]
  }

  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) {
      this.x = this.spriteToFollow.x - this.width / 2
      this.y = this.spriteToFollow.y - this.height / 2
    }
  }

  follow(sprite) {
    this.spriteToFollow = sprite
  }
}

const battle = new Battle()

for (let ti = 0; ti < battle.teams.length; ti++) {
  const team = battle.teams[ti]
  for (let ci = 0; ci < team.characters.length; ci++) {
    Object.assign(team.characters[ci], [
      [
        {x: 0, y: 240, name: 'Ren'},
        {x: -40, y: 240, name: 'Fie'},
        {x: 40, y: 240, name: 'Grat'}
      ],
      [
        {x: -40, y: 200, name: 'Nomber A'},
        {x: 0, y: 200, name: 'Nomber B'},
        {x: 40, y: 200, name: 'Flaprat'}
      ]
    ][ti][ci])
  }
}

const camera = battle.camera
camera.width = canvas.width
camera.height = canvas.height

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.preWinAnim) {
    ctx.filter = `grayscale(${(1 - battle.preWinAnim.time) * 100}%)`
  } else if (battle.gameState === 'win') {
    ctx.filter = 'grayscale(100%)'
  }
  ctx.drawImage(battle.canvas, 0, 0)

  requestAnimationFrame(drawLoop)
}

canvas.addEventListener('keypress', evt => {
  const { actionMenu, targetMenu, currentMenu } = battle
  const { atbBar } = battle.playerCharacter
  if (!battle.playerCharacter.isExecutingChain && battle.currentMenu) {
    if (evt.keyCode === 38) {
      currentMenu.upOption()
    } else if (evt.keyCode === 40) {
      currentMenu.downOption()
    } else if (currentMenu === 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) {
        atbBar.dequeue()
      } else if (evt.keyCode === 13 || evt.key.toLowerCase() === 'e') {
        if (battle.playerCharacter.atbBar.queuedActions.length) {
          battle.showTargetMenu()
        }
      }
    } else if (currentMenu === 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.currentMenu = actionMenu
        battle.changeMenuAnim = {old: targetMenu, direction: -1, time: 1}
      }
    }
  } else {
    // TODO: Backspace to cancel chain
    // TODO: E to execute chain immediately
  }
})

canvas.focus()

requestAnimationFrame(drawLoop)