1
0
mirror of https://github.com/thib8956/tic-tac-toe-ws.git synced 2024-11-17 09:26:33 +00:00
tic-tac-toe-ws/server.mts

53 lines
1.3 KiB
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-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
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-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}));
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;
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-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
});