def gen_ship_coords(anchor, size, direction): """Generate ship board coordinate based on anchor location and size The ship coordinates start at the anchor position and run Down for vertical direction and run Right for horizontal direction. Verify ship fits on board. Args: anchor (str): two character board coordinate "A1" size (int): size of ship in board spaces orientation (str): is ship Horizontal or Vertical Returns: List[str]: list of board coordinates, if valid. Empty list otherwise. """ ship_col = ord(anchor[0].upper()) ship_row = int(anchor[1:]) if direction[0].lower() == 'v': # ship runs vertically DOWN from anchor coords = [chr(ship_col) + str(row) for row in range(ship_row, ship_row + size)] else: # ship runs horizontally RIGHT from anchor coords = [chr(col) + str(ship_row) for col in range(ship_col, ship_col + size)] # check if ship bow and stern are on board if is_legal_coord(coords[0]) and is_legal_coord(coords[-1]): # coords confirmed return coords else: # bad ship coords print("Error: not all coords on board: ", coords) return []
def get_anchor_coord(): """Ask user for ship anchor coordinates""" while True: response = input("What is the upper-most or left-most ship postion " "(for example D4): ").strip() anchor = response.upper() if is_legal_coord(anchor): return anchor else: print("Coordnate {} is not on the board. Please enter Letter " "and Number as one word.".format(response))
def gen_ship_coords(anchor, size, direction): """Generate ship board coordinate based on anchor location and size The ship coordinates start at the anchor position and run Down for vertical direction and run Right for horizontal direction. Verify ship fits on board. Args: anchor (str): two character board coordinate "A1" size (int): size of ship in board spaces orientation (str): is ship Horizontal or Vertical Returns: List[str]: list of board coordinates, if valid. Empty list otherwise. """ ship_col = ord(anchor[0].upper()) ship_row = int(anchor[1:]) if direction[0].lower() == 'v': # ship runs vertically DOWN from anchor coords = [ chr(ship_col) + str(row) for row in range(ship_row, ship_row + size) ] else: # ship runs horizontally RIGHT from anchor coords = [ chr(col) + str(ship_row) for col in range(ship_col, ship_col + size) ] # check if ship bow and stern are on board if is_legal_coord(coords[0]) and is_legal_coord(coords[-1]): # coords confirmed return coords else: # bad ship coords print("Error: not all coords on board: ", coords) return []
def get_guess(player): """Ask user for guess""" while True: response = input("Enter {}'s guess (for example D4): " "".format(player.name)).strip() guess = response.upper() if guess in player.guesses: print("Coordnate {} already guessed. Try Again." "".format(response)) continue if is_legal_coord(guess): return guess else: print("Coordnate {} is not on the board. Please enter Letter " "and Number as one word.".format(response))