-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeys.js
More file actions
240 lines (237 loc) · 8.29 KB
/
keys.js
File metadata and controls
240 lines (237 loc) · 8.29 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
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
// 2025. 07. 17. ; 12:01
class keysKey {
constructor(name="", time=-1) {
this.name = name;
this.time = time;
}
str() {
return `${this.name}||${this.time}`;
}
static from(str) {
return new keysKey(...str.split("||"));
}
}
class keysClass {
constructor(logKeysDown=false) {
this.keysDown = new Set();
this.cooldown = [];
this.keysBound = {};
this.logKeysDown = logKeysDown;
this.updateID = -69; // Makes sure that only 1 update cycle is running
}
get anyKeyDown() {
return this.keysDown.size > 0;
}
get allKeysDown() {
return Array.from(this.keysDown).map(x => x.split("||")[0]);
}
/**
* Has the key been pressed for exactly {time} frames
* @param {Number} time frames
*/
isKeyPressed(key, time=1) {
let keys = [...this.keysDown], f = false
keys.forEach(k => {
if (f) return;
let keyw = keysKey.from(k)
if (keyw.name == key && keyw.time <= time) f = true;
})
return f;
}
/**
* @param {Number} time frames
*/
hasBeenDownFor(key, time=1) {
let keys = [...this.keysDown], f = false
keys.forEach(k => {
if (f) return;
let keyw = keysKey.from(k)
if (keyw.name == key && keyw.time >= time) f = true;
})
return f;
}
/**
* Key has been down for either 1 frame, or 19<
*/
hPress(key) {
return this.isKeyPressed(key, 1) || this.hasBeenDownFor(key, 20)
}
/**
* Is key currently down
*/
isKeyDown(key) {
let keys = [...this.keysDown], f = false
keys.forEach(k => {
if (f) return;
if (k.split("||")[0] == key) f = true;
})
return f;
}
add(key) {
let keys = [...this.keysDown]
let names = keys.map(x => x.split("||")[0])
if (!names.includes(key.name))
keys.push(key.str())
this.keysDown = new Set(keys);
}
remove(key) {
let keys = [...this.keysDown], t = [...keys], r = []
t.forEach((x, i) => {
let kname = x.split("||")[0];
if (kname == key.name) {
if (kname in this.keysBound) {
let boundKey = this.keysBound[kname];
boundKey.forEach(ak => {
if (!this.isOnCooldown(kname) && ["up", "keyup"].includes(ak.type.toLowerCase())) {
ak.func();
if (ak.cooldown > 1) {
this.cooldown.push(new keysKeyCooldown(kname, ak.cooldown, ak.type));
if (this.logKeysDown) console.log(`${kname} has been put on cooldown for ${ak.cooldown} frames`);
}
}
})
}
keys.splice(i, 1)
r.push(x)
}
})
this.keysDown = new Set(keys);
}
/**
*
* @param {String} key KeyA, KeyW
* @param {Function} func Bound function
* @param {String} type keydown, down, keypress, press, keyup, up, keyhpress, hpress
*/
bindkey(key, func, type="down", cooldown=0) {
let place = this.keysBound[key];
if (place) {
let dirs = place.map(x => x.type);
if (dirs.includes(type)) {
let found = place.filter(x => x.type == type)[0];
place[place.indexOf(found)].func = func;
}
else
place.push(keysKeyBind.as(func, type, cooldown));
return;
}
this.keysBound[key] = [keysKeyBind.as(func, type, cooldown)];
}
unbindkey(key, type=null) {
if (type == null) delete this.keysBound[key];
else {
let foundTypes = this.keysBound[key].filter(x => x.type == type);
foundTypes.forEach(q => {
this.keysBound[key].splice(this.keysBound[key].indexOf(q), 1);
})
if (this.keysBound[key].length == 0) delete this.keysBound[key];
}
}
/**
*
* @param {String} key KeyA, KeyW (key.code)
* @param {String} type press, down, hpress
*/
isKeyActive(key, type="down") {
if (["press", "keypress"].includes(type.toLowerCase())) {
return this.isKeyPressed(key);
} else if (["hpress", "keyhpress"].includes(type.toLowerCase())) {
return this.hPress(key);
} else {
return this.isKeyDown(key);
}
}
isOnCooldown(key="KeyW") {
for (let i = 0; i < this.cooldown.length; i++) {
if (this.cooldown[i].key == key) return true;
}
return false;
}
handleCooldowns() {
let removeIndexes = [];
this.cooldown.forEach((x, i) => {
x.cooldown -= 1;
if (x.cooldown > 0) return;
removeIndexes.push(i);
});
removeIndexes.reverse().forEach(i => {
if (this.logKeysDown) console.log(`${this.cooldown[i].key} removed from cooldown list`);
this.cooldown.splice(i, 1);
});
}
lockAllKeys(except = []) {
if (!navigator.keyboard || !navigator.keyboard.lock) {
console.warn("Keyboard lock is not supported");
return 1;
}
let codes = [
..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map(x => "Key" + x),
..."0123456789".split("").map(x => "Digit" + x),
...Array.from({ length: 24 }).map((_, i) => "F" + (i + 1)),
"ShiftLeft", "ShiftRight", "ControlLeft", "ControlRight",
"AltLeft", "AltRight", "MetaLeft", "MetaRight",
"CapsLock", "Tab", "Escape", "Enter", "Space",
"ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"
];
navigator.keyboard.lock(codes.filter(x => !except.includes(x)));
}
update(id=0) {
if (id != this.updateID) return;
this.handleCooldowns();
let keys = [...this.keysDown].map(x => {
let y = x.split("||");
return new keysKey(y[0], parseInt(y[1]) + 1).str()
})
this.keysDown = new Set(keys);
keys.forEach(key => {
key = key.split("||")[0];
if (key in this.keysBound) {
let boundKey = this.keysBound[key];
boundKey.forEach(ak => {
if (ak.type.toLowerCase().includes("up")) return;
if (!this.isOnCooldown(key) && this.isKeyActive(key, ak.type)) {
ak.func();
if (ak.cooldown > 1) {
this.cooldown.push(new keysKeyCooldown(key, ak.cooldown, ak.type));
if (this.logKeysDown) console.log(`${key} has been put on cooldown for ${ak.cooldown} frames`);
}
}
})
}
})
if (this.logKeysDown) console.log(keys);
requestAnimationFrame(() => { this.update(id); });
}
}
class keysKeyBind {
/**
*
* @param {Function} func The function that runs
* @param {string} type keydown, down, keypress, press, keyup, up, keyhpress, hpress
* @param {Number} cooldown The cooldown between registering actions
*/
constructor(func=() => {}, type="keydown", cooldown=0) {
this.func = func;
this.type = type;
/** Time between registering as pressed in frames */
this.cooldown = cooldown;
}
static as(func, type="keydown", cooldown=0) {
return new keysKeyBind(func, type, cooldown);
}
}
class keysKeyCooldown {
constructor(key="", cooldown=0, type="down") {
this.key = key;
this.cooldown = cooldown;
this.type = type;
}
}
/**
* Put this in your Update() loop:
* @example keys.update()
*/
const keys = new keysClass();
keys.update(keys.updateID); // Starts the update cycle
document.addEventListener("keydown", function(k) { keys.add(new keysKey(k.code, 0)); })
document.addEventListener("keyup", function(k) { keys.remove(new keysKey(k.code)); })