Project- Game of Tic Tac Toe with Python

12 / 16

Tic Tac Toe with Python - Define the moves of the AI

Now we will write the logic where the AI will determine the best moves. Here will will provide a number of positions which are considered the best positions to have, we will also write the logic where the AI will ensure that if the computer is winning by a move, it takes that move, else if the human player is winning because of a move, it blocks that.

INSTRUCTIONS
  • Write a function computer_move as shown below:

    def <<your code goes here>>(board, computer, human):
        board = board[:]
    
        BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)
    
        print("I shall take square number", end=" ")
    
        for move in legal_moves(board):
            board[move] = computer
            if winner(board) == computer:
                print(move)
                return move 
            board[move] = EMPTY
    
        for move in legal_moves(board):
            board[move] = human
            if winner(board) == human:
                print(move)
                return move
            board[move] = EMPTY
    
        for move in BEST_MOVES:
            if move in legal_moves(board):
                print(move)
                return move
    
See Answer

No hints are availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...