-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeyboard_input_manager.ts
More file actions
116 lines (102 loc) · 2.55 KB
/
keyboard_input_manager.ts
File metadata and controls
116 lines (102 loc) · 2.55 KB
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
/**
* Keyboard Input Manager
*
* Singleton class that manages keyboard inputs.
*/
export class KeyboardInputManager {
/** Events */
static events: { [key: string]: any[] } = {}
constructor() {
KeyboardInputManager.events = {}
KeyboardInputManager.listen()
}
/**
* Adds an event listener.
*
* @param event Event
* @param callback Callback
*/
static on(event: string, callback: any): void {
if (!KeyboardInputManager.events[event])
KeyboardInputManager.events[event] = []
KeyboardInputManager.events[event].push(callback)
}
/**
* Emits an event to all listeners.
*
* @param event Event
* @param data Data
*/
static emit(event: string, data?: any): void {
if (KeyboardInputManager.events[event])
for (const callback of KeyboardInputManager.events[event]) callback(data)
}
/**
* Listens for events.
*/
static listen(): void {
const map = {
ArrowUp: 0,
ArrowRight: 1,
ArrowDown: 2,
ArrowLeft: 3,
w: 0, // Up
a: 3, // Left
s: 2, // Down
d: 1 // Right
}
// Respond to direction keys.
document.addEventListener('keydown', function (event: KeyboardEvent) {
// Ignore the event if it includes a modifier key.
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)
return
const mappedKey = map[event.key as keyof typeof map]
if (mappedKey !== undefined) {
event.preventDefault()
KeyboardInputManager.emit('move', mappedKey)
}
// R key restarts the game.
if (event.key === 'r') {
event.preventDefault()
KeyboardInputManager.restart(event)
}
})
// Respond to button presses.
KeyboardInputManager.bindButtonPress(
'.retry-button',
KeyboardInputManager.restart
)
KeyboardInputManager.bindButtonPress(
'.keep-playing-button',
KeyboardInputManager.keepPlaying
)
// Lab 5: New Game Button
}
/**
* Emits a restart event.
*
* @param event Event
*/
static restart(event: Event) {
event.preventDefault()
KeyboardInputManager.emit('restart')
}
/**
* Emits a keep playing event.
*
* @param event Event
*/
static keepPlaying(event: Event) {
event.preventDefault()
KeyboardInputManager.emit('keepPlaying')
}
/**
* Binds a button press.
*
* @param selector Selector
*/
static bindButtonPress(selector: any, fn: any) {
const button = document.querySelector(selector)
button.addEventListener('click', fn.bind(KeyboardInputManager))
}
}