Battleship Challenge

BattleShip_CallengeFor this challenge we are not going to recreate a full battleship game. Instead we are going to focus on randomly placing the ships on the grid using an algorithm.

The code given below uses Python Turtle to draw the full grid.
The grid is a 10 by 10 array. As Python does not support 2-dimensional arrays we created a list of lists instead.

The grid is first initialised with the value 0 in each cell of the array.
To place a ship you change the value from 0 to 1 on all the required cells.

This program uses four functions called:

  • addSubmarine to place a submarine (ship of size 1) on the grid. This function is already completed.
  • addDestroyer to place a destroyer (ship of size 2) on the grid. You need to complete this function.
  • addCruiser to place a cruiser (ship of size 3) on the grid. You need to complete this function.
  • addAircraftCarrier to place an aircraft carrier (ship of size 4) on the grid. You need to complete this function.

Note that when placing a destroyer, cruiser or aircraft carrier, you can either place it horizontally or vertically. However before placing the ship on the grid you must ensure that:

  • All the cells used to place the ship are empty (No conflict with another ship on the grid),
  • The ship will not go off the 10 by 10 grid.

The code so far…

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: , , , ,