Design: Turn-based Game System
Design classes for Board, Player, and Game to manage game logic and state. UI, network communication, and persistence are out of scope.
Functional Requirements
Non-Functional Requirements
Jump into concepts and practice - no test required
+----------------+ +----------------+ +----------------+
| Player |<----->| Game |<----->| Board |
+----------------+ +----------------+ +----------------+
^ ^ ^
| | |
playerId, name gameId, players boardState, size
score, status currentTurn, status update(), reset()
Board, Player, and Game classes?constructor.game.playTurn() once?class Player {
constructor(name) { this.name = name; }
}
class Board {
constructor() { this.state = ['-', '-', '-']; }
mark(position, symbol) { this.state[position] = symbol; }
}
class Game {
constructor() {
this.board = new Board();
this.players = [new Player('Alice'), new Player('Bob')];
this.currentPlayerIndex = 0;
}
playTurn() {
const player = this.players[this.currentPlayerIndex];
this.board.mark(0, this.currentPlayerIndex === 0 ? 'X' : 'O');
this.currentPlayerIndex = 1 - this.currentPlayerIndex;
return this.board.state;
}
}
const game = new Game();
console.log(game.playTurn());class Game {
constructor() {
this.players = ['Alice', 'Bob'];
this.currentPlayerIndex = 0;
}
nextTurn() {
this.currentPlayerIndex += 1;
if (this.currentPlayerIndex > this.players.length) {
this.currentPlayerIndex = 0;
}
}
}Board, Player, and Game classes. Which design choice best supports adding new game rules and multiple player types (e.g., human, AI) without changing existing code much?