Let's look in a little more detail at the solution to Lab 6.

Here is the make_computer_move_attack(board, mark) function. The function makes use of the is_win(board, mark) function, which returns True iff mark has won on board board. The strategy is to try every possible move, see if it resulted in a win, return (and stop the execution of the function) if it did, and undo it if it didn't.

In [1]:
def make_computer_move_attack(board, mark):
    '''If possible, make a winning move using mark mark on the board. If not,
    put the mark mark in the first available square, where we're going 
    through the square in the order
    for i in range(3):
      for j in range(3)
      
    Aruguments:
    board -- a list of lists of strings representing a 3x3 table of " ", "X", and "O". Assume board is not full.
    mark -- "X" or "O"
    '''
    
    #First, we look through all the squares and
    for i in range(3):
        for j in range(3):
            #Only try to make the move at (i, j)
            #if the square is current empty
            if board[i][j] == " ":
                board[i][j] = mark
                if is_win(board, mark):
                    #We found the winning move -- keep the move
                    #on the board, and stop the function
                    return
                
                #is_win(board, mark) is False, so we should undo
                #the move and keep going.
                board[i][j] = " "
            
    #If we reached this point, we haven't found a winning move. Go
    #through the board until we find an empty square, put mark
    #there, and return
    for i in range(3):
        for j in range(3):
            if board[i][j] == " ":
                board[i][j] = mark
                return