DEV Community


Posted on

Battleship!... On Command Line

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:

What is Battleship?
Battleship Game box

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".

Game set up
Game grid
For my game, I have decided to create a 10x10 alphanumerical grid. Each player will have 5 different boats with different lengths:

  1. Carrier - 5 cells
  2. Battleship - 4 cells
  3. Cruiser - 3 cells
  4. Submarine - 3 cells
  5. 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:
GIF showing game set up on command line

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))])
Enter fullscreen mode Exit fullscreen mode

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.

The player logic is the same but the user has to input the desired cell. The code will warn the user if an already bombed cell has been chosen.
GIF showing game play on command line

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.

End game
GIF showing game end
The game end when one side has lost all of the boats. The code terminates and outputs a message to restart if the user wishes to.

Future improvements

  • 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.

Top comments (0)