Problem Statement
Hardcoding a fixed board size and a fixed number of players makes the game rigid. When you want to change the board size or add more players, you must rewrite large parts of the code, causing bugs and slowing development.
Jump into concepts and practice - no test required
This diagram shows the game engine coordinating between a flexible NxN board manager and a player manager that supports multiple players. Inputs flow into the game engine, which updates board and player states accordingly.
### Before: Fixed 3x3 board and 2 players class Game: def __init__(self): self.board = [[None]*3 for _ in range(3)] self.players = ['X', 'O'] self.current_player = 0 def make_move(self, row, col): if self.board[row][col] is None: self.board[row][col] = self.players[self.current_player] self.current_player = 1 - self.current_player ### After: Extensible NxN board and multiple players class Game: def __init__(self, size=3, players=None): if players is None: players = ['X', 'O'] self.size = size self.board = [[None]*size for _ in range(size)] self.players = players self.current_player = 0 def make_move(self, row, col): if 0 <= row < self.size and 0 <= col < self.size: if self.board[row][col] is None: self.board[row][col] = self.players[self.current_player] self.current_player = (self.current_player + 1) % len(self.players)
NxN board and support for multiple players?NxN board in Python for any given size n?players = ['Alice', 'Bob', 'Carol']
turns = 5
for i in range(turns):
current = players[i % len(players)]
print(current)def setup_game(n, players):
board = [[None]*n]*n
for p in players:
print(f"Player: {p}")
return board
setup_game(3, ['A', 'B'])NxN board and support for multiple players. Which design approach best supports easy extensibility for future features like variable board sizes, more players, and custom rules?