DEV Community

ptrick72
ptrick72

Posted on

Terminal-based Battleship Game in Python3

As part of my final project for the CS101 module of the computer science path in codecademy, I made a terminal-based battleship game in which you can play against the computer. The game is written in python3 and it was fun to make.

Each player (you and the computer) have a 7x7 grid to place their ships. There are 3 ships to place: Warship, Cruiser and Destroyer.

I have defined different classes for the main game objects, f.e. ship, grid, player. The computer player which I named HAL is a class that inherits from the player class. The game routine itself is a class named Battleship and it as a play function.

By making a game from the Battleship class HAL gets initialized and his ships get placed. By calling play() you as the player must enter your name and the starting point and alignments of your ships, so that they can be placed in your grid.

After all ships have been placed you and HAL take turns in shooting by giving a x-y-point to the shoot function of the Player class. Each player has also a shot list to keep track of his shots. If a ship is hit, the ship’s own hit attribute gets increased. The Ship class also provides an is_destroyed() function to check if a ship is destroyed. This is done by simply checking if the hit count is equal to the ship size. After each shot there is a check whether all enemy ships are down and the game is won. Each time you make an input, you can type „q“ of „Q“ to quit the game.

The game helped me to dive into python3 and I feel like there are still many ways to optimize the code and the game. F.e. I think it would be nice to have all the texts in one place and not distributed over the code. Maybe something like an TextHandler class that validates all inputs and prints out all texts. A restart function could also be nice.

If you are interested in trying the game you can find it here:
https://github.com/ptrick72/Battlehsip-Game.git

This is how the game looks like:

Image description

Top comments (0)