For exercise 19 - Extra Credit, in lesson 13 - Battleship!, one of the enhancements is to add multiple differently-sized battleships. I've found a way to place multiple, non-overlapping randomly-sized ships (up to a max size). However, I'm having trouble with hit tracking.
Currently, I store all coordinates of all ship sections in a set (
ships). I attempt to place an individual ship (
temp_ship), and add it to
ships if it doesn't overlap with an existing ship. Then I check for hits using
(guess_row, guess_col) in ships.
What I can't figure out is how to separately track hits for each ship, so that I can tell when all sections of a ship are hit and the ship is sunk. I've seen several solutions utilizing classes or hardcoding hit detection for this purpose, but I was wondering if this was possible without doing so.
def place_ships(ships, board_dim, num_ships, max_size = 1): ship_num = 0 while ship_num < num_ships: ship_length = randint(1, max_size) temp_ship = set() if randint(0,1) == 0: # horizontal placement, left to right bow_col = random_one_coord(board_dim + 1 - max_size) bow_row = random_one_coord(board_dim) for col in range(bow_col, bow_col + ship_length): temp_ship.add((col, bow_row)) else: bow_col = random_one_coord(board_dim) bow_row = random_one_coord(board_dim + 1 - max_size) for row in range(bow_row, bow_row + ship_length): temp_ship.add((bow_col, row)) if len(ships.intersection(temp_ship)): # don't place ship if overlap continue else: for coord in temp_ship: ships.add(coord) ship_num += 1
Thanks for reading!