< Prev  |  Home  |  Next >

Python Battleships Game

In this challenge, I’ll give you a starting point for creating your own battleships game, and then it’s up to you to apply everything you’ve learnt to make the finished game.

Anyway, first I’d like you to image a simple gameshow game where a contestant has to choose one of 3 doors, and there’s a prize (maybe a speedboat or a bacon sandwich) behind one of the doors.

We could model the game in Python like this:

The only thing I’ll point out here is the relationship between the guess (1-3) and the array of doors (0-2). We have to subtract 1 from the guess to find the correct array position of the door.

Remember when we learnt about 2-dimensional arrays when using lists, and could do something like this:

Which prints the first character of the second list item (“t”).

We can use 2-dimensional arrays in this way to model, say, a noughts and crosses board.

In this program, the variable “board” represents a 3×3 grid:

o/x board

So for our battleships challenge, we could imagine a 10×10 board, with a “X” representing a boat (a hit) and a “O” representing nothing (a miss).

We can use x and y co-ordinates to access a board position with the general code:

Where ‘y’ and ‘x’ are integer variables.

If a player guesses a boat position correctly, we could use something like:

To “sink” the boat.

There aren’t really any rules about what your finished game should be like; you can include any features that you’ve learnt about. For example, you could allow two players to choose their boat location (by editing “boardA” and “boardB” list variables), you could let them take turns guessing their opponent’s boat positions, or even save the game to come back to later!

Good luck.

< Prev  |  Home  |  Next >