1
0
mirror of https://github.com/thib8956/tic-tac-toe-ws.git synced 2024-09-29 06:06:37 +00:00
tic-tac-toe-ws/server.mts

38 lines
1005 B
TypeScript
Raw Normal View History

2024-09-08 10:05:02 +00:00
import { Message, Response, Hello } from "common.mjs"
import { WebSocket, WebSocketServer } from "ws";
2024-09-02 20:34:24 +00:00
const port = 1234
const wss = new WebSocketServer({ port });
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;
let clients: WebSocket[] = [];
2024-09-03 12:07:13 +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
clients.push(ws);
2024-09-08 10:05:02 +00:00
ws.send(JSON.stringify({kind: "hello", data: { id } as Hello}));
console.log(`player #${id} connected`);
2024-09-02 20:34:24 +00:00
ws.addEventListener("message", (event: any) => {
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
});
});