-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
107 lines (87 loc) · 2.52 KB
/
index.js
File metadata and controls
107 lines (87 loc) · 2.52 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
// index.js
const WebSocket = require("ws");
const { spawn } = require("child_process");
// this is for tetris.com
const moveToKey = {
"R": "up", // rotate
"R'": "space", // piece down
"L": "space", // piece down
"L'": "up", // rotate
"U": "left", // move left
"U'": "right", // move right
"D": "z", // whatever z does
"D'": "c", // hold
};
function pressKey(key) {
let script;
switch (key) {
// normal character keys
case "z":
case "c":
script = `tell application "System Events" to keystroke "${key}"`;
break;
// spacebar (key code 49)
case "space":
script = `tell application "System Events" to key code 49`;
break;
// left shift (key code 56)
case "shift":
script = `tell application "System Events" to key code 56`;
break;
case "up":
script = `tell application "System Events" to key code 126`;
break;
case "down":
script = `tell application "System Events" to key code 125`;
break;
case "left":
script = `tell application "System Events" to key code 123`;
break;
case "right":
script = `tell application "System Events" to key code 124`;
break;
default:
console.log("[pressKey] No script for key", key);
return;
}
console.log("[pressKey] Running:", script);
const child = spawn("osascript", ["-e", script]);
child.stdout.on("data", (data) => {
console.log("[osascript stdout]", data.toString());
});
child.stderr.on("data", (data) => {
console.error("[osascript stderr]", data.toString());
});
child.on("close", (code) => {
console.log("[osascript] exited with code", code);
});
child.on("error", (err) => {
console.error("[osascript error]", err);
});
}
const wss = new WebSocket.Server({ port: 8081 });
console.log("WebSocket server listening on ws://localhost:8081");
wss.on("connection", (ws) => {
console.log("[ws] Browser connected");
ws.on("message", (msg) => {
const raw = msg.toString();
console.log("[ws] got message:", JSON.stringify(raw));
const trimmed = raw.trim();
let key = moveToKey[trimmed];
if (!key && trimmed.startsWith("MOVE:")) {
const move = trimmed.slice("MOVE:".length);
key = moveToKey[move];
}
if (!key) {
console.log("[ws] no key mapped for", trimmed);
return;
}
pressKey(key);
});
ws.on("close", () => {
console.log("[ws] Browser disconnected");
});
ws.on("error", (err) => {
console.error("[ws] error:", err);
});
});