Huge refactor of web-socket-handler
This commit is contained in:
parent
f68a8d152f
commit
10a4bd64d2
11 changed files with 333 additions and 510 deletions
|
|
@ -1,9 +1,9 @@
|
|||
import { GameInstance } from './game-instance';
|
||||
import { GomokuGame } from './game-instance';
|
||||
import { expect, test, describe } from 'bun:test';
|
||||
|
||||
describe('GameInstance', () => {
|
||||
test('should initialize with correct default state', () => {
|
||||
const game = new GameInstance();
|
||||
const game = new GomokuGame();
|
||||
|
||||
expect(game.id).toBeDefined();
|
||||
expect(game.board.length).toBe(15);
|
||||
|
|
@ -15,7 +15,7 @@ describe('GameInstance', () => {
|
|||
});
|
||||
|
||||
test('should add players correctly', () => {
|
||||
const game = new GameInstance();
|
||||
const game = new GomokuGame();
|
||||
|
||||
const player1 = 'player1-uuid';
|
||||
const player2 = 'player2-uuid';
|
||||
|
|
@ -36,7 +36,7 @@ describe('GameInstance', () => {
|
|||
});
|
||||
|
||||
test('should prevent more than two players from joining', () => {
|
||||
const game = new GameInstance();
|
||||
const game = new GomokuGame();
|
||||
|
||||
const player1 = 'player1-uuid';
|
||||
const player2 = 'player2-uuid';
|
||||
|
|
@ -56,7 +56,7 @@ describe('GameInstance', () => {
|
|||
});
|
||||
|
||||
test('should validate moves correctly', () => {
|
||||
const game = new GameInstance();
|
||||
const game = new GomokuGame();
|
||||
|
||||
const player1 = 'player1-uuid';
|
||||
const player2 = 'player2-uuid';
|
||||
|
|
@ -86,7 +86,7 @@ describe('GameInstance', () => {
|
|||
});
|
||||
|
||||
test('should detect win conditions', () => {
|
||||
const game = new GameInstance();
|
||||
const game = new GomokuGame();
|
||||
|
||||
const player1 = 'player1-uuid';
|
||||
const player2 = 'player2-uuid';
|
||||
|
|
@ -106,7 +106,7 @@ describe('GameInstance', () => {
|
|||
});
|
||||
|
||||
test('should detect draw condition', () => {
|
||||
const game = new GameInstance();
|
||||
const game = new GomokuGame();
|
||||
|
||||
const player1 = 'player1-uuid';
|
||||
const player2 = 'player2-uuid';
|
||||
|
|
|
|||
|
|
@ -1,89 +1,32 @@
|
|||
import { v4 as uuidv4 } from 'uuid';
|
||||
export type PlayerColor = 'black' | 'white';
|
||||
export type GameStatus = 'waiting' | 'playing' | 'finished';
|
||||
export type BoardCell = null | 'black' | 'white';
|
||||
|
||||
type PlayerColor = 'black' | 'white';
|
||||
type GameStatus = 'waiting' | 'playing' | 'finished';
|
||||
type BoardCell = null | 'black' | 'white';
|
||||
|
||||
export class GameInstance {
|
||||
public readonly id: string;
|
||||
export class GomokuGame {
|
||||
public readonly board: BoardCell[][];
|
||||
public currentPlayerColor: PlayerColor | null;
|
||||
public currentPlayerColor: null | PlayerColor;
|
||||
public status: GameStatus;
|
||||
public winnerColor: null | PlayerColor | 'draw';
|
||||
public players: { black?: string; white?: string };
|
||||
public history: { row: number, col: number }[];
|
||||
|
||||
private readonly boardSize = 15;
|
||||
private moveCount = 0;
|
||||
|
||||
constructor(id?: string) {
|
||||
this.id = id || uuidv4();
|
||||
constructor() {
|
||||
this.board = Array.from({ length: this.boardSize }, () =>
|
||||
Array(this.boardSize).fill(null),
|
||||
);
|
||||
this.currentPlayerColor = null;
|
||||
this.currentPlayerColor = 'black';
|
||||
this.status = 'waiting';
|
||||
this.winnerColor = null;
|
||||
this.players = {};
|
||||
}
|
||||
|
||||
public getCurrentPlayerId(): string | undefined {
|
||||
if (this.currentPlayerColor === 'black') {
|
||||
return this.players.black;
|
||||
} else {
|
||||
return this.players.white;
|
||||
}
|
||||
}
|
||||
|
||||
public getPlayerCount(): number {
|
||||
return Object.values(this.players).filter(Boolean).length;
|
||||
}
|
||||
|
||||
public addPlayer(playerId: string): boolean {
|
||||
// If game is full, prevent new players from joining.
|
||||
if (this.getPlayerCount() >= 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If player is already in the game, return true.
|
||||
if (Object.values(this.players).includes(playerId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Assign black if available, otherwise white
|
||||
if (!this.players.black) {
|
||||
this.players.black = playerId;
|
||||
} else if (!this.players.white) {
|
||||
this.players.white = playerId;
|
||||
} else {
|
||||
return false; // Should not happen if getPlayerCount() check is correct
|
||||
}
|
||||
|
||||
// If both players have joined, start the game.
|
||||
if (this.players.black && this.players.white) {
|
||||
this.currentPlayerColor = 'black';
|
||||
this.status = 'playing';
|
||||
}
|
||||
return true;
|
||||
this.history = [];
|
||||
}
|
||||
|
||||
public makeMove(
|
||||
playerId: string,
|
||||
playerColor: PlayerColor,
|
||||
row: number,
|
||||
col: number,
|
||||
): { success: boolean; error?: string } {
|
||||
// Find player's color
|
||||
let playerColor: PlayerColor | null = null;
|
||||
for (const [color, id] of Object.entries(this.players)) {
|
||||
if (id === playerId) {
|
||||
playerColor = color as PlayerColor;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!playerColor) {
|
||||
return { success: false, error: 'Player not in this game' };
|
||||
}
|
||||
|
||||
// Validate it's the player's turn
|
||||
if (this.currentPlayerColor !== playerColor) {
|
||||
return { success: false, error: 'Not your turn' };
|
||||
|
|
@ -103,6 +46,14 @@ export class GameInstance {
|
|||
this.board[row][col] = playerColor;
|
||||
this.moveCount++;
|
||||
|
||||
// If this was the first move, declare the game to have begun
|
||||
if (this.status === 'waiting') {
|
||||
this.status = 'playing';
|
||||
}
|
||||
|
||||
// Add the move to the game's history
|
||||
this.history.push({ row, col });
|
||||
|
||||
// Check for win condition
|
||||
if (this.checkWin(row, col, playerColor)) {
|
||||
this.winnerColor = playerColor;
|
||||
|
|
|
|||
37
src/index.ts
37
src/index.ts
|
|
@ -1,8 +1,9 @@
|
|||
import { Elysia, t } from 'elysia';
|
||||
import { html } from '@elysiajs/html';
|
||||
import { staticPlugin } from '@elysiajs/static';
|
||||
import { cookie } from '@elysiajs/cookie';
|
||||
import { WebSocketHandler } from './web-socket-handler';
|
||||
import { GameInstance } from './game/game-instance';
|
||||
import { GomokuGame } from './game/game-instance';
|
||||
|
||||
const wsHandler = new WebSocketHandler();
|
||||
|
||||
|
|
@ -14,21 +15,13 @@ const app = new Elysia()
|
|||
}),
|
||||
)
|
||||
.use(cookie())
|
||||
.use(html())
|
||||
.ws('/ws', {
|
||||
query: t.Object({
|
||||
gameId: t.String(),
|
||||
playerId: t.String(),
|
||||
}),
|
||||
open(ws) {
|
||||
const { gameId, playerId } = ws.data.query;
|
||||
if (!gameId || !playerId) {
|
||||
console.error(
|
||||
'WebSocket connection missing gameId or playerId in query params.',
|
||||
);
|
||||
ws.send('Error: missing gameId or playerId.');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
wsHandler.handleConnection(ws);
|
||||
},
|
||||
message(ws, message) {
|
||||
|
|
@ -55,30 +48,22 @@ const app = new Elysia()
|
|||
console.log(`Generated new playerId and set cookie: ${playerId}`);
|
||||
}
|
||||
|
||||
const urlGameId = query.gameId as string | undefined;
|
||||
let game: GameInstance;
|
||||
if (urlGameId) {
|
||||
let existingGame = wsHandler.getGame(urlGameId);
|
||||
if (existingGame) {
|
||||
game = existingGame;
|
||||
console.log(`Found existing game: ${urlGameId}`);
|
||||
} else {
|
||||
game = wsHandler.createGame(urlGameId);
|
||||
console.log(`Created new game with provided ID: ${urlGameId}`);
|
||||
let gameId = query.gameId as string | undefined;
|
||||
if (gameId) {
|
||||
if (!wsHandler.hasGame(gameId)) {
|
||||
wsHandler.createGame(gameId);
|
||||
console.log(`Created new game with provided ID: ${gameId}`);
|
||||
}
|
||||
} else {
|
||||
game = wsHandler.createGame();
|
||||
console.log(`Created new game without specific ID: ${game.id}`);
|
||||
gameId = wsHandler.createGame();
|
||||
console.log(`Created new game without specific ID: ${gameId}`);
|
||||
}
|
||||
|
||||
game.addPlayer(playerId);
|
||||
wsHandler.broadcastGameState(game.id);
|
||||
|
||||
const htmlTemplate = await Bun.file('./index.html').text();
|
||||
let finalHtml = htmlTemplate
|
||||
.replace(
|
||||
'<meta name="gameId" content="" />',
|
||||
`<meta name="gameId" content="${game.id}" />`,
|
||||
`<meta name="gameId" content="${gameId}" />`,
|
||||
)
|
||||
.replace(
|
||||
'<meta name="playerId" content="" />',
|
||||
|
|
|
|||
13
src/messages.ts
Normal file
13
src/messages.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
export interface Message {
|
||||
type: 'make_move' | 'resign';
|
||||
gameId: string;
|
||||
playerId: string;
|
||||
}
|
||||
|
||||
export interface MakeMoveMessage extends Message {
|
||||
row: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
export interface ResignationMessage extends Message {}
|
||||
|
||||
|
|
@ -1,17 +1,10 @@
|
|||
import { GameInstance } from '../game/game-instance';
|
||||
import { GomokuGame } from '../game/game-instance';
|
||||
|
||||
export function renderGameBoardHtml(
|
||||
game: GameInstance,
|
||||
playerId: string,
|
||||
game: GomokuGame,
|
||||
isPlayerToPlay: boolean,
|
||||
): string {
|
||||
let boardHtml = '<div id="game-board" class="game-board-grid">';
|
||||
|
||||
const currentPlayerColor =
|
||||
Object.entries(game.players).find(([_, id]) => id === playerId)?.[0] ||
|
||||
null;
|
||||
const isPlayersTurn =
|
||||
game.status === 'playing' && game.currentPlayerColor === currentPlayerColor;
|
||||
|
||||
for (let row = 0; row < game.board.length; row++) {
|
||||
for (let col = 0; col < game.board[row].length; col++) {
|
||||
const stone = game.board[row][col];
|
||||
|
|
@ -28,7 +21,7 @@ export function renderGameBoardHtml(
|
|||
const left = col * 30;
|
||||
|
||||
// HTMX attributes for making a move
|
||||
const wsAttrs = isPlayersTurn && !stone ? `ws-send="click"` : '';
|
||||
const wsAttrs = isPlayerToPlay && !stone ? `ws-send="click"` : '';
|
||||
|
||||
boardHtml += `
|
||||
<div
|
||||
|
|
@ -46,7 +39,3 @@ export function renderGameBoardHtml(
|
|||
boardHtml += `</div>`;
|
||||
return boardHtml;
|
||||
}
|
||||
|
||||
export function renderTitleBoxHtml(gameId: string, playerId: string): string {
|
||||
return `<div id="title-box">You are: ${playerId}<br/>Game ID: ${gameId}</div>`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,293 +0,0 @@
|
|||
import { ElysiaWS } from 'elysia/dist/ws';
|
||||
import { GameInstance } from './game/game-instance';
|
||||
import { renderGameBoardHtml } from './view/board-renderer';
|
||||
|
||||
interface MakeMoveMessage {
|
||||
gameId: string;
|
||||
playerId: string;
|
||||
row: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
type WS = ElysiaWS<{ query: { playerId: string; gameId: string } }>;
|
||||
export class WebSocketHandler {
|
||||
private connections: Map<string, Array<WS>>;
|
||||
private games: Map<string, GameInstance>;
|
||||
|
||||
constructor() {
|
||||
this.connections = new Map();
|
||||
this.games = new Map();
|
||||
}
|
||||
|
||||
public handleConnection(ws: WS): void {
|
||||
const { gameId, playerId } = ws.data.query;
|
||||
|
||||
if (!this.connections.has(gameId)) {
|
||||
this.connections.set(gameId, []);
|
||||
}
|
||||
this.connections.get(gameId)?.push(ws);
|
||||
|
||||
const game = this.getGame(gameId);
|
||||
if (game) {
|
||||
this.broadcastGameState(game.id);
|
||||
} else {
|
||||
ws.send('Error: game not found');
|
||||
ws.close();
|
||||
}
|
||||
|
||||
console.log(
|
||||
`WebSocket connected, registered for Game ${gameId} as Player ${playerId}`,
|
||||
);
|
||||
}
|
||||
|
||||
public handleMessage(ws: WS, message: any): void {
|
||||
const type: string = message.type;
|
||||
// Someday we might have other message types
|
||||
if (type === 'make_move') {
|
||||
this.handleMakeMove(ws, message as MakeMoveMessage);
|
||||
}
|
||||
}
|
||||
|
||||
private handleMakeMove(ws: WS, message: MakeMoveMessage): void {
|
||||
const { row, col } = message;
|
||||
const { gameId, playerId } = ws.data.query;
|
||||
console.log(
|
||||
`Handling make_move message in game ${gameId} from player ${playerId}: ${{ message }}`,
|
||||
);
|
||||
|
||||
if (!gameId || !playerId || row === undefined || col === undefined) {
|
||||
this.sendMessage(ws, 'Error: missing gameId, playerId, row, or col');
|
||||
return;
|
||||
}
|
||||
|
||||
const game = this.games.get(gameId);
|
||||
if (!game) {
|
||||
this.sendMessage(ws, 'Error: game not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const playerColor = Object.entries(game.players).find(
|
||||
([_, id]) => id === playerId,
|
||||
)?.[0] as ('black' | 'white') | undefined;
|
||||
if (!playerColor) {
|
||||
this.sendMessage(ws, 'Error: you are not a player in this game');
|
||||
return;
|
||||
}
|
||||
|
||||
if (game.currentPlayerColor !== playerColor) {
|
||||
this.sendMessage(ws, "Error: It's not your turn");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = game.makeMove(playerId, row, col);
|
||||
if (result.success) {
|
||||
this.broadcastGameState(game.id);
|
||||
console.log(
|
||||
`Move made in game ${game.id} by ${playerId}: (${row}, ${col})`,
|
||||
);
|
||||
} else {
|
||||
this.sendMessage(ws, result.error || 'Error: invalid move');
|
||||
}
|
||||
} catch (e: any) {
|
||||
this.sendMessage(ws, 'Error: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public handleDisconnect(ws: WS): void {
|
||||
const { gameId, playerId } = ws.data.query;
|
||||
|
||||
const connectionsInGame = this.connections.get(gameId);
|
||||
if (!connectionsInGame) {
|
||||
console.error(
|
||||
`Disconnecting WebSocket for player ${playerId} from game ${gameId}, but that game has no connections!`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.connections.set(
|
||||
gameId,
|
||||
connectionsInGame.filter(
|
||||
(conn) => conn.data.query.playerId !== ws.data.query.playerId,
|
||||
),
|
||||
);
|
||||
if (this.connections.get(gameId)?.length === 0) {
|
||||
this.connections.delete(gameId);
|
||||
}
|
||||
|
||||
if (this.connections.has(gameId)) {
|
||||
// Notify remaining players about disconnect
|
||||
this.sendMessageToGame(gameId, `${playerId} disconnected.`);
|
||||
}
|
||||
|
||||
this.sendTitleBoxesForGame(gameId);
|
||||
|
||||
console.log(`${playerId} disconnected from game ${gameId}`);
|
||||
}
|
||||
|
||||
public broadcastGameState(gameId: string): void {
|
||||
const game = this.games.get(gameId);
|
||||
if (!game) {
|
||||
console.warn(
|
||||
'Attempted to broadcast state of game ${gameId}, which is not loaded.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const connectionsToUpdate = this.connections.get(gameId);
|
||||
if (connectionsToUpdate) {
|
||||
connectionsToUpdate.forEach((ws) => {
|
||||
const { gameId, playerId } = ws.data.query;
|
||||
|
||||
const updatedBoardHtml = renderGameBoardHtml(game, playerId);
|
||||
ws.send(updatedBoardHtml);
|
||||
|
||||
if (game.status === 'finished') {
|
||||
if (game.winnerColor === 'draw') {
|
||||
this.sendMessageToGame(gameId, 'Game ended in draw.');
|
||||
} else if (game.winnerColor) {
|
||||
this.sendMessageToGame(
|
||||
gameId,
|
||||
`${game.winnerColor.toUpperCase()} wins!`,
|
||||
);
|
||||
}
|
||||
} else if (game.status === 'playing') {
|
||||
const clientPlayerColor = Object.entries(game.players).find(
|
||||
([_, id]) => id === playerId,
|
||||
)?.[0] as ('black' | 'white') | undefined;
|
||||
if (
|
||||
game.currentPlayerColor &&
|
||||
clientPlayerColor === game.currentPlayerColor
|
||||
) {
|
||||
this.sendMessage(ws, "It's your turn!");
|
||||
} else if (game.currentPlayerColor) {
|
||||
this.sendMessage(
|
||||
ws,
|
||||
`Waiting for ${game.currentPlayerColor}'s move.`,
|
||||
);
|
||||
}
|
||||
} else if (game.status === 'waiting') {
|
||||
this.sendMessage(ws, 'Waiting for another player...');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.log(`No connections to update for game ${gameId}.`);
|
||||
}
|
||||
|
||||
this.sendTitleBoxesForGame(gameId);
|
||||
}
|
||||
|
||||
public sendMessageToGame(gameId: string, message: string): void {
|
||||
const connections = this.connections.get(gameId);
|
||||
if (connections) {
|
||||
connections.forEach((ws) => {
|
||||
this.sendMessage(ws, message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public sendMessage(targetWs: WS, message: string): void {
|
||||
targetWs.send('<div id="messages">' + message + '</div>');
|
||||
}
|
||||
|
||||
private sendTitleBox(targetWs: WS, message: string): void {
|
||||
targetWs.send('<div id="title-box">' + message + '</div>');
|
||||
}
|
||||
|
||||
private sendTitleBoxesForGame(gameId: string): void {
|
||||
const game = this.games.get(gameId);
|
||||
if (!game) {
|
||||
console.error(
|
||||
`Tried to send title boxes for game ${gameId}, but it doesn't exist!`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const connections = this.connections.get(gameId);
|
||||
if (!connections) {
|
||||
console.log(
|
||||
`Attempted to send title boxes for game ${gameId}, but no players are connected.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
var message = '';
|
||||
switch (game.status) {
|
||||
case 'waiting': {
|
||||
message = 'Waiting for players...';
|
||||
break;
|
||||
}
|
||||
case 'playing': {
|
||||
const blackTag = game.players.black
|
||||
? this.playerTag(gameId, game.players.black)
|
||||
: 'Unknown';
|
||||
const whiteTag = game.players.white
|
||||
? this.playerTag(gameId, game.players.white)
|
||||
: 'Unknown';
|
||||
message = `${blackTag} vs ${whiteTag}`;
|
||||
break;
|
||||
}
|
||||
case 'finished': {
|
||||
switch (game.winnerColor) {
|
||||
case 'draw': {
|
||||
message = 'Game ended in draw.';
|
||||
break;
|
||||
}
|
||||
case 'black': {
|
||||
message = `${this.playerTag(gameId, game.players.black!)} wins!`;
|
||||
break;
|
||||
}
|
||||
case 'white': {
|
||||
message = `${this.playerTag(gameId, game.players.white!)} wins!`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
connections.forEach((connection) => {
|
||||
this.sendTitleBox(connection, message);
|
||||
});
|
||||
}
|
||||
|
||||
private playerTag(gameId: string, playerId: string) {
|
||||
// Determine whether the player is disconnected
|
||||
var connectionIcon = `<img src="/icons/disconnected.svg" alt="Disconnected" class="icon" />`;
|
||||
const connections = this.connections.get(gameId);
|
||||
if (connections) {
|
||||
connections.forEach((ws) => {
|
||||
if (ws.data.query.playerId === playerId) {
|
||||
console.log(`Connection exists for player ${playerId}`);
|
||||
connectionIcon = '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Set the correct name color for the player
|
||||
var colorClass = '';
|
||||
var turnClass = '';
|
||||
const game = this.games.get(gameId);
|
||||
if (game) {
|
||||
if (game.players.white === playerId) {
|
||||
colorClass = 'player-white';
|
||||
} else if (game.players.black === playerId) {
|
||||
colorClass = 'player-black';
|
||||
}
|
||||
if (game.getCurrentPlayerId() === playerId) {
|
||||
turnClass = 'player-to-play';
|
||||
}
|
||||
}
|
||||
const classes = `player-name ${colorClass} ${turnClass}`.trim();
|
||||
|
||||
return `<span class="${classes}">${playerId}${connectionIcon}</span>`;
|
||||
}
|
||||
|
||||
public getGame(gameId: string): GameInstance | undefined {
|
||||
return this.games.get(gameId);
|
||||
}
|
||||
|
||||
createGame(gameId?: string): GameInstance {
|
||||
const game = new GameInstance(gameId);
|
||||
this.games.set(game.id, game);
|
||||
return game;
|
||||
}
|
||||
}
|
||||
267
src/web-socket-handler.tsx
Normal file
267
src/web-socket-handler.tsx
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
import { ElysiaWS } from 'elysia/dist/ws';
|
||||
import { Html } from '@elysiajs/html';
|
||||
import { GomokuGame as GomokuGame, PlayerColor } from './game/game-instance';
|
||||
import { renderGameBoardHtml } from './view/board-renderer';
|
||||
import { Message, MakeMoveMessage, ResignationMessage } from './messages';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
type WS = ElysiaWS<{ query: { playerId: string; gameId: string } }>;
|
||||
|
||||
class PlayerConnection {
|
||||
id: string;
|
||||
name: string;
|
||||
ws: WS;
|
||||
|
||||
constructor(id: string, ws: WS) {
|
||||
this.id = id;
|
||||
this.name = id;
|
||||
this.ws = ws;
|
||||
}
|
||||
|
||||
public sendMessage(severity: 'info' | 'error', message: string) {
|
||||
// TODO
|
||||
}
|
||||
}
|
||||
|
||||
class GameServer {
|
||||
id: string;
|
||||
gomoku: GomokuGame;
|
||||
connections: Map<string, PlayerConnection>;
|
||||
blackPlayerId?: string;
|
||||
whitePlayerId?: string;
|
||||
|
||||
constructor(id: string) {
|
||||
this.id = id;
|
||||
this.gomoku = new GomokuGame();
|
||||
this.connections = new Map();
|
||||
}
|
||||
|
||||
public handleConnection(ws: WS) {
|
||||
const { playerId } = ws.data.query;
|
||||
const conn = new PlayerConnection(playerId, ws);
|
||||
this.connections.set(playerId, conn);
|
||||
console.log(`Created connection with player ${conn.id} in game ${this.id}`);
|
||||
|
||||
if (!this.blackPlayerId) {
|
||||
this.blackPlayerId = conn.id;
|
||||
} else if (!this.whitePlayerId) {
|
||||
this.whitePlayerId = conn.id;
|
||||
}
|
||||
if (this.whitePlayerId && this.blackPlayerId) {
|
||||
this.gomoku.status = 'playing';
|
||||
}
|
||||
|
||||
this.broadcastBoard();
|
||||
this.broadcastButtons();
|
||||
this.broadcastTitle();
|
||||
}
|
||||
|
||||
public handleDisconnect(ws: WS) {
|
||||
const { playerId } = ws.data.query;
|
||||
this.connections.delete(playerId);
|
||||
}
|
||||
|
||||
public broadcastBoard() {
|
||||
this.connections.forEach((conn: PlayerConnection) => this.broadcastBoardToPlayer(conn));
|
||||
}
|
||||
|
||||
public broadcastTitle() {
|
||||
this.connections.forEach((conn: PlayerConnection) => this.broadcastTitleToPlayer(conn));
|
||||
}
|
||||
|
||||
public broadcastButtons() {
|
||||
this.connections.forEach((conn: PlayerConnection) => this.broadcastButtonsToPlayer(conn));
|
||||
}
|
||||
|
||||
public broadcastBoardToPlayer(conn: PlayerConnection) {
|
||||
const isToPlay = this.gomoku.currentPlayerColor == this.getPlayerColor(conn);
|
||||
const updatedBoardHtml = renderGameBoardHtml(this.gomoku, isToPlay);
|
||||
conn.ws.send(updatedBoardHtml);
|
||||
console.log(`Sent board for game ${this.id} to player ${conn.id}`);
|
||||
}
|
||||
|
||||
public broadcastTitleToPlayer(conn: PlayerConnection) {
|
||||
let message = '';
|
||||
switch (this.gomoku.status) {
|
||||
case 'waiting': {
|
||||
message = 'Waiting for players...';
|
||||
break;
|
||||
}
|
||||
case 'playing': {
|
||||
const blackTag = this.playerTag(this.blackPlayerId!, 'black');
|
||||
const whiteTag = this.playerTag(this.whitePlayerId!, 'white');
|
||||
message = `${blackTag} vs ${whiteTag}`;
|
||||
break;
|
||||
}
|
||||
case 'finished': {
|
||||
switch (this.gomoku.winnerColor) {
|
||||
case 'draw': {
|
||||
message = 'Game ended in draw.';
|
||||
break;
|
||||
}
|
||||
case 'black': {
|
||||
const name = this.connections.get(this.blackPlayerId!)?.name;
|
||||
message = `${name} wins!`;
|
||||
break;
|
||||
}
|
||||
case 'white': {
|
||||
const name = this.connections.get(this.whitePlayerId!)?.name;
|
||||
message = `${name} wins!`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
conn.ws.send(<div id="title-box">{message}</div>);
|
||||
console.log(`Sent title for game ${this.id} to player ${conn.id}`);
|
||||
}
|
||||
|
||||
public broadcastButtonsToPlayer(conn: PlayerConnection) {
|
||||
// TODO
|
||||
console.log(`Sent buttons for game ${this.id} to player ${conn.id}`);
|
||||
}
|
||||
|
||||
private playerTag(playerId: string, color: PlayerColor) {
|
||||
const connectionIcon = this.connections.has(playerId) ? '' : `<img src="/icons/disconnected.svg" alt="Disconnected" class="icon" />`;
|
||||
var turnClass = (this.gomoku.currentPlayerColor === color) ? 'player-to-play' : ''
|
||||
const classes = `player-name ${'player-' + color} ${turnClass}`.trim();
|
||||
return (<span class={classes}>{playerId}{connectionIcon}</span>);
|
||||
}
|
||||
|
||||
public handleMessage(ws: WS, message: Message): void {
|
||||
const conn = this.connections.get(ws.data.query.playerId);
|
||||
if (!conn) {
|
||||
console.error(`Failed to handle message from player ${ws.data.query.playerId}, because they are not in the game ${this.id}, which it was routed to`);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.type) {
|
||||
case 'make_move': {
|
||||
this.handleMakeMove(conn, message as MakeMoveMessage);
|
||||
break;
|
||||
}
|
||||
case 'resign': {
|
||||
this.handleResignation(conn, message as ResignationMessage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getPlayerColor(conn: PlayerConnection): PlayerColor | undefined {
|
||||
if (this.blackPlayerId === conn.id) {
|
||||
return 'black';
|
||||
} else if (this.whitePlayerId === conn.id) {
|
||||
return 'white';
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private handleMakeMove(conn: PlayerConnection, message: MakeMoveMessage): void {
|
||||
console.log(
|
||||
`Handling make_move message in game ${this.id} from player ${conn.id}: ${{ message }}`,
|
||||
);
|
||||
const { row, col } = message;
|
||||
|
||||
var playerColor;
|
||||
if (this.blackPlayerId === conn.id) {
|
||||
playerColor = 'black';
|
||||
} else if (this.whitePlayerId == conn.id) {
|
||||
playerColor = 'white';
|
||||
} else {
|
||||
conn.sendMessage('error', 'You are not a player in this game, you cannot make a move!');
|
||||
return;
|
||||
}
|
||||
if (this.gomoku.currentPlayerColor !== playerColor) {
|
||||
conn.sendMessage('error', "It's not your turn");
|
||||
return;
|
||||
}
|
||||
|
||||
const stateBeforeMove = this.gomoku.status;
|
||||
const result = this.gomoku.makeMove(playerColor, row, col);
|
||||
console.log(result);
|
||||
if (result.success) {
|
||||
this.broadcastBoard();
|
||||
this.broadcastTitle();
|
||||
// We only need to re-send buttons when the game state changes
|
||||
if (stateBeforeMove != this.gomoku.status) {
|
||||
this.broadcastButtons();
|
||||
}
|
||||
console.log(
|
||||
`Move made in game ${this.id} by ${conn.id}: (${row}, ${col})`,
|
||||
);
|
||||
} else {
|
||||
conn.sendMessage('error', result.error!);
|
||||
}
|
||||
}
|
||||
|
||||
private handleResignation(conn: PlayerConnection, _message: ResignationMessage): void {
|
||||
// TODO
|
||||
}
|
||||
}
|
||||
|
||||
export class WebSocketHandler {
|
||||
private games: Map<String, GameServer>;
|
||||
|
||||
constructor() {
|
||||
this.games = new Map();
|
||||
}
|
||||
|
||||
public handleConnection(ws: WS): void {
|
||||
const { gameId } = ws.data.query;
|
||||
if (this.games.has(gameId)) {
|
||||
this.games.get(gameId)!.handleConnection(ws);
|
||||
} else {
|
||||
ws.send('Error: game not found');
|
||||
ws.close();
|
||||
}
|
||||
}
|
||||
|
||||
public handleDisconnect(ws: WS): void {
|
||||
const { gameId, playerId } = ws.data.query;
|
||||
|
||||
const game = this.games.get(gameId);
|
||||
if (!game) {
|
||||
console.error(`Attempted to disconnect player ${playerId} from game ${gameId}, which does not exist!`);
|
||||
return;
|
||||
}
|
||||
|
||||
game.handleDisconnect(ws);
|
||||
console.log(`${playerId} disconnected from game ${gameId}`);
|
||||
|
||||
if (game.connections.entries.length == 0) {
|
||||
this.games.delete(gameId);
|
||||
console.log(`Game ${gameId} has been deleted (empty).`);
|
||||
}
|
||||
}
|
||||
|
||||
public handleMessage(ws: WS, messageUnparsed: any) {
|
||||
let message = messageUnparsed as Message;
|
||||
if (!message) {
|
||||
console.log(`Received malformed message ${messageUnparsed} from player ${ws.data.query.playerId}.`);
|
||||
ws.send("Error: malformed message!");
|
||||
return;
|
||||
}
|
||||
|
||||
const { gameId } = ws.data.query;
|
||||
const gameServer = this.games.get(gameId);
|
||||
if (!gameServer) {
|
||||
console.error(`A WebSocket connection was left open for the non-existent game ${gameId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
gameServer.handleMessage(ws, message);
|
||||
}
|
||||
|
||||
public createGame(id?: string): string {
|
||||
const realId = id ? id : uuidv4();
|
||||
this.games.set(realId, new GameServer(realId));
|
||||
return realId;
|
||||
}
|
||||
|
||||
public hasGame(id: string): boolean {
|
||||
return this.games.has(id);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue