aboutsummaryrefslogtreecommitdiff
path: root/src/controls.ts
blob: b575b3fcebb67f834a3f57b039e8ac501fd82a60 (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,
  space: boolean,
}

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

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 === ' ')
    return { ...current, space: isDown }
  else
    return current
}