0
0
LLDsystem_design~15 mins

Board and piece hierarchy in LLD - Deep Dive

Choose your learning style9 modes available
Overview - Board and piece hierarchy
What is it?
Board and piece hierarchy is a way to organize the parts of a game or system where a board holds pieces, and pieces have different types and behaviors. It helps structure how pieces interact with the board and each other. This hierarchy defines relationships and shared features, making the system easier to build and understand.
Why it matters
Without a clear board and piece hierarchy, managing game rules and piece behaviors becomes chaotic and error-prone. It would be like trying to play chess without knowing what each piece does or where it can move. This structure allows developers to add new pieces or boards easily and keeps the system organized and scalable.
Where it fits
Before learning this, you should understand basic object-oriented concepts like classes and inheritance. After this, you can explore game logic implementation, move validation, and AI strategies that use the hierarchy to make decisions.
Mental Model
Core Idea
A board and piece hierarchy organizes game elements so that shared features live in general classes, and specific behaviors live in specialized subclasses, making the system clear and extendable.
Think of it like...
Think of a board as a stage and pieces as actors. The stage sets the scene and rules, while actors have roles and actions. Some actors share roles, like all knights wearing armor, but each has unique moves.
┌─────────────┐        ┌─────────────┐
│    Board    │◄───────│   Game      │
│  (grid/map) │        │ Controller  │
└─────┬───────┘        └─────────────┘
      │
      │ contains
      ▼
┌─────────────┐
│   Piece     │
│ (base class)│
└─────┬───────┘
      │
 ┌────┴─────┐
 │          │
▼          ▼
Pawn      Knight
(derived) (derived)
Build-Up - 7 Steps
1
FoundationUnderstanding Board as Container
🤔
Concept: Introduce the board as a container that holds pieces in positions.
A board is like a grid or map where pieces sit. It keeps track of where each piece is placed. For example, in chess, the board has 8 rows and 8 columns, and each square can hold one piece or be empty.
Result
You can represent the board as a 2D array or list of lists, where each cell points to a piece or is empty.
Understanding the board as a container clarifies how pieces are organized and accessed, which is the foundation for all game interactions.
2
FoundationDefining Piece Base Class
🤔
Concept: Create a general piece class that holds common properties like position and color.
All pieces share some features: they have a position on the board, a color or team, and a way to move. The base class defines these shared properties and methods, so specific pieces can build on them.
Result
A base piece class can be used to create any piece type, ensuring consistency and reducing repeated code.
Having a base piece class centralizes common features, making the system easier to maintain and extend.
3
IntermediateSpecializing Pieces with Inheritance
🤔Before reading on: do you think all pieces should have the same move logic or different ones? Commit to your answer.
Concept: Use inheritance to create specific piece types that override or extend base behaviors.
Each piece type, like Pawn or Knight, inherits from the base piece class but defines its own movement rules and special abilities. This allows different pieces to behave uniquely while sharing common structure.
Result
You get a clear hierarchy where adding new piece types is simple and does not affect existing code.
Using inheritance for pieces models real-world differences cleanly and supports flexible game rules.
4
IntermediateBoard-Piece Interaction Design
🤔Before reading on: should pieces know about the board, or should the board control pieces? Commit to your answer.
Concept: Design how pieces and board communicate to enforce rules and update states.
Pieces often need to check the board to see if moves are valid or if other pieces block them. The board can provide methods to query positions and update piece locations. This interaction must be carefully designed to avoid tight coupling.
Result
A clean interface between board and pieces allows easy rule enforcement and state updates.
Understanding the communication flow prevents tangled code and supports future changes like new rules or board types.
5
IntermediateHandling Piece Movement and Validation
🤔Before reading on: do you think move validation belongs in the piece, the board, or both? Commit to your answer.
Concept: Implement move logic and validation considering both piece abilities and board state.
Pieces define where they can move, but the board checks if those moves are possible (e.g., no blocking pieces, within bounds). Combining these checks ensures moves follow game rules.
Result
Moves are validated correctly, preventing illegal actions and maintaining game integrity.
Separating move logic and validation responsibilities leads to clearer, more maintainable code.
6
AdvancedExtending Hierarchy for Complex Games
🤔Before reading on: can the same hierarchy support different games or variants? Commit to your answer.
Concept: Design the hierarchy to support multiple game types or piece variants with minimal changes.
By abstracting common behaviors and using interfaces or abstract classes, the hierarchy can be extended to new games or piece types. For example, adding a 'FlyingPiece' subclass for games with flying units.
Result
The system becomes flexible and reusable across different games or rule sets.
Designing for extension upfront saves time and effort when evolving or creating new games.
7
ExpertOptimizing Hierarchy for Performance and Scalability
🤔Before reading on: do you think a deep inheritance tree always improves design? Commit to your answer.
Concept: Balance hierarchy depth and composition to optimize runtime performance and code clarity.
Deep inheritance can cause complexity and slowdowns. Using composition (e.g., behaviors as separate objects) alongside inheritance can improve flexibility and performance. Also, caching board states or move results can speed up calculations in complex games.
Result
A well-balanced design that performs well even with many pieces and complex rules.
Knowing when to combine inheritance with composition and caching is key to building scalable game systems.
Under the Hood
The board is typically implemented as a data structure like a 2D array or graph that holds references to piece objects. Each piece object stores its state and behavior. When a move is requested, the piece's move method generates possible moves, and the board validates them by checking boundaries and occupancy. This interaction often uses method calls and event notifications. Inheritance allows pieces to override base methods to customize behavior, while polymorphism lets the system treat all pieces uniformly when needed.
Why designed this way?
This design follows object-oriented principles to promote code reuse and clarity. Early game systems used procedural code, which became hard to maintain as complexity grew. Using a hierarchy separates concerns: the board manages space, pieces manage behavior. Alternatives like flat structures or heavy use of conditionals were rejected because they do not scale well or are error-prone.
┌───────────────┐
│    Board      │
│  (2D array)   │
│  + getPiece() │
│  + movePiece()│
└──────┬────────┘
       │ contains
       ▼
┌───────────────┐
│    Piece      │
│  (base class) │
│ + position    │
│ + move()      │
└──────┬────────┘
       │
 ┌─────┴─────┐
 │           │
▼           ▼
Pawn       Knight
+ move()   + move()
Myth Busters - 4 Common Misconceptions
Quick: Do all pieces need to know the entire board state to decide moves? Commit yes or no.
Common Belief:Each piece must know the whole board to decide where it can move.
Tap to reveal reality
Reality:Pieces only need limited information, often just nearby squares or specific board queries. The board manages global state and provides necessary info.
Why it matters:If pieces try to manage full board state, code becomes complex and inefficient, making maintenance and updates harder.
Quick: Is deep inheritance always better than composition? Commit yes or no.
Common Belief:A deep inheritance tree with many subclasses is the best way to model all piece behaviors.
Tap to reveal reality
Reality:Too deep inheritance causes rigidity and complexity. Composition (combining behaviors) often leads to more flexible and maintainable designs.
Why it matters:Overusing inheritance can cause bugs and slow down development when adding new features.
Quick: Can the board be just a simple list of pieces without positions? Commit yes or no.
Common Belief:The board can be just a list of pieces; positions are not necessary to store separately.
Tap to reveal reality
Reality:Positions are essential for move validation and game logic. Without explicit positions, the system cannot enforce rules or display the game state.
Why it matters:Ignoring positions breaks core game mechanics and confuses both the system and players.
Quick: Does the piece hierarchy only apply to board games? Commit yes or no.
Common Belief:Board and piece hierarchy is only useful for traditional board games like chess or checkers.
Tap to reveal reality
Reality:This hierarchy pattern applies to many domains, including strategy video games, simulations, and even UI component trees.
Why it matters:Limiting the concept to board games misses opportunities to reuse and adapt the pattern in other complex systems.
Expert Zone
1
Pieces can implement interfaces for behaviors like 'Movable' or 'Capturable' to separate concerns beyond inheritance.
2
The board can use event-driven updates to notify pieces of changes, reducing tight coupling and improving responsiveness.
3
Caching valid moves per piece and invalidating caches only on state changes can greatly improve performance in complex games.
When NOT to use
Avoid deep inheritance hierarchies when piece behaviors vary widely and overlap; prefer composition or entity-component systems instead. For highly dynamic or moddable games, data-driven designs with scripting languages may be better.
Production Patterns
Real-world games use a mix of inheritance and composition, often with a central game controller managing turns and state. Pieces are lightweight objects with behavior modules. Boards support multiple layers (e.g., terrain, pieces) and use spatial partitioning for performance.
Connections
Entity-Component-System (ECS)
Alternative design pattern to inheritance-based hierarchies
Understanding board and piece hierarchy helps grasp ECS, where behaviors are components attached to entities, offering more flexibility in complex games.
Composite Design Pattern
Builds on the idea of hierarchical object structures
Knowing piece hierarchies clarifies how composite patterns allow treating groups of objects and single objects uniformly, useful in UI and game design.
Organizational Hierarchies
Similar structural principles in management and software
Recognizing that board and piece hierarchies mirror organizational charts helps understand delegation, inheritance, and responsibility distribution in systems.
Common Pitfalls
#1Placing all move logic inside the board class.
Wrong approach:class Board { bool isValidMove(Piece p, Position pos) { // all piece move rules here } }
Correct approach:class Piece { virtual bool canMove(Position pos, Board board); } class Board { bool isValidMove(Piece p, Position pos) { return p.canMove(pos, this); } }
Root cause:Misunderstanding responsibility leads to bloated board class and hard-to-maintain code.
#2Using a flat list of pieces without position tracking.
Wrong approach:List pieces; // no position info stored
Correct approach:class Piece { Position position; } Board stores pieces in a 2D array or map keyed by position.
Root cause:Ignoring spatial organization breaks core game mechanics and state management.
#3Creating a deep inheritance tree for every small piece variation.
Wrong approach:class Piece -> class Pawn -> class SpecialPawn -> class FastPawn -> ...
Correct approach:Use composition: class Piece has Behavior objects like MoveBehavior, CaptureBehavior.
Root cause:Overusing inheritance causes rigidity and complexity, making changes costly.
Key Takeaways
A board and piece hierarchy organizes game elements by shared and unique features, making the system clear and extendable.
The board acts as a container managing piece positions, while pieces define their own behaviors and moves.
Inheritance helps model different piece types, but combining it with composition improves flexibility and maintainability.
Clear communication between board and pieces is essential to enforce rules and update game state correctly.
Designing for extension and performance upfront prepares the system for complex games and future changes.