I found a code academy lesson about battleship game and I'm trying to expand it a little. I added some code that allows to place multiple ships on the board but I've run into some issues when randomly placing ships namely, the ships sometimes overlaps.
As you see S should be of length 3. But B overlaps that. Below is the place_ship function. I would really appreciate some advice on what to fix.
def place_ship(board, ship_name):
global ship_count, hiddenBoard
ship = ""
size = 0
if ship_name == "Destroyer":
ship, size = "D", 2
elif ship_name == "Submarine":
ship, size = "S", 3
elif ship_name == "Battleship":
ship, size = "B", 4
ship_row, ship_col = random_row(board), random_col(board)
orientation = bool(random.getrandbits(1))
if orientation:
while hiddenBoard[ship_row][ship_col] != "D" or "S" or "B":
if ship_col + size not in range(10):
ship_col -= size
if ship_row + size not in range(10):
ship_row -= size
for x in range(0, size):
hiddenBoard[ship_row][ship_col + x] = ship
ship_count += 1
break
else:
while hiddenBoard[ship_row][ship_col] != "D" or "S" or "B":
if ship_row + size not in range(10):
ship_row -= size
if ship_col + size not in range(10):
ship_col -= size
for x in range(0, size):
hiddenBoard[ship_row + x][ship_col] = ship
ship_count += 1
break
Aucun commentaire:
Enregistrer un commentaire