I have my battleships game working completely accept ships do not generate randomly. I have each point of the ship assigned to certain squares.

Example:

ship_1_1 = Grid[1][1]
ship_1_2 = Grid[1][2]
ship_1_3 = Grid[1][3]
ship_1_4 = Grid[1][3]

Randomly generating ships is harder than I thought. For these reasons:
- Ships cant overlap
- Ships must be within the gamegrid
- Ships must randomly generate
- Ships must be going down or across.

Any ideas of how to make the ships randomly generate while avoiding these problems?

Thanks.

Use a while loop to generate random numbers until a valid number occurs:
- Ships can't overlap --> keep track of the occupied squares in a list
- Ships must be within the gamegrid --> you can supply a range for rows and a range for columns
- Ships must be going down or across --> randomly choose 0 (across) or 1 (down) and then get a random number for column start or row start.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.