1
0
mirror of https://github.com/thib8956/tic-tac-toe-ws.git synced 2024-09-28 21:56:38 +00:00

handle remote websocketserver and handle game reset by client

This commit is contained in:
Thibaud Gasser 2024-09-25 22:15:10 +02:00
parent 6a729cc7ad
commit c9157e83ef
3 changed files with 35 additions and 10 deletions

View File

@ -5,7 +5,11 @@ const GRID_SIZE = CELL_SIZE * 3;
const SHAPE_SIZE = 100;
const ANIMATE_DURATION = 500; // ms
const ws = new WebSocket("ws://localhost:1234");
let address = "ws://localhost:1234";
if (window.location.hostname !== "localhost") {
address = "wss://tic-tac-toe-ws-production.up.railway.app";
}
const ws = new WebSocket(address);
interface Point {
x: number;
@ -221,6 +225,12 @@ function init() {
}
break;
}
case "reset": {
canvasMsg = `Game reset... Id #${myId}, playing as ${mySymbol}`;
grid = new Array(9);
pendingEvts = [];
break;
}
default: {
console.warn("unhandled message kind:", msg.kind);
break;

View File

@ -1,8 +1,8 @@
export type MessageKind = "hello" | "update" | "endgame";
export type MessageKind = "hello" | "update" | "endgame" | "reset";
export interface Message {
kind: MessageKind,
data: Response | Hello | EndGame,
data: Response | Hello | EndGame | Reset,
}
export interface Request {
@ -11,7 +11,6 @@ export interface Request {
}
export interface Response {
grid: number[],
last: { x: number, y: number, symbol: "x" | "o" }
}
@ -23,3 +22,6 @@ export interface Hello {
export interface EndGame {
issue: "win" | "lose" | "draw"
}
type Reset = undefined;

View File

@ -19,6 +19,12 @@ let id = 1;
let clients: Client[] = [];
let currentPlayer: Client | undefined = undefined;
function getPlayerSymbol(): "o" | "x" {
console.assert(clients.length < 2, "there should never be more than 2 clients");
if (clients.length === 0) return "o";
return clients[0].symbol === "o" ? "x" : "o";
}
wss.on("connection", (ws) => {
id += 1;
if (clients.length == 2) {
@ -27,7 +33,7 @@ wss.on("connection", (ws) => {
return;
}
const symbol = clients.length == 0 ? "o" : "x";
const symbol = getPlayerSymbol();
const helloMsg: Message = {
kind: "hello",
data: { id, symbol } as Hello
@ -57,7 +63,6 @@ wss.on("connection", (ws) => {
const msg: Message = {
kind: "update",
data: {
grid,
last: { x, y, symbol: player.symbol }
} as Response,
}
@ -92,14 +97,22 @@ wss.on("connection", (ws) => {
kind: "endgame",
data: { issue: "lose" } as EndGame
} as Message));
endGame = true;
endGame = true;
}
}
});
ws.on("close", () => {
console.log(`player #${id} disconnected`);
clients = clients.filter(x => x.id !== id);
ws.on("close", (code: number) => {
console.log(`player disconnected. Resetting game. code: ${code}`);
clients = clients.filter(x => x.ws.readyState !== 3); // 3 == CLOSED
// reset game state
grid = [0, 0, 0, 0, 0, 0, 0, 0, 0]
currentPlayer = undefined;
for (const c of clients) {
c.ws.send(JSON.stringify({
kind: "reset"
} as Message));
}
});
});