Terminal Naval Combat: Fleet Setup and Attack System
Data Structure DesignModel answerLast updated
Implement a console-based naval battle game where two players configure their fleets through text input, then exchange fire until one side is eliminated.
Design and implement a naval combat game that runs entirely in a terminal window. Two players will use the same console, alternating control to configure their fleets and then engage in combat.
Core Requirements
Build a game system where:
- Each player configures their fleet by entering ship specifications via text commands
- After both fleets are ready, players alternate attempting to strike enemy vessels
- The game concludes when all ships belonging to one player have been destroyed
Technical Expectations
- Deliver executable code, not just class diagrams or pseudocode
- Handle all text input gracefully—malformed entries should prompt retry, not crash the program
- Maintain information hiding: no player should see the opponent's ship locations
- The codebase should be substantial enough to demonstrate production-quality engineering
Design Decisions Required
You must define and clearly communicate:
- Grid dimensions (make this configurable)
- Fleet composition—how many ships and what sizes (make this configurable)
- Input syntax for specifying ship position (e.g., row/column pairs, algebraic notation)
- Placement rules: Can ships touch? Overlap? Must they fit entirely within bounds?
Implementation Phases
Phase One: Fleet Configuration
Create the necessary classes and game loop so both players can:
- Enter ship specifications through terminal prompts
- See their own grid during placement
- Receive clear error messages for invalid placements (out of bounds, collision, invalid format)
- Complete placement before the opponent begins their turn
Expected capabilities:
- Parse text input into structured placement data
- Validate every placement without leaving partial or corrupted state
- Switch control between players during the setup phase
- Display each player's grid showing their own fleet
Phase Two: Combat Operations
Extend the system to support the attack phase:
- Players alternate selecting target coordinates
- Each attack returns a result: miss, hit, or vessel destroyed
- Attackers see a tracking view showing their previous strikes and outcomes
- Game detects victory condition (all enemy ships eliminated)
Additional considerations:
- Should hitting a vessel grant an immediate follow-up shot?
- Should the system distinguish between damaging and destroying a vessel?
- How should repeated attacks on the same position be handled?
Evaluation Criteria
Strong implementations demonstrate:
- Separation of game logic from input/output operations
- Robust input validation at every interaction point
- Clean data structures that simplify collision detection and damage tracking
- Incremental development: basic playable version first, then enhancements
- Clear method naming and responsibilities, despite the code volume
Hints
Hint 1
Start with core data structures—Board and Ship classes—before building the game loop, and test placement logic independently of terminal I/O
Hint 2
Use a 2D structure to track each cell's state (empty, occupied by which ship, hit or not) rather than searching ship coordinates on every operation
Hint 3
Handle setup and combat as separate phases with distinct state, and use a tracking board for each player to remember what they've learned about the opponent
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests your ability to build a substantial, working system under time pressure while maintaining clean architecture. The key is to deliver a playable minimum version quickly, then layer on features.
Development Strategy
- Core models first:
Board,Ship,Cellclasses that can be tested without I/O - Placement logic: Validate and place ships on a board
- Basic game loop: Two players place ships in sequence
- Combat phase: Attack resolution and victory detection
- Polish: Better output formatting, tracking boards, edge cases
Architecture
Separate concerns cleanly:
class Cell:
"""Represents one grid position"""
def __init__(self):
self.ship = None # Reference to Ship occupying this cell
self.is_hit = False # Has this cell been attacked?
class Ship:
"""Represents a vessel with size and damage"""
def __init__(self, size, cells):
self.size = size
self.cells = cells # List of (row, col) positions
self.hits = 0
def is_sunk(self):
return self.hits >= self.size
class Board:
"""Manages grid state for one player"""
def __init__(self, rows=10, cols=10):
self.rows = rows
self.cols = cols
self.grid = [[Cell() for _ in range(cols)] for _ in range(rows)]
self.ships = []
def place_ship(self, start_row, start_col, size, orientation):
"""Returns True if valid placement, False otherwise"""
# Calculate cells the ship would occupy
cells = self._calculate_cells(start_row, start_col, size, orientation)
# Validate: in bounds and no collision
if not self._is_valid_placement(cells):
return False
# Create ship and mark cells
ship = Ship(size, cells)
for r, c in cells:
self.grid[r][c].ship = ship
self.ships.append(ship)
return True
def attack(self, row, col):
"""Returns 'miss', 'hit', 'sunk', 'already_hit', or 'invalid'"""
if not self._in_bounds(row, col):
return 'invalid'
cell = self.grid[row][col]
if cell.is_hit:
return 'already_hit'
cell.is_hit = True
if cell.ship:
cell.ship.hits += 1
return 'sunk' if cell.ship.is_sunk() else 'hit'
return 'miss'
def all_sunk(self):
return all(ship.is_sunk() for ship in self.ships)
class Game:
"""Orchestrates game flow"""
def __init__(self, board_size=10, fleet=[5, 4, 3, 3, 2]):
self.board_size = board_size
self.fleet = fleet # Ship sizes each player must place
self.player1_board = Board(board_size, board_size)
self.player2_board = Board(board_size, board_size)
def run(self):
self._setup_phase()
self._combat_phase()
Input Parsing
Accept flexible input like "A5 horizontal 3" or "2,3 v 4":
def parse_placement(input_line):
"""Returns (row, col, size, orientation) or None if invalid"""
parts = input_line.strip().lower().split()
if len(parts) < 3:
return None
# Parse coordinate (handle both "A5" and "0,5")
coord = parts[0]
if ',' in coord:
row, col = map(int, coord.split(','))
else:
row = ord(coord[0]) - ord('a')
col = int(coord[1:]) - 1
# Parse orientation
orientation = 'horizontal' if parts[1][0] in 'hr' else 'vertical'
# Parse size
size = int(parts[2])
return (row, col, size, orientation)
Key Implementation Details
Placement validation must be atomic: Either the entire ship is placed, or nothing changes. Never leave a partially-placed ship corrupting the board.
Two views per player:
- Their own board (shows ship locations and damage)
- Tracking board for opponent (shows only previous strikes and results)
Turn structure during combat:
def _combat_phase(self):
current_attacker = 1
while True:
attacker_board = self.player1_board if current_attacker == 1 else self.player2_board
target_board = self.player2_board if current_attacker == 1 else self.player1_board
self._show_tracking_view(attacker_board)
target = self._get_attack_input()
result = target_board.attack(*target)
print(f"Result: {result}")
if target_board.all_sunk():
print(f"Player {current_attacker} wins!")
break
current_attacker = 3 - current_attacker # Toggle between 1 and 2
Screen clearing between turns: Use os.system('clear') or print many newlines to prevent the next player from seeing the previous player's board.
Common Mistakes
-
Storing ship positions as lists and searching on every operation: Use a 2D grid where each cell knows its ship—O(1) lookups.
-
Tight coupling between I/O and logic: The
Boardclass should never callinput()orprint(). Keep game rules testable. -
Fragile input parsing: Real users type
"a 5 h 3","A5h3","a5 horiz 3". Handle variations or clearly document the exact required format. -
Forgetting already-attacked cells: Track whether each cell has been targeted, independent of whether a ship occupies it.
-
Not validating ship overlap: Two ships sharing a cell breaks damage tracking—one hit would register on both.
Complexity
- Space: O(R × C) for each board, where R and C are grid dimensions
- Placement validation: O(S) where S is ship size (check S cells for bounds and collision)
- Attack resolution: O(1) with grid-based storage
Complete Flow
- Player 1 places all ships (with validation and retry on errors)
- Screen cleared
- Player 2 places all ships
- Screen cleared
- Players alternate attacking until one fleet is destroyed
- Game announces winner
The large scope demands disciplined incremental building: get basic placement working, add validation, add combat, then enhance. Rushing to write everything at once leads to debugging chaos under time pressure.