mirror of
https://github.com/thib8956/tic-tac-toe-ws.git
synced 2024-11-17 01:16:33 +00:00
Implement base of tic tac toe game
This commit is contained in:
parent
ad265f4011
commit
5ccbdb3194
42
client.mts
42
client.mts
@ -1,7 +1,45 @@
|
||||
const ws = new WebSocket("ws://localhost:1234");
|
||||
|
||||
ws.onopen = (e) => {
|
||||
console.log("connected to server");
|
||||
ws.send("hello");
|
||||
console.log("connected to server");
|
||||
|
||||
const canvas = document.getElementById("game") as HTMLCanvasElement | null;
|
||||
|
||||
if (canvas) {
|
||||
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;
|
||||
if (ctx) {
|
||||
drawGrid(ctx);
|
||||
|
||||
canvas.addEventListener("click", (evt: any) => {
|
||||
const {clientX, clientY} = evt;
|
||||
const x = Math.floor(clientX / 90);
|
||||
const y = Math.floor(clientY / 90);
|
||||
if (x < 3 && y < 3) {
|
||||
const rx = x + x * 100;
|
||||
const ry = y + y * 100;
|
||||
ctx.fillStyle = "red";
|
||||
ctx.fillRect(rx, ry, 90, 90);
|
||||
|
||||
ws.send(JSON.stringify({x, y}));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ws.onmessage = (evt) => {
|
||||
console.log(evt.data);
|
||||
};
|
||||
|
||||
|
||||
function drawGrid(ctx: CanvasRenderingContext2D){
|
||||
for (let y = 0; y < 3; ++y) {
|
||||
for (let x = 0; x < 3; ++x) {
|
||||
ctx.fillStyle = "green";
|
||||
const rx = x + x * 100;
|
||||
const ry = y + y * 100;
|
||||
ctx.fillRect(rx, ry, 90, 90);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -3,6 +3,8 @@
|
||||
<head>
|
||||
<title>Hello websockets</title>
|
||||
</head>
|
||||
<body></body>
|
||||
<body>
|
||||
<canvas id="game" width=800 height=600></canvas>
|
||||
</body>
|
||||
<script type="module" src="client.mjs"></script>
|
||||
</html>
|
||||
|
18
server.mts
18
server.mts
@ -5,13 +5,27 @@ const wss = new WebSocketServer({ port });
|
||||
|
||||
console.log(`waiting for connection on ws://localhost:${port}`);
|
||||
|
||||
let id = -1;
|
||||
let clients = [];
|
||||
|
||||
wss.on("connection", (ws, req) => {
|
||||
console.log(`${req.socket.remoteAddress} connected`);
|
||||
id += 1;
|
||||
if (id > 1) {
|
||||
throw new Error("too many players");
|
||||
}
|
||||
|
||||
clients.push(ws);
|
||||
ws.send("bonjour" + id);
|
||||
console.log(`player #${id} connected`);
|
||||
|
||||
ws.addEventListener("message", (event: any) => {
|
||||
//const message = JSON.parse(event.data.toString());
|
||||
const message = event.data.toString();
|
||||
console.log(`message from client : ${message}`);
|
||||
if (id == 0) {
|
||||
clients[1].send("coucou");
|
||||
} else {
|
||||
clients[0].send("coucou");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user