2024-09-04 12:25:37 +00:00
|
|
|
import { Message, Response } from "common.mjs"
|
|
|
|
import { WebSocket, WebSocketServer } from "ws";
|
2024-09-02 20:34:24 +00:00
|
|
|
|
|
|
|
const port = 1234
|
|
|
|
const wss = new WebSocketServer({ port });
|
|
|
|
|
2024-09-04 12:25:37 +00:00
|
|
|
let grid = [0, 0, 0, 0, 0, 0, 0, 0, 0]
|
|
|
|
|
2024-09-02 20:34:24 +00:00
|
|
|
console.log(`waiting for connection on ws://localhost:${port}`);
|
|
|
|
|
2024-09-03 12:07:13 +00:00
|
|
|
let id = -1;
|
2024-09-04 12:25:37 +00:00
|
|
|
let clients: WebSocket[] = [];
|
2024-09-03 12:07:13 +00:00
|
|
|
|
2024-09-04 12:25:37 +00:00
|
|
|
wss.on("connection", (ws) => {
|
|
|
|
id += 1;
|
|
|
|
if (id > 1) {
|
|
|
|
throw new Error("too many players");
|
|
|
|
}
|
2024-09-03 12:07:13 +00:00
|
|
|
|
2024-09-04 12:25:37 +00:00
|
|
|
clients.push(ws);
|
|
|
|
ws.send(JSON.stringify({kind: "hello", data: `player #${id} connected`} as any));
|
|
|
|
console.log(`player #${id} connected`);
|
2024-09-02 20:34:24 +00:00
|
|
|
|
|
|
|
ws.addEventListener("message", (event: any) => {
|
2024-09-04 12:25:37 +00:00
|
|
|
const message = JSON.parse(event.data);
|
|
|
|
const {x, y} = message;
|
|
|
|
const playerId = clients.indexOf(ws);
|
|
|
|
grid[y*3+x] = playerId + 1;
|
|
|
|
for (const c of clients) {
|
|
|
|
const msg: Message = {
|
|
|
|
kind: "update",
|
|
|
|
data: { grid } as Response,
|
|
|
|
}
|
|
|
|
c.send(JSON.stringify(msg));
|
|
|
|
}
|
2024-09-02 20:34:24 +00:00
|
|
|
});
|
|
|
|
});
|