Files
liars-bar-game/server/game/room.js
T

113 lines
2.4 KiB
JavaScript

const { v4: uuidv4 } = require('uuid');
const GameEngine = require('./engine');
class RoomManager {
constructor() {
this.rooms = new Map();
}
// 建立房間
createRoom(hostId) {
const roomId = uuidv4().substring(0, 8);
const room = {
id: roomId,
hostId,
players: [hostId],
engine: null,
gameState: null,
status: 'waiting', // waiting, playing, ended
maxPlayers: 4, // 20 張牌 ÷ 5 張 = 最多 4 人
minPlayers: 2
};
this.rooms.set(roomId, room);
return room;
}
// 加入房間
joinRoom(roomId, playerId) {
const room = this.rooms.get(roomId);
if (!room) {
return { error: '房間不存在' };
}
if (room.status !== 'waiting') {
return { error: '遊戲已開始,無法加入' };
}
if (room.players.length >= room.maxPlayers) {
return { error: '房間已滿' };
}
if (room.players.includes(playerId)) {
return { error: '已在房間中' };
}
room.players.push(playerId);
return { success: true, room };
}
// 開始遊戲
startGame(roomId) {
const room = this.rooms.get(roomId);
if (!room) {
return { error: '房間不存在' };
}
if (room.players.length < room.minPlayers) {
return { error: '人數不足' };
}
if (room.status !== 'waiting') {
return { error: '遊戲已開始' };
}
const engine = new GameEngine();
const gameState = engine.init(room.players);
room.engine = engine; // 儲存引擎
room.gameState = gameState;
room.status = 'playing';
return { success: true, gameState };
}
// 取得房間
getRoom(roomId) {
return this.rooms.get(roomId);
}
// 列出房間
listRooms() {
const rooms = [];
for (const [id, room] of this.rooms) {
rooms.push({
id: room.id,
players: room.players.length,
maxPlayers: room.maxPlayers,
status: room.status
});
}
return rooms;
}
// 移除玩家
removePlayer(playerId) {
for (const [roomId, room] of this.rooms) {
if (room.players.includes(playerId)) {
room.players = room.players.filter(id => id !== playerId);
// 如果房間人數不足,結束遊戲
if (room.players.length < room.minPlayers && room.status === 'playing') {
room.status = 'ended';
}
return { roomId, room };
}
}
return null;
}
}
module.exports = RoomManager;