Everyone would have played Battleship at least once in their lifetime, right? It is an exciting game and is loads of fun. However, the pen and paper version of Battleship is old-fashioned. Let's go modern now. Let us program the entire game in Python. The code may be extended and confusing with all the rules and conditions but is quite simple once you understand it.
If you don't know what Battleship is, it is a two-player game played with a book and a pen or nowadays with unique boards or computers. Each player arranges a set of 'ships' of different lengths in a 10x10 grid or panel. The game's objective is to call out cells and find the opponent's ships before they find yours. Here is a more detailed version of the rules: Rules of Battleships
If we develop a basic algorithm out of this, here is how it would go...
The first step would be to generate a board. Two 10x10 panels are used for Battleships. Nested lists are the most suitable data type for this purpose.
Next, the ships need to be placed. Each ship has a name and a different length. We can use letters to identify the different ships. Here are the 5 ships:
Aircraft Carrier (5 spaces), Battleship (4 spaces), Cruiser (3 spaces), Submarine (3 spaces), and Destroyer (2 spaces).
They must be placed so that each ship takes up the corresponding number of spaces vertically or horizontally without colliding with another ship.
Next, the computer must randomly place its ships (the same set of ships). The computer needs to ensure that it puts its ships without collisions.
Now, let us go to the actual game. Make your move. If there is part of a ship in that spot, the game returns "Hit !" and the player gets another chance. Else, the computer returns "Miss." This result needs to be updated on your reference board and marked if it is a Hit.
There is no Battleship AI for the opponent, so it makes a random move that it has not made before. The computer's move must also be updated on your board to know how many ships have been damaged or sunk. Once all of your ships have been sunk, or the opponent's ships have been sunk, the game must tell 'game over' and show the winner.
Keeping all these points in mind, let's try to convert English to Python.
Here's the Battleships source code: Click this Link
Once you are done coding, you are good to go. Enjoy a game with your computer and see who ends up winning.
If you found this interesting, do check out these other posts:
Comments
Post a Comment