I'm creating a battleship console game in Python.
In my game, the AI will have 3 ships, each 3 squares long. A ship's square will be denoted with an 'O' and a water square will be denoted with a '*'. The grid is a 7x7 2D list.
When I run my code, most of the time it works fine. The create_board
function works fine, creating 3 ships with a width of 3 squares each.
However, sometimes, one ship overlaps with another one. This results in 2 ships of length 3 squares and 1 ship of length 2. To counteract this, I've checked if there are 9 ship squares in total and if not, I have called the function again to restart the ship creation.
However, when this happens, the ship does not return and I get an error saying that the list is null.
How can I ensure the ships never overlap? How can I ensure there are always 3 ships each of length 3 squares?
Thank you.
import random
ai_board = [['*' for _ in range(7)] for _ in range(7)]
def create_board(starting_board):
for i in range(3):
anchor_x = random.randint(0, 6)
anchor_y = random.randint(0, 6)
starting_board[anchor_y][anchor_x] = 'O'
orientation = random.choice(['h', 'v'])
if orientation == 'h':
if anchor_x > 4:
starting_board[anchor_y][anchor_x-1] = 'O'
starting_board[anchor_y][anchor_x-2] = 'O'
else:
starting_board[anchor_y][anchor_x+1] = 'O'
starting_board[anchor_y][anchor_x+2] = 'O'
else:
if anchor_y > 4:
starting_board[anchor_y-1][anchor_x] = 'O'
starting_board[anchor_y-2][anchor_x] = 'O'
else:
starting_board[anchor_y+1][anchor_x] = 'O'
starting_board[anchor_y+2][anchor_x] = 'O'
ship_count = 0
for row in starting_board:
for column in row:
if column == 'O':
ship_count += 1
if ship_count == 9:
return starting_board
if ship_count < 9:
new_board = [['*' for _ in range(7)] for _ in range(7)]
create_board(new_board)
ai_board = create_board(ai_board)
for row in ai_board:
print(" ".join(row))
I tried running the function again within the function, expecting it to fix the board until it comes out with 3 ships of length 3. What actually happened was an error as a result of my function not returning anything.