1
0
mirror of https://github.com/thib8956/tic-tac-toe-ws.git synced 2025-02-22 16:58:14 +00:00

Implement click to reset at the end of game

This commit is contained in:
Thibaud Gasser 2025-01-24 16:19:16 +01:00
parent 797a32c00a
commit 6da3762502
3 changed files with 27 additions and 12 deletions

View File

@ -1,4 +1,4 @@
import { Request, Response, Message, Hello, EndGame } from "common.js";
import { Click, Update, Message, Hello, EndGame } from "common.js";
const CELL_SIZE = 150;
const GRID_SIZE = CELL_SIZE * 3;
@ -71,7 +71,7 @@ function handlePendingEvts(ws: WebSocket, gridOrigin: Point) {
const gridIndex = coordToGridIndex(gridOrigin, evt);
if (gridIndex) {
const [x, y] = gridIndex;
const msg: Request = { x, y };
const msg: Click = { x, y };
ws.send(JSON.stringify(msg));
}
}
@ -202,7 +202,7 @@ function init() {
break;
}
case "update": {
const res = msg.data as Response;
const res = msg.data as Update;
const { x, y } = res.last;
const shape: Shape = {
kind: res.last.symbol,
@ -217,17 +217,19 @@ function init() {
case "endgame": {
const issue = (msg.data as EndGame).issue;
switch (issue) {
case "win": canvasMsg = "you won"; break;
case "lose": canvasMsg = "you lose"; break;
case "draw": canvasMsg = "it's a draw!"; break;
case "win": canvasMsg = "You won!"; break;
case "lose": canvasMsg = "You lose!"; break;
case "draw": canvasMsg = "It's a draw!"; break;
default: throw new Error(`unexpected ${issue}`);
}
canvasMsg += " Click to reset";
break;
}
case "reset": {
canvasMsg = `Game reset... Id #${myId}, playing as ${mySymbol}`;
grid = new Array(9);
pendingEvts = [];
resizeCanvas(ctx);
break;
}
default: {

View File

@ -1,16 +1,16 @@
export type MessageKind = "hello" | "update" | "endgame" | "reset";
export type MessageKind = "click" | "hello" | "update" | "endgame" | "reset";
export interface Message {
kind: MessageKind,
data: Response | Hello | EndGame | Reset,
data: Click | Update | Hello | EndGame | Reset,
}
export interface Request {
export interface Click {
x: number,
y: number
}
export interface Response {
export interface Update {
last: { x: number, y: number, symbol: "x" | "o" }
}

View File

@ -1,4 +1,4 @@
import { Message, Response, Hello, EndGame } from "common.js"
import { Message, Update, Hello, EndGame } from "common.js"
import { WebSocket, WebSocketServer, MessageEvent } from "ws";
const port = 1234
@ -54,6 +54,19 @@ wss.on("connection", (ws, req) => {
currentPlayer = player;
}
if (endGame) {
console.log("player", currentPlayer!.id, "reset the game");
// reset game state
grid = [0, 0, 0, 0, 0, 0, 0, 0, 0];
currentPlayer = undefined;
endGame = false;
for (const c of clients) {
c.ws.send(JSON.stringify({
kind: "reset"
} as Message));
}
}
if (clients.length < 2 || player.id != currentPlayer?.id || endGame) {
return;
}
@ -65,7 +78,7 @@ wss.on("connection", (ws, req) => {
kind: "update",
data: {
last: { x, y, symbol: player.symbol }
} as Response,
} as Update,
}
c.ws.send(JSON.stringify(msg));
}