« 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: 3e46f74023e8baea697dcbef61f0bfcd77447e6b (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
'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')
      ctx.drawImage(this.image, 0, 0)
    }
  }
}

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

class ATBBar {
  constructor(battleCharacter) {
    // Parts

    this.battleCharacter = battleCharacter

    // 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.save()

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

    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)

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

  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
      let cutoff = 0, segment = 0
      while (cutoff < this.queuedActions.length) {
        segment += this.queuedActions[cutoff].size
        if (segment > this.progress * this.segmentCount) {
          break
        }
        cutoff++
      }
      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.battleCharacter.isExecutingChain = true
    }
  }
}

class ActionMenu {
  constructor() {
    this.canvas = document.createElement('canvas')

    // State

    this.options = [
      ['Fire', 'Fira', 'Firaga'],
      ['Blizz', 'Blizza', 'Blizzaga'],
      ['Aero', 'Aerora', 'Aeroga'],
      ['Zap', 'Zappa', 'Zappaga'],
      ['Bio', 'Biora'],
      ['Stun', 'Stunra', 'Stunga']
    ]

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

    // Drawing

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

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

    const len = this.options.length

    let y = 1
    for (let i = startIndex; i < endIndex; i++) {
      const option = this.options[i === -1 ? len - 1 : i === len ? 0 : i]
      const maxLevel = option.length
      const effectiveLevel = Math.min(maxLevel, this.uiLevel)
      const text = option[effectiveLevel - 1]
      const rectW = this.getRectW(effectiveLevel)
      if (effectiveLevel < maxLevel) {
        const ghostRectW = this.getRectW(maxLevel)
        ctx.fillStyle = 'rgba(255, 255, 255, 0.3)'
        ctx.fillRect(1.5, y + 0.5, ghostRectW, 8)
        ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)'
        ctx.strokeRect(1.5, y + 0.5, ghostRectW, 8)
      }
      if (i === 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, y, rectW, 9)
      ctx.strokeStyle = 'black'
      ctx.strokeRect(1.5, y + 0.5, rectW - 1, 8)
      ctx.textAlign = 'center'
      ctx.fillStyle = 'black'
      ctx.font = '5px pixel-font'
      ctx.fillText(text, 1 + Math.round(rectW / 2), y + 2 + 9 / 2)

      y += 10
    }
  }

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

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

  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 = option.length
    const effectiveLevel = Math.min(maxLevel, this.uiLevel)
    const remainingSpace = atbBar.getRemainingSpace()

    if (effectiveLevel <= remainingSpace) {
      atbBar.queuedActions.push({
        label: option[effectiveLevel - 1],
        size: effectiveLevel
      })
    } else {
      // TODO: Feedback
    }
  }
}

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

    // Parts

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

    // State

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

  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
  }

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

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 battleCharacter = new BattleCharacter()
battleCharacter.x = 0
battleCharacter.y = 240

const atbBar = battleCharacter.atbBar
//atbBar.queuedActions = [{label: 'Fire', size: 1}, {label: 'Blizz', size: 1}, {label: 'Zap', size: 1}, {label: 'Firaga', size: 3}]

const actionMenu = new ActionMenu()

const camera = new Camera()
camera.width = canvas.width
camera.height = canvas.height
camera.follow(battleCharacter)

const backdrop = new Backdrop()
backdrop.y = 300 / 2

let lastTime = Date.now()

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

  battleCharacter.update(dt)
  camera.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)

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

  let y = canvas.height - 20
  if (!battleCharacter.isExecutingChain) {
    y -= actionMenu.canvas.height
    actionMenu.draw()
    ctx.drawImage(actionMenu.canvas, 20, y)
    y -= 2
  }
  atbBar.draw()
  ctx.drawImage(atbBar.canvas, 20, y - atbBar.canvas.height)

  requestAnimationFrame(drawLoop)
}

canvas.addEventListener('keypress', evt => {
  if (!battleCharacter.isExecutingChain) {
    if (evt.keyCode === 38) {
      actionMenu.upOption()
    } else if (evt.keyCode === 40) {
      actionMenu.downOption()
    } else if (evt.keyCode === 37) {
      actionMenu.decreaseLevel()
    } else if (evt.keyCode === 39) {
      actionMenu.increaseLevel()
    } else if (evt.which === 32) {
      actionMenu.queueTo(atbBar)
    } else if (evt.keyCode === 8) {
      atbBar.dequeue()
    } else if (evt.keyCode === 13 || evt.key.toLowerCase() === 'e') {
      atbBar.activate()
    }
  } else {
    // TODO: Backspace to cancel chain
  }
})

requestAnimationFrame(drawLoop)