Python Forum
Help coding the computers ship placements in battleships - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help coding the computers ship placements in battleships (/thread-14555.html)



Help coding the computers ship placements in battleships - MAZambelli4353 - Dec-06-2018

Im trying to code random placements for the computer's ships into the 10x10 grid. The five ships are of lengths 2, 3, 3, 4, and 5. If you are unaware of the game, the ships cant be diagonally placed, only vertical and horizontal. I cant seem to get around all the problems that arise such as two ships overlapping or their positions simply being illegal. I mean I could code it but it would be extremely tedious and ugly. Is there some elegant way of doing something like this?


RE: Help coding the computers ship placements in battleships - ichabod801 - Dec-06-2018

I've done this. First you have an adjacent_squares function that returns the four squares around a given square. I'm assuming you've figured out how to get the squares for a ship. For the first ship you add the squares to the player's board. Then you add those squares, and all of their adjacent squares (because to ships can't be next to each other either) to a set called invalid_squares. For the second and later ships, you check each square in the ship to see if it's in invalid_squares. Only if none of them are in invalid_squares do you add the ship to the player's board. Then again, you add those squares and the adjacent squares to invalid_squares.

while True:
    ship = get_new_ship()
    for square in ship:
        if square in invalid_squares:
            print_warning()
            break
    else:
        break