task3_5.py 2.07 KB
from task2 import check_valid_coord


def ask_coordinates(board):
    """
    Ask the player for valid coordinates on a board in an x,y format.
    
    Args:
        board (list[list[bool]]): ship or hit board. 
        False represents an empty space, and True represents a ship or hit.
    
    Returns:
        tuple[int, int]: valid x and y coordinates.
    """
    need_to_check = True
    # Until all conditions have been fulfilled, the user is asked to input new
    # coordinates as the previous ones were not valid. The variable 
    # need_to_check is initially set to True and set to False once all of the 
    # conditions have been fulfilled, to exit the while loop.
    while need_to_check:
        user_input = input("Enter the desired coordinates x,y: ")
        if ',' in user_input:

            # TODO: modify the following line of code to split the user's input
            # by comma and set the variable coordinates to the resulting list
            # of 2 elements (x-coordinate and y-coordinate).
            coordinates = user_input

            # TODO: modify the following conditional to check that the list 
            # coordinates is indeed of size 2 and that its first and second
            # elements are both digits.
            if placeholder:

                # TODO: Modify the two following lines of code to cast each 
                # coordinate to integers and modify their value to make them 
                # suitable for indexing on our boards. Hint: Remember, user 
                # input should be between 1 and 7 but the indices in our 
                # boards go from 0 to 6 because of zero-indexing.
                x = coordinates[0]
                y = coordinates[1]

                if check_valid_coord((x, y), board) and not board[y][x]:
                    need_to_check = False
                else:
                    print('Make sure that the location is valid!')
            else:
                print('Your coordinates must be 2 numbers!')
        else:
            print('Your coordinates format is invalid! Please enter as x,y.')
    return x, y