aboutsummaryrefslogtreecommitdiff
path: root/src/controls.ts
blob: 8ae0dbfecb01e390b04800b7c47626cada66d199 (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
export interface Controls {
  up: boolean,
  right: boolean,
  down: boolean,
  left: boolean,
  spaceCount: number,
}

export let current = {
  up: false,
  right: false,
  down: false,
  left: false,
  spaceCount: 0,
}

document.addEventListener('keydown', event => {
  current = update(current, event.key, true)
})

document.addEventListener('keyup', event => {
  current = update(current, event.key, false)
})

function update(current: Controls, key: string, isDown: boolean): Controls {
  if (key === 'ArrowUp')
    return { ...current, up: isDown }
  else if (key === 'ArrowRight')
    return { ...current, right: isDown }
  else if (key === 'ArrowDown')
    return { ...current, down: isDown }
  else if (key === 'ArrowLeft')
    return { ...current, left: isDown }
  else if (key === ' ' && !isDown)
    return { ...current, spaceCount: current.spaceCount + 1 }
  else
    return current
}