Python Forum
Help coding the computers ship placements in battleships
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help coding the computers ship placements in battleships
#1
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?
Reply
#2
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
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Accessing same python script from multiple computers bigrockcrasher 1 1,707 May-25-2022, 08:35 PM
Last Post: Gribouillis
  “NameError” “is not defined” script that I know works on other computers iamwithstupid 0 2,522 Nov-24-2020, 04:23 PM
Last Post: iamwithstupid

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020