2024-09-08 10:05:02 +00:00
|
|
|
import { Message, Response, Hello } from "common.mjs"
|
2024-09-04 12:25:37 +00:00
|
|
|
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-08 10:58:00 +00:00
|
|
|
interface Client {
|
|
|
|
id: number,
|
|
|
|
ws: WebSocket
|
|
|
|
}
|
|
|
|
|
|
|
|
let id = 1;
|
|
|
|
let clients: Client[] = [];
|
2024-09-03 12:07:13 +00:00
|
|
|
|
2024-09-04 12:25:37 +00:00
|
|
|
wss.on("connection", (ws) => {
|
|
|
|
id += 1;
|
2024-09-08 10:58:00 +00:00
|
|
|
if (clients.length == 2) {
|
|
|
|
console.log("too many players");
|
|
|
|
ws.close();
|
|
|
|
return;
|
2024-09-04 12:25:37 +00:00
|
|
|
}
|
2024-09-03 12:07:13 +00:00
|
|
|
|
2024-09-08 10:58:00 +00:00
|
|
|
clients.push({id, ws});
|
2024-09-08 10:05:02 +00:00
|
|
|
ws.send(JSON.stringify({kind: "hello", data: { id } as Hello}));
|
2024-09-04 12:25:37 +00:00
|
|
|
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;
|
2024-09-08 10:58:00 +00:00
|
|
|
const playerId = clients.find(x => x.ws === ws)?.id;
|
|
|
|
console.assert(playerId);
|
|
|
|
if (grid[y*3+x] === 0) {
|
|
|
|
grid[y*3+x] = playerId as number;
|
|
|
|
for (const c of clients) {
|
|
|
|
const msg: Message = {
|
|
|
|
kind: "update",
|
|
|
|
data: { grid } as Response,
|
|
|
|
}
|
|
|
|
c.ws.send(JSON.stringify(msg));
|
2024-09-04 12:25:37 +00:00
|
|
|
}
|
|
|
|
}
|
2024-09-02 20:34:24 +00:00
|
|
|
});
|
2024-09-08 10:58:00 +00:00
|
|
|
|
|
|
|
ws.on("close", () => {
|
|
|
|
console.log(`player #${id} disconnected`);
|
|
|
|
clients = clients.filter(x => x.id !== id);
|
|
|
|
});
|
2024-09-02 20:34:24 +00:00
|
|
|
});
|