-
Notifications
You must be signed in to change notification settings - Fork 0
/
keypressed.js
47 lines (42 loc) · 1.46 KB
/
keypressed.js
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
// Name: Key Press Extension
// ID: keypressed
// Description: It has a reporter block reporting what key has been pressed, allowing for more supported keys and easier detection
// By: snowboyz0825 <https://scratch.mit.edu/users/Dat_Snow_Kid/>
// Mostly by chatGPT, I just added a few edits after training the chatbot to code extensions. I take no creative credit.
class KeyPressExtension {
constructor(runtime) {
this.runtime = runtime;
this.currentKey = null;
// Attach event listener for keydown and keyup events
document.addEventListener('keydown', this.handleKeyDown.bind(this));
document.addEventListener('keyup', this.handleKeyUp.bind(this));
}
getInfo() {
return {
id: 'keyPress',
name: 'Key Press Extension',
blocks: [
{
opcode: 'getCurrentKey',
blockType: Scratch.BlockType.REPORTER,
text: 'current key',
arguments: {},
},
],
};
}
getCurrentKey() {
return this.currentKey || 'No key pressed';
}
handleKeyDown(event) {
// Get the name of the pressed key
this.currentKey = event.key;
this.runtime.requestRedraw(); // Notify Scratch to update the block value
}
handleKeyUp() {
// Reset the currentKey when the key is released
this.currentKey = null;
this.runtime.requestRedraw(); // Notify Scratch to update the block value
}
}
Scratch.extensions.register(new KeyPressExtension());