As part of the course I am taking to improve my programming skills, I have decided to code a Battleship game to be played using the command line.
Github link to code: https://github.com/guachilimbo/battleship
Battleship is a two player board game where the objective is to sink all of your opponent's ships. Each turn, the players will "bomb" a grid cell (e.g. "C7"). If a boat is occupying the cell, the boat will be "hit". Otherwise it will be a "miss".
- Carrier - 5 cells
- Battleship - 4 cells
- Cruiser - 3 cells
- Submarine - 3 cells
- Destroyer - 2 cells
The game is played against the CPU. Upon inisialisation, the user will be given a prompt to choose the initial cell the boat will occupy, and whether you want to position the boat vertically or horizontally. This process is repeated for each boat:
The CPU board is set up using Python's random library:
columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] rows = list(range(10)) def random_cell(self): return "".join([random.choice(Play.columns),str(random.choice(Play.rows))])
Playing the game
Using a similar logic as the set up, the CPU will randomly choose a cell to bomb. If there is a boat on that cell of the player's grid, the cell will be updated with an "x" to show that the boat has been hit. Otherwise, the cell will be updated with a "~" to show the bomb missed.
A list keeps track of the number of hits a boat has received. When the number of hits equals the length of the boat (i.e. number of lives), the number of boats left displayed under the grids, changes. Allowing the user to know how many (and which) boats are left.
The user experience can be easily improved by user-proofing the code. Right now certain inputs will cause the code to crash. Wanted to move on from this project to learn more stuff, so will improve it in the future.
The game's difficulty is too easy. This is due to the computer randomly choosing a cell from a decreasing list of 100. It would be fun to implement different algorithms to increase the difficulty once I learn a bit more.