Problem Statement
When designing a board game application, mixing all board and piece logic in one place causes code to become tangled and hard to maintain. Adding new piece types or changing board rules becomes error-prone and slows development.
Jump into concepts and practice - no test required
This diagram shows the Board class holding the game grid and referencing a base Piece class. Specific piece types like Pawn, Knight, and Bishop inherit from Piece and implement their own move logic.
### Before: All logic in one class class Game: def __init__(self): self.board = [[None]*8 for _ in range(8)] def move_pawn(self, from_pos, to_pos): # pawn move logic here pass def move_knight(self, from_pos, to_pos): # knight move logic here pass ### After: Board and piece hierarchy class Piece: def __init__(self, position): self.position = position def move(self, new_position, board): raise NotImplementedError class Pawn(Piece): def move(self, new_position, board): # pawn-specific move logic pass class Knight(Piece): def move(self, new_position, board): # knight-specific move logic pass class Board: def __init__(self): self.grid = [[None]*8 for _ in range(8)] def place_piece(self, piece, position): self.grid[position[0]][position[1]] = piece piece.position = position def move_piece(self, from_pos, to_pos): piece = self.grid[from_pos[0]][from_pos[1]] if piece and piece.move(to_pos, self): self.grid[to_pos[0]][to_pos[1]] = piece self.grid[from_pos[0]][from_pos[1]] = None piece.position = to_pos return True return False
Piece class in a board game design?Piece class holds these.King that extends a base Piece class in a typical object-oriented design?extends keyword and calls super() in constructor.class King extends Piece { constructor(position) { super(position); } }.console.log(board.pieces[0].type);?
class Piece {
constructor(type, position) {
this.type = type;
this.position = position;
}
}
class Board {
constructor() {
this.pieces = [];
}
addPiece(piece) {
this.pieces.push(piece);
}
}
const board = new Board();
board.addPiece(new Piece('Knight', 'B1'));
Piece with type 'Knight' and position 'B1' is created and added to board.pieces.board.pieces[0] refers to the first piece, so board.pieces[0].type is 'Knight'.class Piece {
constructor(type, position) {
this.type = type;
this.position = position;
}
}
class Queen extends Piece {
constructor(position) {
this.type = 'Queen';
this.position = position;
}
}super() before using this.this.type and this.position without calling super(), causing an error.Piece lets each piece implement its own move logic, enabling easy extension.