battleship
game validation
coding
programming
board game

How to validate Battleship field?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Validating a Battleship field is a crucial component of creating a computerized version of the classic board game, Battleship. This process ensures that the setup of the game adheres to its rules before play begins. A typical Battleship grid is usually a 10x10 matrix, where ships of varying lengths are placed either horizontally or vertically. In this article, we will delve into how you can validate a Battleship field programmatically.

Understanding the Battleship Rules

Ship Types and Sizes

In a standard Battleship game, you have the following ships:

  • Carrier: Occupies 5 squares.
  • Battleship: Occupies 4 squares.
  • Cruiser: Occupies 3 squares.
  • Submarine: Occupies 3 squares.
  • Destroyer: Occupies 2 squares.

Placement Rules

  1. Ships cannot overlap.
  2. Ships can only be placed horizontally or vertically.
  3. No ship can be immediately adjacent to another ship, including diagonally.

With these rules in mind, let us examine how to validate a Battleship field.

Designing a Validation Algorithm

Data Representation

A Battleship field can be represented as a 2D array or matrix. Each element in the matrix can either be a `0` (empty cell) or a `1` (part of a ship).

Steps for Validation

  1. Count and Verify Ship Sizes:
    • Iterate through the matrix and count sequences of `1`s horizontally and vertically.
    • Ensure they match the required number of each type of ship (two 3-lengths for Cruiser and Submarine).
  2. Check for Correct Positioning:
    • Confirm that all ships are placed either entirely horizontally or vertically.
    • Ships must align with the specified sizes.
  3. Verify No Overlaps or Adjacent Ships:
    • As you count ships, check adjacent cells (including diagonals) for other `1`s.

Pseudocode Example

Here's an example of how this can be approached:

  • Diagonal Ships: Make sure to flag any ships that are not placed linearly.
  • Multiple Ships Detection: Accurately tracking which cells belong to which ship is crucial.
  • Boundary Conditions: Ensure proper checks for cells at the edges of the matrix.
  • This validation assumes the field size of 10x10, which makes a brute-force solution feasible. But consider optimizations if scaling to larger grids or multiple games.

Course illustration
Course illustration

All Rights Reserved.