Two-Player Grid Battle: Terminal Ship Placement and Combat
Data Structure DesignModel answerLast updated
Build a complete terminal game where two players secretly place ships on grids, then take turns firing until one fleet is destroyed.
Build a complete two-player naval combat game that runs in the terminal. Two players share one machine: each secretly positions their fleet on a private grid, then they alternate firing shots at each other's grids until one player's entire fleet is destroyed.
Your code must be runnable and testable. Prioritize getting a working prototype early, then refine the validation and edge cases.
Phase 1: Fleet Positioning
- The game uses an 8×8 grid by default. Columns are labeled
AthroughH, rows are numbered1through8. For example,D6refers to column D, row 6. - The grid size and fleet composition must be configurable via constructor:
GridBattle(size=10, fleet=(5, 4, 3, 3, 2)). - The default fleet contains ships of lengths:
4, 3, 3, 2. - Each player enters one ship per command:
<start-cell> <length> <H|V>. For example:C3 3 Hplaces a 3-cell ship horizontally starting at C3, occupyingC3, D3, E3.C3 3 Vplaces it vertically, occupyingC3, C4, C5.
- Reject invalid commands with a clear message and re-prompt without changing the grid state. Reasons for rejection:
- Malformed input (wrong number of tokens, invalid direction).
- Cell outside the grid bounds.
- Length not in the remaining fleet.
- Ship extends beyond grid boundaries.
- Ship overlaps an already-placed ship.
- After each successful placement, display the player's current grid showing all ships.
- Before switching players, clear the screen and wait for confirmation (e.g., press Enter) to prevent the other player from seeing ship positions.
Phase 2: Combat
- Players alternate turns. On each turn, display:
- The current player's own grid, showing ship positions and any incoming hits.
- The opponent's grid showing only previous shots (hits and misses), without revealing ship locations.
- The player enters a single cell to target, such as
F4. - Report the outcome:
Miss.,Hit!, orHit - ship destroyed!. - If the player targets a cell they've already fired at, or enters an invalid cell, display an error and re-prompt without ending their turn.
- The game ends when all ships belonging to one player are destroyed. Announce the winner.
Sample Interaction
Player 1, place a ship [2, 3, 3, 4]: A9 2 H
Rejected: row must be 1-8
Player 1, place a ship [2, 3, 3, 4]: H3 3 H
Rejected: ship would extend beyond the grid
Player 1, place a ship [2, 3, 3, 4]: A1 4 H
A B C D E F G H
1 V V V V . . . .
2 . . . . . . . .
...
Player 2, fire at: D5
Hit!
Player 1, fire at: D5
You already targeted that cell. Try again.
Design Requirements
- Inject I/O dependencies: Accept
readandwriteparameters (e.g.,read=input, write=print) so tests can drive the game with scripted inputs. - Centralize validation: Parse and validate commands fully before modifying any game state. A rejected command must leave the grid unchanged.
- Model clarity: Separate concerns—ship state, grid operations, turn flow, and I/O—into distinct components or classes.
Write working, runnable code that handles the core mechanics and validation robustly.
Hints
Hint 1
Start with the data model: how will you represent ships, grids, and damage? Design so hit detection is fast.
Hint 2
Validate placement commands in full before applying them. Compute all cells the ship would occupy, check bounds and overlaps, then commit only if valid.
Hint 3
Use a reveal flag when rendering grids: show ship positions for the owner, but only shots for the opponent.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Break the problem into modeling, validation, and control flow:
- Model the domain: Ships track their cells and damage. Grids own ships, manage occupancy for fast lookups, and record all shots. Players own a grid.
- Validate before mutating: Parse commands into structured data, compute what would happen, validate completely, then commit only if valid. This keeps rejected commands from corrupting state.
- Control the flow: Setup loops until all ships are placed. Combat alternates turns, rendering the right views for each player, until a fleet is eliminated.
Plan to have a minimal playable loop working in 15–20 minutes (place one ship, fire one shot, detect a hit), then layer on full fleet management, validation messages, and screen transitions.
Data Structures
- Ship: Stores its length, the set of cells it occupies, and the set of cells that have been hit. A ship is sunk when these sets are equal.
- Grid: Maintains a list of ships, a map from cell to ship (for O(1) hit lookup), and a map from cell to shot result. Provides methods to compute cell ranges, validate placement, place a ship, fire at a cell, check defeat, and render with or without revealing ship positions.
- Player: Wraps a name and a grid.
- Game controller: Orchestrates parsing, setup, turn-taking, and victory detection. Injects I/O so tests can script interactions.
Validation Strategy
Parsing raises ValueError with actionable messages. Placement validation:
- Parse the start cell, length, and direction.
- Compute all cells the ship would occupy.
- Check that all cells lie within bounds and none overlap existing ships.
- Only if all checks pass, mutate the grid.
This guarantees atomicity: a command either fully succeeds or leaves the grid untouched.
Rendering uses a reveal flag: when true, show ship locations; when false, show only shot history. This lets us render a player's own grid (revealed) and the opponent's grid (concealed) with one function.
Screen handoff prints blank lines and waits for Enter—a simple hot-seat privacy mechanism for terminal play.
Complexity
- Placement validation: O(length) to generate cells, O(length) to check occupancy via hash lookup.
- Firing: O(1) lookup in the shot map and occupancy map.
- Rendering: O(size²) to build the grid display.
- Overall game: O(fleet_size × avg_length + turns × size²), dominated by rendering and turns, both reasonable for small grids.
Code
import string
WATER, SHIP, HIT, MISS = ".", "S", "X", "o"
class Ship:
def __init__(self, length, cells):
self.length = length
self.cells = set(cells)
self.hits = set()
def is_sunk(self):
return self.hits == self.cells
class Grid:
def __init__(self, size):
self.size = size
self.ships = []
self.occupancy = {} # (row, col) -> Ship
self.shots = {} # (row, col) -> HIT or MISS
def compute_cells(self, row, col, length, direction):
delta_row, delta_col = (0, 1) if direction == "H" else (1, 0)
return [(row + delta_row * i, col + delta_col * i) for i in range(length)]
def validate_placement(self, cells):
for r, c in cells:
if not (0 <= r < self.size and 0 <= c < self.size):
return "ship would extend beyond the grid"
if (r, c) in self.occupancy:
return "ship would overlap an existing ship"
return None
def place_ship(self, length, cells):
ship = Ship(length, cells)
self.ships.append(ship)
for cell in cells:
self.occupancy[cell] = ship
def fire_at(self, cell):
if cell in self.shots:
return "repeat"
ship = self.occupancy.get(cell)
if ship is None:
self.shots[cell] = MISS
return "miss"
self.shots[cell] = HIT
ship.hits.add(cell)
return "sunk" if ship.is_sunk() else "hit"
def all_sunk(self):
return bool(self.ships) and all(s.is_sunk() for s in self.ships)
def render(self, reveal):
cols = string.ascii_uppercase[: self.size]
header = " " + " ".join(cols)
lines = [header]
for r in range(self.size):
row_chars = []
for c in range(self.size):
if (r, c) in self.shots:
row_chars.append(self.shots[(r, c)])
elif reveal and (r, c) in self.occupancy:
row_chars.append(SHIP)
else:
row_chars.append(WATER)
lines.append(f"{r + 1:>2} " + " ".join(row_chars))
return "\n".join(lines)
class Player:
def __init__(self, name, size):
self.name = name
self.grid = Grid(size)
class GridBattle:
def __init__(self, size=8, fleet=(4, 3, 3, 2), read=input, write=print):
if not 2 <= size <= 26:
raise ValueError("grid size must be between 2 and 26")
self.size = size
self.fleet = tuple(fleet)
self.read = read
self.write = write
self.players = [Player("Player 1", size), Player("Player 2", size)]
def parse_cell(self, text):
text = text.strip().upper()
cols = string.ascii_uppercase[: self.size]
if len(text) < 2 or text[0] not in cols:
raise ValueError(f"column must be A-{cols[-1]}")
if not text[1:].isdigit():
raise ValueError("row must be a number")
row = int(text[1:]) - 1
col = ord(text[0]) - ord("A")
if not 0 <= row < self.size:
raise ValueError(f"row must be 1-{self.size}")
return row, col
def parse_placement(self, line, available):
tokens = line.split()
if len(tokens) != 3:
raise ValueError("expected: <cell> <length> <H|V>")
row, col = self.parse_cell(tokens[0])
if not tokens[1].isdigit() or int(tokens[1]) not in available:
raise ValueError(f"length must be one of {sorted(available)}")
length = int(tokens[1])
direction = tokens[2].upper()
if direction not in ("H", "V"):
raise ValueError("direction must be H or V")
return row, col, length, direction
def clear_and_wait(self, player):
self.write("\n" * 50)
self.read(f"{player.name}, press Enter when ready (other player look away)...")
def setup_phase(self, player):
self.clear_and_wait(player)
remaining = list(self.fleet)
while remaining:
self.write(player.grid.render(reveal=True))
line = self.read(f"{player.name}, place a ship {sorted(remaining)}: ")
try:
row, col, length, direction = self.parse_placement(line, remaining)
cells = player.grid.compute_cells(row, col, length, direction)
error = player.grid.validate_placement(cells)
if error:
raise ValueError(error)
except ValueError as e:
self.write(f"Rejected: {e}")
continue
player.grid.place_ship(length, cells)
remaining.remove(length)
self.write(player.grid.render(reveal=True))
def combat_turn(self, attacker, defender):
self.clear_and_wait(attacker)
self.write("Your fleet:\n" + attacker.grid.render(reveal=True))
self.write("\nOpponent's waters:\n" + defender.grid.render(reveal=False))
while True:
line = self.read(f"{attacker.name}, fire at: ")
try:
cell = self.parse_cell(line)
except ValueError as e:
self.write(f"Rejected: {e}")
continue
outcome = defender.grid.fire_at(cell)
if outcome == "repeat":
self.write("You already targeted that cell. Try again.")
continue
messages = {"miss": "Miss.", "hit": "Hit!", "sunk": "Hit - ship destroyed!"}
self.write(messages[outcome])
return
def play(self):
for player in self.players:
self.setup_phase(player)
turn_index = 0
while True:
attacker = self.players[turn_index % 2]
defender = self.players[(turn_index + 1) % 2]
self.combat_turn(attacker, defender)
if defender.grid.all_sunk():
self.write(f"\n{attacker.name} wins! All enemy ships destroyed.")
return
turn_index += 1
if __name__ == "__main__":
game = GridBattle()
game.play()
Common Mistakes
- Partial validation: Checking bounds but not overlaps, or vice versa, then mutating the grid before all checks pass.
- Leaking opponent state: Rendering the opponent's grid with
reveal=True, exposing ship locations. - Off-by-one in cell math: Forgetting rows are 1-indexed for display but 0-indexed internally; using
int(text[1:])directly instead of subtracting 1. - Reusing lengths: Not removing a placed ship length from the available pool, allowing duplicates.
Testing
Inject scripted I/O to drive the game deterministically:
inputs = iter(["A1 4 H", "", "A1 3 V", "B5", ...])
outputs = []
game = GridBattle(read=lambda prompt="": next(inputs), write=outputs.append)
game.play()
assert "Hit!" in outputs
This confirms validation, state transitions, and victory detection without manual play.