diff --git a/src/games/gameHandler.ts b/src/games/gameHandler.ts index 4ac5a12..e167dc1 100644 --- a/src/games/gameHandler.ts +++ b/src/games/gameHandler.ts @@ -38,6 +38,7 @@ import { getUserTables } from '../database/queries'; import {HoldemBot} from './holdem/holdemBot'; +import {getPublicChatMessages, handlePublicChatMessage} from '../publicChat'; let playerIdIncrement = 0; const players = new Map(); @@ -341,6 +342,9 @@ class GameHandler implements GameHandlerInterface { } else if (table && table instanceof FiveCardDrawTable) { logger.info(`Player ${player.playerId} send chat message ${chatMsg} into table ${table.tableName}`); table.handleChatMessage(player.playerId, chatMsg) + } else if (tableId === -1) { + handlePublicChatMessage(players, player, chatMsg); + logger.info(`Player ${player.playerId} send public chat message ${chatMsg}`); } } break; @@ -354,6 +358,8 @@ class GameHandler implements GameHandlerInterface { table.getChatMessages(player.playerId); } else if (table && table instanceof FiveCardDrawTable) { table.getChatMessages(player.playerId); + } else if (tableId === -1) { + getPublicChatMessages(player); } } break; diff --git a/src/publicChat.ts b/src/publicChat.ts new file mode 100644 index 0000000..3444976 --- /dev/null +++ b/src/publicChat.ts @@ -0,0 +1,39 @@ +import {ChatMessage} from './types'; +import {ClientResponse} from './interfaces'; +import {SocketState} from './enums'; +import {Player} from './player'; +import WebSocket from 'ws'; + +const chatMessages: ChatMessage[] = []; +const chatMaxSize: number = 50; + +export function getPublicChatMessages(player: Player): void { + if (player && player.socket) { + const response: ClientResponse = { + key: 'getChatMessages', data: { + messages: [...chatMessages], + } + }; + if (player.socket.readyState === SocketState.OPEN) { + player.socket.send(JSON.stringify(response)); + } + } +} + +export function handlePublicChatMessage( + players: Map, player: Player, message: string +): void { + if (player) { + if (chatMessages.length >= chatMaxSize) { + chatMessages.shift(); + } + const newMessage: ChatMessage = {playerName: player.playerName, message}; + chatMessages.push(newMessage); + const response: ClientResponse = {key: 'chatMessage', data: {chatMessage: newMessage}}; + players.forEach((p: Player) => { + if (p.selectedTableId === -1 && p.socket && p.socket.readyState === SocketState.OPEN) { + p.socket.send(JSON.stringify(response)); + } + }); + } +}