UNPKG

poem_game_component

Version:

119 lines (99 loc) 3.55 kB
import { Player } from './entities/Player'; import { GameType } from './enums/GameType'; import { GameRule } from './interfaces/GameRule'; import { GameStatus } from './enums/GameStatus'; export class Game { private players: Player[] = []; private currentPlayerIndex: number = 0; private historyAnswers: string[] = []; private status: GameStatus = GameStatus.PREPARING; constructor( private id: string, private gameType: GameType, private initialCondition: string ) {} getId(): string { return this.id; } getGameType(): GameType { return this.gameType; } getInitialCondition(): string { return this.initialCondition; } getPlayers(): Player[] { return this.players; } // setPlayers(players: Player[]): void { // this.players = players; // } getCurrentPlayerIndex(): number { return this.currentPlayerIndex; } getCurrentPlayer(): Player { return this.players[this.currentPlayerIndex]; } getHistoryAnswers(): string[] { return this.historyAnswers; } getStatus(): GameStatus { return this.status; } addPlayer(player: Player): void { if (this.status !== GameStatus.PREPARING) { throw new Error('游戏已经开始或结束,不能添加玩家'); } if (this.players.some(p => p.getName() === player.getName())) { throw new Error('玩家已存在'); } this.players.push(player); } async submitAnswer(answer: string, rule: GameRule): Promise<boolean> { if (this.status === GameStatus.PREPARING) { throw new Error('游戏尚未开始,不能提交答案'); } if (this.status === GameStatus.FINISHED) { throw new Error('游戏已结束,不能提交答案'); } const isValid = await rule.validateAnswer(this.historyAnswers, answer, this.initialCondition); if (isValid) { this.historyAnswers.push(answer); this.currentPlayerIndex = this.getNextPlayer(); } else { const player = this.getCurrentPlayer(); console.log(answer,player); this.getCurrentPlayer().eliminate(); this.currentPlayerIndex = this.getNextPlayer(); } if (this.isGameOver()) { this.status = GameStatus.FINISHED; } return isValid; } startGame(): void { if (this.status !== GameStatus.PREPARING) { throw new Error('游戏已经开始或结束'); } if (this.players.length < 2) { throw new Error('至少需要两名玩家才能开始游戏'); } this.status = GameStatus.PLAYING; } isGameOver(): boolean { const activePlayers = this.players.filter(player => !player.isPlayerEliminated()); return activePlayers.length <= 1; } getWinner(): Player | null { if (!this.isGameOver()) { return null; } return this.players.find(player => !player.isPlayerEliminated()) || null; } getNextPlayer(): number { let nextIndex = (this.currentPlayerIndex + 1) % this.players.length; while (this.players[nextIndex].isPlayerEliminated()) { nextIndex = (nextIndex + 1) % this.players.length; } return nextIndex; } }