Tutorial 9: Battleship
Setup: before you start
Create a new empty project in Spyder, and call it “Tutorial_9”.
Now create a new program file, battleship.py. All the
functions that you write have to be added to this file.
Files to download
You will need to download these files (by right-clicking on each link and selecting “Save link as…”):
- graphics.py,
- grid1.txt, and
- grid2.txt
Save each file in your Tutorial_9 project directory.
Context and Objectives
As you might already have noticed, some of us use CSC_1F001 tutorials to relive parts of their childhood. In this week, we will do so by playing Battleship, a game that was wildly popular in our elementary schools. For those who do not know the rules, we will not explain them here but refer you to Wikipedia.
In this tutorial we will program the grids, the ships, and the basic game logic for shooting, missing, hitting and sinking ships. You will also be given a visualization to play. Finally, we will give you the opportunity to program different versions of an artificial intelligence for Battleship.
Contrary to the description on Wikipedia, we will not use letters to encode the rows of the grid. Instead, we encode rows and columns using integers, which simplifies dealing with them in Python.
Skills we will practice today: handling classes, objects, and their interactions; working with lists and sets; reading input from files.
Exercises
Exercise 1: Ships
The most important thing in Battleship are of course ships. So let us create a class for those first.
To this end, create a new class Ship.
Its __init__() method must initialize
name, the name of the ship (a string)positions, a set containing the positions that the ship occupies on the grid, andhits, a set of positions of the ship that have already been hit (starting empty of course; remember that you can create an empty set in Python usingset()).
Your class Ship should begin as follows:
class Ship:
"""A ship that can be placed on the grid"""
def __repr__(self):
return f"Ship('{self.name}', {self.positions})"
def __str__(self):
return f'{repr(self)} with hits {self.hits}'
def __init__(self, name, positions):Test the construction of your ships as follows:
In [1]: s = Ship('Destroyer', {(1, 2), (2, 2)})
In [2]: s.name
Out[2]: 'Destroyer'
In [3]: s.positions
Out[3]: {(1, 2), (2, 2)}
In [4]: s.hits
Out[4]: set()
In [5]: str(s)
Out[5]: "Ship('Destroyer', {(1, 2), (2, 2)}) with hits set()"
Note that here, and in all other places where we deal with sets, the elements in the sets may be permuted in the output.
Now add a method __eq__() to compare
two ships. Two ships are considered to be equal if their three data
attributes name, positions, and
hits are equal.
Test your __eq__ method:
In [6]: s1 = Ship('Destroyer', {(1, 2), (2, 2)})
In [7]: s2 = Ship('Destroyer', {(1, 2), (2, 2)})
In [8]: s1 == s2
Out[8]: True
In [9]: s2.name = 'Different'
In [10]: s1 == s2
Out[10]: False
Finally, write a method is_afloat that
checks if the ship is still afloat, i.e., if there are any positions of
the ship that have not been hit.
Test your is_afloat() method in the
console:
In [11]: s1 = Ship('Destroyer', {(1, 2), (2, 2)})
In [12]: s1.is_afloat()
Out[12]: True
In [13]: s1.hits.add((1, 2))
In [14]: s1.hits
Out[14]: {(1, 2)}
In [15]: s1.is_afloat()
Out[15]: True
In [16]: s1.hits.add((2, 2))
In [17]: s1.is_afloat()
Out[17]: False
Afterwards, upload your file
battleship.py:
Exercise 2: Grids
Now that we have a way to build Ship objects, we will
write a class Grid to place the ships on. Grid
objects will have the following attributes:
- two integer attributes
x_sizeandy_sizeencoding the size in the x- and y-directions, respectively; - a list
shipscontaining the ships on the board; - a set
missescontaining the positions that were shot at and contained no ship.
We assume that cells in the grid have x-coordinate from
0 to x_size-1 and y-coordinate from
0 to y_size-1.
Note: the grid records only the first shot at each
position. If it hits a Ship in ships, we
record the hit in that ship’s hits set. Otherwise, we
record the position in the grid’s misses set.
Create the class Grid and add a method
__init__ that initializes x_size and
y_size to given values and the other attributes
(ships and misses) as empty. Your class should
begin as follows:
class Grid:
"""Encodes the grid on which the Ships are placed. Also remembers the
shots that have been fired so far and if they were hits.
"""
def __init__(self, x_size, y_size):Test your class, for example as follows:
In [18]: g = Grid(10, 11)
In [19]: g.x_size
Out[19]: 10
In [20]: g.y_size
Out[20]: 11
In [21]: g.ships
Out[21]: []
In [22]: g.misses
Out[22]: set()
The game won’t be very interesting if we can’t add some ships to a
grid, so now define a method add_ship to
your Grid class:
def add_ship(self, ship):
"""Add a ship only if it does not overlap with an existing ship."""This method should add the ship at the end of the ships list only if the positions of this new ship do not intersect positions of ships of the grid. Continuing the example above, we should see
In [23]: g = Grid(10, 11)
In [24]: g.ships
Out[24]: []
In [25]: s1 = Ship('Destroyer', {(1, 2), (2, 2)})
In [26]: g.add_ship(s1)
In [26]: g.ships
Out[26]: [Ship('Destroyer', {(1, 2), (2, 2)})]
In [27]: s2 = Ship('Destroyer', {(3, 2), (2, 2)})
In [28]: g.add_ship(s2)
In [28]: g.ships
Out[28]: [Ship('Destroyer', {(1, 2), (2, 2)})]
In [29]: s3 = Ship('Destroyer', {(4, 2), (3, 2)})
In [30]: g.add_ship(s3)
In [30]: g.ships
Out[30]: [Ship('Destroyer', {(1, 2), (2, 2)}), Ship('Destroyer', {(4, 2), (3, 2)})]
Afterwards, upload your file
battleship.py:
Exercise 3: Loading grids from files
To make adding ships to a grid an easier process, we will now write a
function to load them from a text file. To this end, first write
a function create_ship_from_line that returns a
ship encoded as a line as follows:
- Each line consists of several entries separated by spaces.
- The first entry on a line is the name of the ship.
- The other entries on the line are of the form
x:y, wherexandyare integers that encode the position of part of the ship on the grid.
For example: the line Destroyer 1:2 2:2 encodes
a ship to be created by
Ship('Destroyer', {(1, 2), (2, 2)}).
Write the function
create_ship_from_line (in battleship.py,
outside the Ship and Grid classes),
and test it, for example as follows:
In [31]: s = create_ship_from_line('Destroyer 1:2 2:2')
In [32]: s == Ship('Destroyer', {(1, 2), (2, 2)})
Out[32]: True
Now add a function
load_grid_from_file(filename) to battleship.py
(outside the Grid and Ship
classes). The first line of the file has the form
x_size:y_size, where x_size is the number of
columns and y_size is the number of rows. For example,
7:4 describes a grid with seven columns and four rows. Each
following line describes a ship in the format above. Your function
should return a Grid of the given dimensions containing the
ships from the file. You can use create_ship_from_line to
read each ship.
Test your function in the console:
In [33]: g = load_grid_from_file('grid1.txt')
In [34]: g.x_size
Out[34]: 5
In [35]: g.y_size
Out[35]: 5
In [36]: g.ships
Out[36]: [Ship('Destroyer', {(1, 2), (2, 2)})]
Afterwards, upload your file
battleship.py:
Exercise 4: Shooting at ships
So far, there has not been a lot of action in our battleship game. We will now start working on the actual shooting.
Add a method take_shot to your class
Ship. It should begin as follows:
def take_shot(self, shot):
"""Check if the shot hits the ship. If so, remember the hit.
Returns 'MISS', 'HIT', 'DESTROYED', or 'ALREADY_SHOT'.
"""Notice that shot is an (x, y) tuple. A
Ship remembers only hits to itself, so shooting twice at a
position outside this ship returns 'MISS' both times.
If shot is already in this ship’s hits set,
return 'ALREADY_SHOT' and leave the ship unchanged. If the
coordinates do not belong to this ship, return 'MISS'.
Otherwise, add the coordinates to hits. Return
'DESTROYED' if this was the last intact part of the ship,
or 'HIT' if the ship is still afloat.
Test your function in the console:
In [37]: s = Ship('Destroyer', {(2, 2), (2, 3)})
In [38]: s.take_shot((1, 1))
Out[38]: 'MISS'
In [39]: s.take_shot((2, 2))
Out[39]: 'HIT'
In [40]: s.hits
Out[40]: {(2, 2)}
In [41]: s.take_shot((2, 2))
Out[41]: 'ALREADY_SHOT'
In [42]: s.take_shot((2, 3))
Out[42]: 'DESTROYED'
Afterwards, upload your file
battleship.py:
Exercise 5: Shooting at grids
Now that we can shoot at individual ships, let us shoot at the grid
next. Add a method shoot to the class Grid
that takes a position and returns a tuple. First check
whether position is already in misses or in
any ship’s hits set. For a new shot, call
take_shot to check for a hit.
- If
positionhas already been shot at, return('ALREADY_SHOT', None)and leave the grid and all ships unchanged. This applies to both an earlier hit and an earlier miss. - If this is the first shot at
positionand the cell contains no ship, addpositiontomissesand return('MISS', None). - If the shot hits a ship but leaves it afloat, return
('HIT', None). - If the shot destroys a ship
s, return('DESTROYED', s).
Test your methods as follows:
In [43]: g = load_grid_from_file('grid1.txt')
In [44]: g.shoot((1, 1))
Out[44]: ('MISS', None)
In [45]: g.shoot((1, 1))
Out[45]: ('ALREADY_SHOT', None)
In [46]: g.misses
Out[46]: {(1, 1)}
In [47]: g.shoot((1, 2))
Out[47]: ('HIT', None)
In [48]: g.shoot((1, 2))
Out[48]: ('ALREADY_SHOT', None)
In [49]: g.misses
Out[49]: {(1, 1)}
In [50]: g.shoot((2, 2))
Out[50]: ('DESTROYED', Ship('Destroyer', {(1, 2), (2, 2)}))
Afterwards, upload your file
battleship.py:
Exercise 6: Blind grids
We are now nearly ready to play Battleship. The only thing we still
have to do is to create a way to show our opponent the grid
without divulging the position of our ships. To this end, we
now introduce a second grid class which we call BlindGrid.
On a BlindGrid, one can only see which positions were shot
at, where there were hits, and which ships have been destroyed; in
particular, one cannot see ships that have not yet been
destroyed. Note that these are exactly the facts one knows about
the opponent’s grid when playing Battleship.
Write the class BlindGrid. It should
begin as follows:
class BlindGrid:
"""Encodes the opponent's view of the grid."""
def __init__(self, grid):The method __init__() should store the following values
in attributes:
x_sizeandy_sizecontain the same values as ingrid,misses, a set containing the positions that have been shot at but that were misses,hits, a set containing the positions in which there were hits, andsunken_ships, a list containing the ships that are not afloat anymore.
Note that crucially, this is all of the information that we
will store in the BlindGrid. In particular, we do
not store the original Grid, nor any of
its Ships that are still afloat. (Doing so might allow our
opponent to cheat, by knowing where to shoot after all.)
Test your class BlindGrid as
follows:
In [51]: g = load_grid_from_file('grid1.txt')
In [52]: g.shoot((1, 1))
Out[52]: ('MISS', None)
In [53]: g.shoot((1, 2))
Out[53]: ('HIT', None)
In [54]: g.shoot((2, 2))
Out[54]: ('DESTROYED', Ship('Destroyer', {(1, 2), (2, 2)}))
In [55]: b = BlindGrid(g)
In [56]: b.misses
Out[56]: {(1, 1)}
In [57]: b.hits
Out[57]: {(1, 2), (2, 2)}
In [58]: b.sunken_ships
Out[58]: [Ship('Destroyer', {(1, 2), (2, 2)})]
Afterwards, upload your file
battleship.py:
Exercise 7: Random ship positions
Playing our implementation of Battleship is not very challenging:
since you create the Grid for the opponent yourself, you
always know where the Ships are, so you can sink them
without any misses.
To make the game more interesting, write a function that places
Ships randomly.
To this end, add import random to the
beginning of your battleship.py file, and then use the randint method of
the random module. Immediately below this, add this
line to your battleship.py file.
# List of tuples: (name, length) where length is the number of positions of your ship
ship_types = [('Battleship',4),('Carrier',5),('Cruiser',3),('Destroyer',2),('Submarine',3)]Add a method random_ship to the class
Grid. For random ship placement, you may assume that
x_size and y_size are both at least 5, so
every ship type fits in either orientation. Choose a type from
ship_types, giving each type the same chance. The same type
may be chosen on different calls. Choose a horizontal or vertical
orientation at random, then choose a random starting position that keeps
the whole ship inside the grid. The ship’s cells must be consecutive in
one row or column. Return the ship without adding it to the grid.
def random_ship(self):Try your method in the console. Your output will vary.
In [59]: g = Grid(10,10)
In [60]: g.random_ship()
Out[60]: Ship('Battleship', {(9, 5), (9, 6), (9, 3), (9, 4)})
In [61]: g.random_ship()
Out[61]: Ship('Destroyer', {(2, 3), (2, 2)})
Add a method create_random to the class
Grid. Generate random ships and try to add them with
add_ship() until the grid contains n ships in
total. If a candidate overlaps an existing ship, try again. For example,
if the grid already has two ships, create_random(5) adds
three. If it already has n or more ships, leave it
unchanged.
You may assume there is room to place at least one more ship at the
start and after each successful placement whenever the grid contains
fewer than n ships. This holds in the game example, which
places five ships on an empty 10 × 10 grid.
def create_random(self, n):Try your method in the console. Your output will vary.
In [62]: g = Grid(10,10)
In [63]: g.create_random(5)
In [64]: print(g.ships)
[Ship('Destroyer', {(8, 2), (8, 3)}), Ship('Destroyer', {(3, 3), (3, 4)}), Ship('Battleship', {(0, 1), (0, 2), (0, 3), (0, 0)}), Ship('Submarine', {(8, 7), (8, 8), (8, 6)}), Ship('Submarine', {(6, 1), (6, 2), (6, 0)})]
Upload your file battleship.py:
Playing the game
After saving battleship.py, run these commands in a
fresh Spyder console.
In [65]: from battleship import Grid
In [66]: from graphics import Battleship
In [67]: g1 = Grid(10, 10)
In [68]: g2 = Grid(10, 10)
In [69]: g1.create_random(5)
In [70]: g2.create_random(5)
In [71]: game = Battleship(g1, g2)
In [72]: game.mainloop()
The upper grid shows your ships. Click a cell on the lower grid to shoot at your opponent. Your hits appear as red circles, and your misses appear as blue circles. When you sink an opponent’s ship, its cells are filled with red squares. Clicking a cell you have already shot at leaves its marker unchanged.
After each click, the default opponent chooses a cell on your grid at random. If it has already fired at that cell, it skips its turn. On your grid, the opponent’s hits appear as yellow circles and its misses as blue circles.
Exercise 8 (optional): (almost) Artificial intelligence
The default strategy, random_shoot() in
graphics.py, uses the grid dimensions to pick a random
cell. If that cell has already been tried, the opponent skips its
turn.
Write a strategy function in battleship.py that takes a
BlindGrid and returns an (x, y) tuple for a
cell inside the grid. Use the information in the BlindGrid
to choose a better target.
To try your strategy, follow the launch instructions above through
creating game. Then run these commands, replacing
my_strategy with the name of your function. Set the
strategy before calling game.mainloop().
In [73]: from battleship import my_strategy
In [74]: game.strategy = my_strategy
In [75]: game.mainloop()
Upload your file battleship.py: