Hi I have a program that randomly places ships on the battlefield but I've ran into some problems namely, ships sometimes overlaps or not all of them are placed or none of them are placed. Below is the whole program without class Ship initialized with size parameter.
import random
from Ship import Ship
def make_board(board):
for x in range(0, 10):
board.append(["_"] * 10)
def print_board(board):
for row in board:
print(" ".join(row))
def random_row(board):
return random.randint(0, len(board) - 1)
def random_col(board):
return random.randint(0, len(board) - 1)
def place(ships, board):
hidden_board = []
for x in range(0, 10):
hidden_board.append(["_"] * 10)
print("jestem w place")
dir_list = ["North", "South", "East", "West"]
for x in range(0, len(ships), 1):
placed = False
while not placed:
ship_row, ship_col = random_row(board), random_col(board)
print(ship_row, ship_col)
if hidden_board[ship_row][ship_col] == "_":
hidden_board[ship_row][ship_col] = "C"
if board[ship_row][ship_col] == "_":
direction = random.choice(dir_list)
if validate(ships[x], ship_row, ship_col, direction):
place_ship(ships[x], ship_row, ship_col, direction)
placed = True
def place_ship(ships, ship_row, ship_col, direction):
size = ships.get_size()
print(direction)
if direction == "North":
for x in range(ship_row, ship_row - size, -1):
board[x][ship_col] = "S"
elif direction == "South":
for x in range(ship_row, ship_row + size, 1):
board[x][ship_col] = "S"
elif direction == "East":
for x in range(ship_col, ship_col + size, 1):
board[ship_row][x] = "S"
elif direction == "West ":
for x in range(ship_col, ship_col - size, -1):
board[ship_row][x] = "S"
def validate(ships, ship_row, ship_col, direction):
size = ships.get_size()
print("Jestem w can_place")
is_free = True
if direction == "North":
if ship_row - size <= 0:
is_free = False
else:
for x in range(ship_row, ship_row - size and is_free, -1):
is_free = is_free
board[x][ship_col] = "_"
elif direction == "South":
if ship_row + size > 10:
is_free = False
else:
for x in range(ship_row, ship_row + size and is_free, 1):
is_free = is_free
board[x][ship_col] = "_"
elif direction == "East":
if ship_col + size > 10:
is_free = False
else:
for x in range(ship_col, ship_col + size and is_free, 1):
is_free = is_free
board[ship_row][x] = "_"
else:
if ship_col - size <= 0:
is_free = False
else:
for x in range(ship_col, ship_col - size and is_free, 1):
is_free = is_free
board[ship_row][x] = "_"
return is_free
if __name__ == "__main__":
board = []
make_board(board)
ships = [Ship(3), Ship(2), Ship(1)]
place(ships, board)
print_board(board)
print("\n")
Aucun commentaire:
Enregistrer un commentaire