Sea Battle is a Battleship-style game: three ships hide on a 6ร6 sea and you have 20 shots to sink them all. You fire at squares like B4. It's a great way to practise turning text into grid coordinates and placing things randomly without overlaps.
Each hit shows an X, each miss an o. Sink all three ships (sizes 3, 2 and 2) before your shots run out.
Play Sea Battle
Press โถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (72 lines)
How to play
- Fire by typing a letter (A-F, the column) and a number (1-6, the row), like C3.
- X marks a hit, o marks a miss. The game tells you when a ship sinks.
- Sink every ship within 20 shots to win.
The complete Sea Battle code
Here is the whole program (72 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
SIZE = 6
LETTERS = "ABCDEF"
ships = [] # each ship is a set of (row, col) squares
def place(length):
while True:
across = random.choice([True, False])
r = random.randrange(SIZE - (0 if across else length - 1))
c = random.randrange(SIZE - (length - 1 if across else 0))
cells = {(r, c + i) if across else (r + i, c) for i in range(length)}
if not any(cells & s for s in ships): # no overlap
ships.append(cells)
return
def parse(text):
text = text.strip().upper()
if len(text) != 2 or text[0] not in LETTERS or not text[1].isdigit():
return None
r = int(text[1]) - 1
if not 0 <= r < SIZE:
return None
return r, LETTERS.index(text[0])
def show():
print("\n " + " ".join(LETTERS))
for r in range(SIZE):
row = []
for c in range(SIZE):
if (r, c) in hits:
row.append("X")
elif (r, c) in misses:
row.append("o")
else:
row.append("~")
print(f" {r + 1} " + " ".join(row))
for length in (3, 2, 2):
place(length)
hits, misses = set(), set()
shots = 20
print("SEA BATTLE - sink 3 ships in 20 shots")
while shots > 0:
show()
spot = parse(input(f"Shots left {shots}. Fire at: "))
if spot is None:
print("Type a letter A-F and a number 1-6, like C3.")
continue
if spot in hits or spot in misses:
print("You already fired there.")
continue
shots -= 1
ship = next((s for s in ships if spot in s), None)
if ship:
hits.add(spot)
print("HIT!" + (" You sank a ship!" if ship <= hits else ""))
if all(s <= hits for s in ships):
show()
print("All ships sunk. You win the battle!")
break
else:
misses.add(spot)
print("Splash. Miss.")
else:
print("Out of shots! The ships were at:")
print(", ".join(LETTERS[c] + str(r + 1) for s in ships for r, c in sorted(s)))How the Sea Battle game works, step by step
01A ship is a set of squares
Each ship is a set of (row, col) tuples. A shot hits when it's in a ship's set, and a ship has sunk when its set is a subset of all hits: ship <= hits.
ships.append({(2, 1), (2, 2), (2, 3)})02Place ships at random without overlap
Pick across or down, then a start square that leaves room for the whole ship. The set intersection cells & s is empty when two ships don't touch the same squares.
if not any(cells & s for s in ships):
ships.append(cells)03Turn "C3" into a position
The letter is the column: "ABCDEF".index("C") is 2. The digit minus one is the row. Anything else returns None, which the loop treats as a bad shot.
r = int(text[1]) - 1
return r, LETTERS.index(text[0])04Count down your shots
A while ... else loop: the else part only runs if the loop ends without break, which here means you ran out of shots.
while shots > 0:
...
else:
print("Out of shots!")What you'll learn
- Sets, intersection
&and subset<= random.randrange()for positions- Converting letters to numbers with
.index() while ... elsenext()with a default
Python concepts in this game:
Sea Battle coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Read a coordinate
Write parse(text) that turns "C3" into (2, 2) (row, column, both from 0). Letters A-F, numbers 1-6, any case and spaces allowed. Return None for anything else.
Hint
After .strip().upper(), check the length is 2, the letter is in LETTERS and the digit is in "123456".
Show a solution
LETTERS = "ABCDEF"
def parse(text):
text = text.strip().upper()
if len(text) != 2 or text[0] not in LETTERS or text[1] not in "123456":
return None
return int(text[1]) - 1, LETTERS.index(text[0])
print(parse("c3"))Ship squares
Write cells(r, c, length, across) that returns the set of squares a ship covers, starting at (r, c) and going right if across is True, else down.
Hint
A set comprehension: {(r, c + i) for i in range(length)}.
Show a solution
def cells(r, c, length, across):
if across:
return {(r, c + i) for i in range(length)}
return {(r + i, c) for i in range(length)}
print(cells(1, 2, 3, True))Has it sunk?
Write sunk(ship, hits): both are sets of squares. Return True if every square of the ship has been hit.
Hint
A set is a subset of another when all its items are in it: ship <= hits or ship.issubset(hits).
Show a solution
def sunk(ship, hits):
return ship <= hits
print(sunk({(0, 0), (0, 1)}, {(0, 0), (0, 1), (3, 3)}))Make it your own
Once your challenges pass, try one of these upgrades:
- Let the computer fire back at your own hidden ships.
- Add a 'sonar' that reveals one row once per game.
- Grow the sea to 10ร10 with five ships.
- Stop ships from touching, not just overlapping.
Frequently asked questions
How do you make Battleship in Python?
Place ships as sets of grid squares with random positions that don't overlap, read shots like C3 and turn them into (row, column), then record hits and misses until every ship's squares have been hit.
How do I stop ships overlapping?
Build the new ship's squares as a set and check the intersection with each existing ship. If any intersection isn't empty, choose a new position.
How do I convert a letter to a column number?
Use "ABCDEF".index(letter). A is 0, B is 1, and so on. ord(letter) - ord('A') does the same.