Oct-17-2022, 06:09 PM
(This post was last modified: Oct-17-2022, 09:51 PM by deanhystad.)
I would modify ships to be ["S", 3, 1] for [marker, length, level]. I find that the code, especially in Python, looks better if you use data instead of code. Sure you could write a bunch of if staetments:
https://docs.python.org/3/library/collec...med-fields
level = 0 if ship[1] > 2: level = 1 if ship[1] > 3: level = 2 if ship[1] > 4: level=3But this looks better and is easier to modify if I want to change how the ships are placed.
level = ship[2]You should look at named tuples. ship.length is much easier to understand than ship[1].
https://docs.python.org/3/library/collec...med-fields
from collections import namedtuple from random import randint, choice Ship = namedtuple("Ship", ["marker", "length", "level"]) def print_level(level): """Print a level""" print(" A B C D E F G H I J") for index, row in enumerate(level, start=1): print(f"""{index:>2} {" ".join(row)}""") print() def make_level(): """Make an empty 10 x 10 level.""" return [["-"] * 10 for _ in range(10)] def place_ship(ship, level): """Add ship to level""" # Keep trying to add the ship until we find a position where it fits. while True: x = randint(0, 9) y = randint(0, 9) dx, dy = (1, 0) if choice([True, False]) else (0, 1) # horizontal or vertical try: # Can we put the ship at x, y? for i in range(ship.length): if level[y + dy*i][x + dx*i] != '-': raise IndexError() # Collision with other ship # The ship fits. Add it to the board. for i in range(ship.length): level[y + dy*i][x + dx*i] = ship.marker return except IndexError: pass # Divide ships among boards board = [make_level() for _ in range(3)] ships = (Ship("D", 2, 0), Ship("C", 3, 1), Ship("S", 3, 1), Ship("B", 4, 2), Ship("A", 5, 2)) for ship in ships: place_ship(ship, board[ship.level]) for level in board: print_level(level) # Put all the ships on the same board board = make_level() ships = (Ship("A", 5, 0), Ship("B", 4, 0), Ship("S", 3, 0), Ship("C", 3, 0), Ship("D", 2, 0)) for ship in ships: place_ship(ship, board) print_level(board)