jeudi 23 avril 2020

How can I place the ships randomly in a BattleShip Game?

I've coded a battleship game, where the 1x1 sized ships were placed randomly.

Now I'm trying to code one, where the ships will have 3x1 size. First I changed the size to 2x1, and tried to get in total 5 ships horizontal and vertical too...but it still has some issues/problems.

Here it is how I tried with with ships of 2x1:

  import random

  board = []
  matrix = []
  total_ships = 0
  horizontal = 0
  vertical = 0
  ship_number = 1

 for i in range(8):
     board = []
  for j in range(8):
     board.append("o")
  matrix.append(board)

while total_ships != 5:

  horizontal = random.randint(1, 7)
  vertical = random.randint(1, 7)

  if matrix[vertical][horizontal] == "o":
      matrix[vertical][horizontal] = ship_number
  if vertical > 1 and matrix[vertical - 1][horizontal] == "o":
      matrix[vertical - 1][horizontal] = ship_number
  elif vertical < 1 and matrix[vertical + 1][horizontal] == "o":
      matrix[vertical + 1][horizontal] = ship_number
  elif horizontal > 1 and matrix[vertical][horizontal - 1] == "o":
      matrix[vertical][horizontal - 1] = ship_number
  elif horizontal < 1 and matrix[vertical + 1][horizontal] == "o":
      matrix[vertical][horizontal + 1] = ship_number

  ship_number += 1
  total_ships += 1

How could I do it to work properly, with ships of 3x1 size, or at least 2x1? Thanks for your help!!




Aucun commentaire:

Enregistrer un commentaire