feat(ttt): added concede detection and move timeout
This commit is contained in:
parent
350c5bf4fc
commit
43e6ec24f5
5 changed files with 109 additions and 67 deletions
|
|
@ -1,5 +1,6 @@
|
|||
// import type { TicTacToeData } from '@shared/database/mixin/tictactoe';
|
||||
|
||||
import { TicTacToeOutcome } from '@shared/database/mixin/tictactoe';
|
||||
import { UserId } from '@shared/database/mixin/user';
|
||||
|
||||
// Represents the possible states of a cell on the board.
|
||||
|
|
@ -7,53 +8,82 @@ import { UserId } from '@shared/database/mixin/user';
|
|||
type CellState = 'O' | 'X' | null
|
||||
|
||||
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;
|
||||
public board: CellState[] = Array(9).fill(null);
|
||||
private currentPlayer: 'O' | 'X' = 'X';
|
||||
|
||||
public gameUpdate: NodeJS.Timeout | null = null;
|
||||
|
||||
public lastMoveTime: number = -1;
|
||||
public lastSeenX: number = -1;
|
||||
public lastSeenO: number = -1;
|
||||
|
||||
private changePlayer() {
|
||||
this.currentPlayer = this.currentPlayer === 'X' ? 'O' : 'X';
|
||||
this.lastMoveTime = Date.now();
|
||||
}
|
||||
|
||||
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.
|
||||
public checkState(): 'winX' | 'winO' | 'draw' | 'ongoing' {
|
||||
const checkRow = (row: number): ('X' | 'O' | 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]; }
|
||||
return null;
|
||||
};
|
||||
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'; }
|
||||
}
|
||||
|
||||
const checkCol = (col: number): ('X' | 'O' | null) => {
|
||||
if (this.board[col] === null) return null;
|
||||
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'; }
|
||||
|
||||
if (this.board[col] === this.board[col + 3] && this.board[col + 3] === this.board[col + 6]) { return this.board[col]; }
|
||||
return null;
|
||||
};
|
||||
|
||||
const checkDiag = (): ('X' | 'O' | null) => {
|
||||
if (this.board[4] === null) return null;
|
||||
const checkRow = (row: number): ('X' | 'O' | 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]; }
|
||||
return null;
|
||||
};
|
||||
|
||||
if (this.board[0] === this.board[4] && this.board[4] === this.board[8]) { return this.board[4]; }
|
||||
const checkCol = (col: number): ('X' | 'O' | null) => {
|
||||
if (this.board[col] === null) return null;
|
||||
|
||||
if (this.board[2] === this.board[4] && this.board[4] === this.board[6]) { return this.board[4]; }
|
||||
if (this.board[col] === this.board[col + 3] && this.board[col + 3] === this.board[col + 6]) { return this.board[col]; }
|
||||
return null;
|
||||
};
|
||||
|
||||
const checkDiag = (): ('X' | 'O' | null) => {
|
||||
if (this.board[4] === null) return null;
|
||||
|
||||
if (this.board[0] === this.board[4] && this.board[4] === this.board[8]) { return this.board[4]; }
|
||||
|
||||
if (this.board[2] === this.board[4] && this.board[4] === this.board[6]) { return this.board[4]; }
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
const row = (checkRow(0) ?? checkRow(1)) ?? checkRow(2);
|
||||
const col = (checkCol(0) ?? checkCol(1)) ?? checkCol(2);
|
||||
const diag = checkDiag();
|
||||
|
||||
if (row !== null) return `win${row}`;
|
||||
if (col !== null) return `win${col}`;
|
||||
if (diag !== null) return `win${diag}`;
|
||||
|
||||
if (this.board.filter(c => c === null).length === 0) { return 'draw'; }
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
const row = (checkRow(0) ?? checkRow(1)) ?? checkRow(2);
|
||||
const col = (checkCol(0) ?? checkCol(1)) ?? checkCol(2);
|
||||
const diag = checkDiag();
|
||||
|
||||
if (row !== null) return `win${row}`;
|
||||
if (col !== null) return `win${col}`;
|
||||
if (diag !== null) return `win${diag}`;
|
||||
|
||||
if (this.board.filter(c => c === null).length === 0) { return 'draw'; }
|
||||
return 'ongoing';
|
||||
if (this.checkWinnerCache === null) {
|
||||
this.checkWinnerCache = real_func();
|
||||
}
|
||||
return this.checkWinnerCache;
|
||||
}
|
||||
|
||||
public reset(): void {
|
||||
|
|
@ -84,14 +114,19 @@ export class TTC {
|
|||
this.board[idx] = this.currentPlayer;
|
||||
this.changePlayer();
|
||||
|
||||
const result = this.checkState();
|
||||
const result = this.checkWinner();
|
||||
|
||||
if (result !== 'ongoing') {
|
||||
if (result !== null) {
|
||||
this.isGameOver = true;
|
||||
}
|
||||
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; };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export type GameUpdate = {
|
|||
|
||||
boardState: CellState[];
|
||||
currentPlayer: 'X' | 'O';
|
||||
gameState: 'winX' | 'winO' | 'draw' | 'ongoing';
|
||||
gameState: 'winX' | 'winO' | 'draw' | 'ongoing' | 'other';
|
||||
}
|
||||
|
||||
export type GameMove = {
|
||||
|
|
@ -26,6 +26,7 @@ export interface ClientToServer {
|
|||
dequeue: () => void;
|
||||
debugInfo: () => void;
|
||||
gameMove: (up: GameMove) => void;
|
||||
keepalive: () => void;
|
||||
connectedToGame: (gameId: string) => void;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { UserId } from '@shared/database/mixin/user';
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { GameMove, SSocket } from './socket';
|
||||
import { GameMove, GameUpdate, SSocket } from './socket';
|
||||
import { isNullish } from '@shared/utils';
|
||||
import { newUUID } from '@shared/utils/uuid';
|
||||
import { GameId } from '@shared/database/mixin/tictactoe';
|
||||
import { TTTGameId } from '@shared/database/mixin/tictactoe';
|
||||
import { TTC } from './game';
|
||||
|
||||
type TTTUser = {
|
||||
socket: SSocket,
|
||||
userId: UserId,
|
||||
windowId: string,
|
||||
updateInterval: NodeJS.Timeout,
|
||||
currentGame: GameId | null,
|
||||
socket: SSocket,
|
||||
userId: UserId,
|
||||
windowId: string,
|
||||
updateInterval: NodeJS.Timeout,
|
||||
currentGame: TTTGameId | null,
|
||||
}
|
||||
|
||||
export class StateI {
|
||||
|
|
@ -21,7 +21,7 @@ export class StateI {
|
|||
|
||||
private queueInterval: NodeJS.Timeout;
|
||||
|
||||
private games: Map<GameId, TTC> = new Map();
|
||||
private games: Map<TTTGameId, TTC> = new Map();
|
||||
|
||||
constructor(private fastify: FastifyInstance) {
|
||||
this.queueInterval = setInterval(() => this.queuerFunction());
|
||||
|
|
@ -50,6 +50,7 @@ export class StateI {
|
|||
socket.on('debugInfo', () => this.debugSocket(socket));
|
||||
|
||||
socket.on('gameMove', (e) => this.gameMove(socket, e));
|
||||
socket.on('keepalive', () => this.keepAlive(socket));
|
||||
if (socket) {
|
||||
console.log('Socket:', socket.id);
|
||||
}
|
||||
|
|
@ -75,14 +76,14 @@ export class StateI {
|
|||
this.queue.delete(id1);
|
||||
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 iState = {
|
||||
const iState: GameUpdate = {
|
||||
boardState: g.board,
|
||||
currentPlayer: g.getCurrentState(),
|
||||
playerX: g.playerX,
|
||||
playerO: g.playerO,
|
||||
gameState: g.checkState(),
|
||||
gameState: g.checkWinner() ?? 'ongoing',
|
||||
gameId: gameId,
|
||||
};
|
||||
|
||||
|
|
@ -96,9 +97,8 @@ export class StateI {
|
|||
g.gameUpdate = setInterval(() => {
|
||||
this.gameUpdate(gameId, u1.socket);
|
||||
this.gameUpdate(gameId, u2.socket);
|
||||
if (g.checkState() !== 'ongoing') {
|
||||
if (g.checkWinner() !== null) {
|
||||
this.cleanupGame(gameId, g);
|
||||
this.fastify.db.setTTTGameOutcome(gameId, u1.userId, u2.userId, g.checkState());
|
||||
}
|
||||
}, 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 {
|
||||
if (!this.users.has(socket.authUser.id)) return;
|
||||
|
||||
|
|
@ -119,7 +129,7 @@ export class StateI {
|
|||
this.queue.delete(socket.authUser.id);
|
||||
}
|
||||
|
||||
private cleanupGame(gameId: GameId, game: TTC): void {
|
||||
private cleanupGame(gameId: TTTGameId, game: TTC): void {
|
||||
clearInterval(game.gameUpdate ?? undefined);
|
||||
this.games.delete(gameId);
|
||||
let player: TTTUser | undefined;
|
||||
|
|
@ -131,6 +141,7 @@ export class StateI {
|
|||
player.currentGame = null;
|
||||
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
|
||||
}
|
||||
|
||||
|
|
@ -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;
|
||||
const user = this.users.get(socket.authUser.id)!;
|
||||
|
||||
|
|
@ -176,19 +187,20 @@ export class StateI {
|
|||
currentPlayer: games.getCurrentState(),
|
||||
playerX: games.playerX,
|
||||
playerO: games.playerO,
|
||||
gameState: games.checkState(),
|
||||
gameState: games.checkWinner() ?? 'ongoing',
|
||||
gameId: gameId,
|
||||
});
|
||||
}
|
||||
|
||||
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)!;
|
||||
|
||||
if (user.currentGame !== null && !this.games.has(user.currentGame)) return 'unknownError';
|
||||
const game = this.games.get(user.currentGame!)!;
|
||||
if (user.currentGame === null) return;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue