get_move Function

The get_move function is redefine below so we can take a closer look at it:

# Get Move function.
# Prompt and re-prompt human player ('X' or 'O')
# until a valid move of form 'row, col' has been
# entered at an available square. Then enter move
# into the grid and re-print the grid display.

def get_move(player_ch):
    while True:
        prompt = 'Enter move for ' + player_ch + ': '
        s = input(prompt)
        a_list = s.split(',')
        if len(a_list) >= 1 and int(a_list[0]) == 0:
            print('Bye now.')
            return True, 0, 0 # Throw 'EXIT' flag
        elif len(a_list) < 2:
            print('Use row, col. Re-enter.')
        else:
            # First, convert to 0-based indexes.
            r = int(a_list[0]) - 1
            c = int(a_list[1]) - 1
            if r < 0 or r >= n or c < 0 or c >= n:
                print('Out of range. Re-enter.')
            elif mat[r][c] != '.':
                print('Occupied square. Re-enter.')
            else:
                mat[r][c] = player_ch
                print_mat()
                break
    return False, r, c # Do not throw 'EXIT' flag

The function prompts and re-prompts until it gets valid input. The function returns three values: exit_flag, r, and c. The last two, r and c, aren’t used in this version of the program but will be useful in Phase 2. The split method is extremely helpful in reading user input. It conveniently splits an input line into a list of individual strings.

The else clause (in line 17) is reached if the input is in the form r, c: a comma-separated list of two integers. The statements in this clause test the other conditions necessary to accept the move. Note that this else clause has a nested if-else clause of its own:

                r = int(a_list[0]) - 1
            	c = int(a_list[1]) - 1
            	if r < 0 or r >= n or c < 0 or c >= n:
                     print(‘Out of range. Re-enter.’)
            	elif mat[r][c] != ‘.’:
              	     print(‘Occupied square. Re-enter.’)
		 else:
      		     mat[r][c] = player_ch
             	     print_mat()
             	     break

The first thing this block of code does is to interpret the two items entered, converting 1-based index numbers to 0-based indexes. Valid moves run from (1,1) to (3,3), and these are converted to actual coordinates, running from (0,0) to (2,2). If the input passes all tests (the last else), the program places an X or O into the grid as appropriate, calls the print_mat function, and breaks the re-prompting cycle.

Note: Python lists evaluate to None if empty; therefore, when tested as conditions, they are equivalent to False if empty and True otherwise. This means that the following line of code:

       if len(a_list) >= 1 and a_list[0] == ‘0’:

Can be replaced by this shorter line:

                if a_list and a_list[0] == ‘0’:

Last updated

Was this helpful?