-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
103 lines (94 loc) · 3 KB
/
Copy pathcontroller.js
File metadata and controls
103 lines (94 loc) · 3 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
function Controller(game, callbacks) {
this.game = game;
this.callbacks = callbacks || {};
var self = this;
var DAS_DELAY = 170;
var DAS_INTERVAL = 50;
var dasTimer = null;
var dasInterval = null;
var dasKey = null;
function clearDAS() {
clearTimeout(dasTimer);
clearInterval(dasInterval);
dasTimer = null;
dasInterval = null;
dasKey = null;
}
function startDAS(key, action) {
clearDAS();
dasKey = key;
dasTimer = setTimeout(function() {
dasInterval = setInterval(function() {
if (!self.game.isPaused && !self.game.gameOver) action();
}, DAS_INTERVAL);
}, DAS_DELAY);
}
this._handler = function(e) {
if (self.game.gameOver) return;
if (e.code === 'Escape' || e.code === 'F1') {
e.preventDefault();
if (self.callbacks.onPause) self.callbacks.onPause();
return;
}
if (self.game.isPaused) return;
switch (e.code) {
case 'ArrowLeft':
case 'Numpad4':
e.preventDefault();
if (self.callbacks.onLeft) self.callbacks.onLeft();
startDAS(e.code, self.callbacks.onLeft);
break;
case 'ArrowRight':
case 'Numpad6':
e.preventDefault();
if (self.callbacks.onRight) self.callbacks.onRight();
startDAS(e.code, self.callbacks.onRight);
break;
case 'ArrowDown':
case 'Numpad2':
e.preventDefault();
if (self.callbacks.onDown) self.callbacks.onDown();
startDAS(e.code, self.callbacks.onDown);
break;
case 'ArrowUp':
case 'KeyX':
case 'Numpad1':
case 'Numpad5':
case 'Numpad9':
e.preventDefault();
if (self.callbacks.onRotateCW) self.callbacks.onRotateCW();
break;
case 'KeyZ':
case 'ControlLeft':
case 'ControlRight':
case 'Numpad3':
case 'Numpad7':
e.preventDefault();
if (self.callbacks.onRotateCCW) self.callbacks.onRotateCCW();
break;
case 'Space':
case 'Numpad8':
e.preventDefault();
if (self.callbacks.onHardDrop) self.callbacks.onHardDrop();
break;
case 'ShiftLeft':
case 'ShiftRight':
case 'KeyC':
case 'Numpad0':
e.preventDefault();
if (self.callbacks.onHold) self.callbacks.onHold();
break;
default:
break;
}
};
this._upHandler = function(e) {
if (e.code === dasKey) clearDAS();
};
window.addEventListener('keydown', this._handler);
window.addEventListener('keyup', this._upHandler);
}
Controller.prototype.destroy = function() {
if (this._handler) window.removeEventListener('keydown', this._handler);
if (this._upHandler) window.removeEventListener('keyup', this._upHandler);
};