feat(ttt): added concede detection and move timeout

This commit is contained in:
Maieul BOYER 2026-01-07 20:44:23 +01:00 committed by Maix0
parent 350c5bf4fc
commit 43e6ec24f5
5 changed files with 109 additions and 67 deletions

View file

@ -1,4 +1,4 @@
import { type Socket } from 'socket.io-client'; import { Socket } from 'socket.io-client';
export type UpdateInfo = { export type UpdateInfo = {
inQueue: number, inQueue: number,
@ -14,7 +14,7 @@ export type GameUpdate = {
boardState: CellState[]; boardState: CellState[];
currentPlayer: 'X' | 'O'; currentPlayer: 'X' | 'O';
gameState: 'winX' | 'winO' | 'concededX' | 'concededO' | 'draw' | 'ongoing'; gameState: 'winX' | 'winO' | 'draw' | 'ongoing' | 'other';
} }
export type GameMove = { export type GameMove = {
@ -26,6 +26,7 @@ export interface ClientToServer {
dequeue: () => void; dequeue: () => void;
debugInfo: () => void; debugInfo: () => void;
gameMove: (up: GameMove) => void; gameMove: (up: GameMove) => void;
keepalive: () => void;
connectedToGame: (gameId: string) => void; connectedToGame: (gameId: string) => void;
}; };

View file

@ -10,17 +10,22 @@ import { updateUser } from "@app/auth";
declare module 'ft_state' { declare module 'ft_state' {
interface State { interface State {
tttSock?: Socket; tttSock?: Socket;
keepAliveInterval?: ReturnType<typeof setInterval>;
} }
} }
document.addEventListener("ft:pageChange", () => { document.addEventListener("ft:pageChange", () => {
if (window.__state.tttSock !== undefined) window.__state.tttSock.close(); if (window.__state.tttSock !== undefined) window.__state.tttSock.close();
if (window.__state.keepAliveInterval !== undefined) clearInterval(window.__state.keepAliveInterval);
window.__state.tttSock = undefined; window.__state.tttSock = undefined;
window.__state.keepAliveInterval = undefined;
}); });
export function getSocket(): Socket { export function getSocket(): Socket {
if (window.__state.tttSock === undefined) if (window.__state.tttSock === undefined)
window.__state.tttSock = io(window.location.host, { path: "/api/ttt/socket.io/" }) as any as Socket; window.__state.tttSock = io(window.location.host, { path: "/api/ttt/socket.io/" }) as any as Socket;
if (window.__state.keepAliveInterval === undefined)
window.__state.keepAliveInterval = setInterval(() => window.__state.tttSock?.emit('keepalive'), 100);
return window.__state.tttSock; return window.__state.tttSock;
} }
@ -63,15 +68,6 @@ async function handleTTT(): Promise<RouteHandlerReturn> {
if (type === 'draw') { if (type === 'draw') {
showWarn('It\'s a draw !') showWarn('It\'s a draw !')
} }
// if the other player conceded, switch the side so you won
if (type === 'conceded') {
player = player === 'X' ? 'O' : 'X';
const youWin = (curGame?.playerX === user.id);
if (youWin)
showSuccess('The other player Conceded !');
else
showError('You Conceded :(');
}
if (type === 'win') { if (type === 'win') {
let youWin: boolean; let youWin: boolean;
@ -98,6 +94,7 @@ async function handleTTT(): Promise<RouteHandlerReturn> {
showInfo('Game is finished, enqueuing directly') showInfo('Game is finished, enqueuing directly')
}) })
socket.on('gameBoard', (u) => { socket.on('gameBoard', (u) => {
if (curGame === null) { if (curGame === null) {
return showError('Got game State, but no in a game ?'); return showError('Got game State, but no in a game ?');
@ -114,11 +111,7 @@ async function handleTTT(): Promise<RouteHandlerReturn> {
case 'winO': case 'winO':
makeEnd('win', u.gameState[3] as 'X' | 'O'); makeEnd('win', u.gameState[3] as 'X' | 'O');
break; break;
case 'concededX': default:
case 'concededO':
makeEnd('conceded', u.gameState[8] as 'X' | 'O');
break;
case 'draw':
makeEnd('draw', 'X'); makeEnd('draw', 'X');
break; break;
} }

View file

@ -1,5 +1,6 @@
// import type { TicTacToeData } from '@shared/database/mixin/tictactoe'; // import type { TicTacToeData } from '@shared/database/mixin/tictactoe';
import { TicTacToeOutcome } from '@shared/database/mixin/tictactoe';
import { UserId } from '@shared/database/mixin/user'; import { UserId } from '@shared/database/mixin/user';
// Represents the possible states of a cell on the board. // Represents the possible states of a cell on the board.
@ -7,20 +8,42 @@ import { UserId } from '@shared/database/mixin/user';
type CellState = 'O' | 'X' | null type CellState = 'O' | 'X' | null
export class TTC { export class TTC {
// 30s
public static readonly TIMEOUT_INMOVE: number = 30 * 1000;
// 1.5s
public static readonly TIMEOUT_KEEPALIVE: number = 1.5 * 1000;
private isGameOver: boolean = false; private isGameOver: boolean = false;
public board: CellState[] = Array(9).fill(null); public board: CellState[] = Array(9).fill(null);
private currentPlayer: 'O' | 'X' = 'X'; private currentPlayer: 'O' | 'X' = 'X';
public gameUpdate: NodeJS.Timeout | null = null; public gameUpdate: NodeJS.Timeout | null = null;
public lastMoveTime: number = -1;
public lastSeenX: number = -1;
public lastSeenO: number = -1;
private changePlayer() { private changePlayer() {
this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X'; this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X';
this.lastMoveTime = Date.now();
} }
public constructor(public readonly playerX: UserId, public readonly playerO: UserId) { } public constructor(public readonly playerX: UserId, public readonly playerO: UserId) { }
private checkWinnerCache: TicTacToeOutcome | null = null;
// Analyzes the current board to determine if the game has ended. // Analyzes the current board to determine if the game has ended.
public checkState(): 'winX' | 'winO' | 'draw' | 'ongoing' { public checkWinner(): TicTacToeOutcome | null {
const real_func = (): (TicTacToeOutcome | null) => {
if (this.lastMoveTime !== -1 && Date.now() - this.lastMoveTime > TTC.TIMEOUT_INMOVE) {
if (this.currentPlayer === 'X') { return 'winO'; }
else { return 'winX'; }
}
if (this.lastSeenX !== -1 && Date.now() - this.lastSeenX > TTC.TIMEOUT_KEEPALIVE) { return 'winO'; }
if (this.lastSeenO !== -1 && Date.now() - this.lastSeenO > TTC.TIMEOUT_KEEPALIVE) { return 'winX'; }
const checkRow = (row: number): ('X' | 'O' | null) => { const checkRow = (row: number): ('X' | 'O' | null) => {
if (this.board[row * 3] === null) { return null; } if (this.board[row * 3] === null) { return null; }
if (this.board[row * 3] === this.board[row * 3 + 1] && this.board[row * 3 + 1] === this.board[row * 3 + 2]) { return this.board[row * 3]; } if (this.board[row * 3] === this.board[row * 3 + 1] && this.board[row * 3 + 1] === this.board[row * 3 + 2]) { return this.board[row * 3]; }
@ -53,7 +76,14 @@ export class TTC {
if (diag !== null) return `win${diag}`; if (diag !== null) return `win${diag}`;
if (this.board.filter(c => c === null).length === 0) { return 'draw'; } if (this.board.filter(c => c === null).length === 0) { return 'draw'; }
return 'ongoing'; return null;
};
if (this.checkWinnerCache === null) {
this.checkWinnerCache = real_func();
}
return this.checkWinnerCache;
} }
public reset(): void { public reset(): void {
@ -84,14 +114,19 @@ export class TTC {
this.board[idx] = this.currentPlayer; this.board[idx] = this.currentPlayer;
this.changePlayer(); this.changePlayer();
const result = this.checkState(); const result = this.checkWinner();
if (result !== 'ongoing') { if (result !== null) {
this.isGameOver = true; this.isGameOver = true;
} }
return 'success'; return 'success';
} }
public updateKeepAlive(user: UserId) {
if (user === this.playerX) { this.lastSeenX = Date.now(); }
if (user === this.playerO) { this.lastSeenO = Date.now(); }
}
getCurrentState(): 'X' | 'O' { return this.currentPlayer; }; getCurrentState(): 'X' | 'O' { return this.currentPlayer; };
} }

View file

@ -14,7 +14,7 @@ export type GameUpdate = {
boardState: CellState[]; boardState: CellState[];
currentPlayer: 'X' | 'O'; currentPlayer: 'X' | 'O';
gameState: 'winX' | 'winO' | 'draw' | 'ongoing'; gameState: 'winX' | 'winO' | 'draw' | 'ongoing' | 'other';
} }
export type GameMove = { export type GameMove = {
@ -26,6 +26,7 @@ export interface ClientToServer {
dequeue: () => void; dequeue: () => void;
debugInfo: () => void; debugInfo: () => void;
gameMove: (up: GameMove) => void; gameMove: (up: GameMove) => void;
keepalive: () => void;
connectedToGame: (gameId: string) => void; connectedToGame: (gameId: string) => void;
}; };

View file

@ -1,9 +1,9 @@
import { UserId } from '@shared/database/mixin/user'; import { UserId } from '@shared/database/mixin/user';
import { FastifyInstance } from 'fastify'; import { FastifyInstance } from 'fastify';
import { GameMove, SSocket } from './socket'; import { GameMove, GameUpdate, SSocket } from './socket';
import { isNullish } from '@shared/utils'; import { isNullish } from '@shared/utils';
import { newUUID } from '@shared/utils/uuid'; import { newUUID } from '@shared/utils/uuid';
import { GameId } from '@shared/database/mixin/tictactoe'; import { TTTGameId } from '@shared/database/mixin/tictactoe';
import { TTC } from './game'; import { TTC } from './game';
type TTTUser = { type TTTUser = {
@ -11,7 +11,7 @@ type TTTUser = {
userId: UserId, userId: UserId,
windowId: string, windowId: string,
updateInterval: NodeJS.Timeout, updateInterval: NodeJS.Timeout,
currentGame: GameId | null, currentGame: TTTGameId | null,
} }
export class StateI { export class StateI {
@ -21,7 +21,7 @@ export class StateI {
private queueInterval: NodeJS.Timeout; private queueInterval: NodeJS.Timeout;
private games: Map<GameId, TTC> = new Map(); private games: Map<TTTGameId, TTC> = new Map();
constructor(private fastify: FastifyInstance) { constructor(private fastify: FastifyInstance) {
this.queueInterval = setInterval(() => this.queuerFunction()); this.queueInterval = setInterval(() => this.queuerFunction());
@ -50,6 +50,7 @@ export class StateI {
socket.on('debugInfo', () => this.debugSocket(socket)); socket.on('debugInfo', () => this.debugSocket(socket));
socket.on('gameMove', (e) => this.gameMove(socket, e)); socket.on('gameMove', (e) => this.gameMove(socket, e));
socket.on('keepalive', () => this.keepAlive(socket));
if (socket) { if (socket) {
console.log('Socket:', socket.id); console.log('Socket:', socket.id);
} }
@ -75,14 +76,14 @@ export class StateI {
this.queue.delete(id1); this.queue.delete(id1);
this.queue.delete(id2); this.queue.delete(id2);
const gameId = newUUID() as unknown as GameId; const gameId = newUUID() as TTTGameId;
const g = new TTC(u1.userId, u2.userId); const g = new TTC(u1.userId, u2.userId);
const iState = { const iState: GameUpdate = {
boardState: g.board, boardState: g.board,
currentPlayer: g.getCurrentState(), currentPlayer: g.getCurrentState(),
playerX: g.playerX, playerX: g.playerX,
playerO: g.playerO, playerO: g.playerO,
gameState: g.checkState(), gameState: g.checkWinner() ?? 'ongoing',
gameId: gameId, gameId: gameId,
}; };
@ -96,9 +97,8 @@ export class StateI {
g.gameUpdate = setInterval(() => { g.gameUpdate = setInterval(() => {
this.gameUpdate(gameId, u1.socket); this.gameUpdate(gameId, u1.socket);
this.gameUpdate(gameId, u2.socket); this.gameUpdate(gameId, u2.socket);
if (g.checkState() !== 'ongoing') { if (g.checkWinner() !== null) {
this.cleanupGame(gameId, g); this.cleanupGame(gameId, g);
this.fastify.db.setTTTGameOutcome(gameId, u1.userId, u2.userId, g.checkState());
} }
}, 100); }, 100);
} }
@ -111,6 +111,16 @@ export class StateI {
}); });
} }
private keepAlive(socket: SSocket): void {
const user = this.users.get(socket.authUser.id);
if (isNullish(user)) { return; }
if (isNullish(user.currentGame)) { return; }
const game = this.games.get(user.currentGame);
if (isNullish(game)) { return; }
game.updateKeepAlive(user.userId);
}
private cleanupUser(socket: SSocket): void { private cleanupUser(socket: SSocket): void {
if (!this.users.has(socket.authUser.id)) return; if (!this.users.has(socket.authUser.id)) return;
@ -119,7 +129,7 @@ export class StateI {
this.queue.delete(socket.authUser.id); this.queue.delete(socket.authUser.id);
} }
private cleanupGame(gameId: GameId, game: TTC): void { private cleanupGame(gameId: TTTGameId, game: TTC): void {
clearInterval(game.gameUpdate ?? undefined); clearInterval(game.gameUpdate ?? undefined);
this.games.delete(gameId); this.games.delete(gameId);
let player: TTTUser | undefined; let player: TTTUser | undefined;
@ -131,6 +141,7 @@ export class StateI {
player.currentGame = null; player.currentGame = null;
player.socket.emit('gameEnd'); player.socket.emit('gameEnd');
} }
this.fastify.db.setTTTGameOutcome(gameId, game.playerX, game.playerO, game.checkWinner() ?? 'draw');
// do something here with the game result before deleting the game at the end // do something here with the game result before deleting the game at the end
} }
@ -163,7 +174,7 @@ export class StateI {
})); }));
} }
private gameUpdate(gameId: GameId, socket: SSocket): void { private gameUpdate(gameId: TTTGameId, socket: SSocket): void {
if (!this.users.has(socket.authUser.id)) return; if (!this.users.has(socket.authUser.id)) return;
const user = this.users.get(socket.authUser.id)!; const user = this.users.get(socket.authUser.id)!;
@ -176,19 +187,20 @@ export class StateI {
currentPlayer: games.getCurrentState(), currentPlayer: games.getCurrentState(),
playerX: games.playerX, playerX: games.playerX,
playerO: games.playerO, playerO: games.playerO,
gameState: games.checkState(), gameState: games.checkWinner() ?? 'ongoing',
gameId: gameId, gameId: gameId,
}); });
} }
private gameMove(socket: SSocket, update: GameMove) { private gameMove(socket: SSocket, update: GameMove) {
if (!this.users.has(socket.authUser.id)) return 'unknownError'; if (!this.users.has(socket.authUser.id)) return;
const user = this.users.get(socket.authUser.id)!; const user = this.users.get(socket.authUser.id)!;
if (user.currentGame !== null && !this.games.has(user.currentGame)) return 'unknownError'; if (user.currentGame === null) return;
const game = this.games.get(user.currentGame!)!; if (!this.games.has(user.currentGame)) return;
const game = this.games.get(user.currentGame)!;
game.makeMove(socket.authUser.id, update.index); game?.makeMove(socket.authUser.id, update.index);
} }
} }