Giter Site home page Giter Site logo

19ai405expno6's Introduction

ExpNo 6 : Implement Minimax Search Algorithm for a Simple TIC-TAC-TOE game

Name: Meyyappan.T

Register Number:212223240086

Aim:

Implement Minimax Search Algorithm for a Simple TIC-TAC-TOE game

Theory and Procedure:

To begin, let's start by defining what it means to play a perfect game of tic tac toe:

If I play perfectly, every time I play I will either win the game, or I will draw the game. Furthermore if I play against another perfect player, I will always draw the game.

How might we describe these situations quantitatively? Let's assign a score to the "end game conditions:"

I win, hurray! I get 10 points! I lose, shit. I lose 10 points (because the other player gets 10 points) I draw, whatever. I get zero points, nobody gets any points. So now we have a situation where we can determine a possible score for any game end state.

Looking at a Brief Example To apply this, let's take an example from near the end of a game, where it is my turn. I am X. My goal here, obviously, is to maximize my end game score.

image

If the top of this image represents the state of the game I see when it is my turn, then I have some choices to make, there are three places I can play, one of which clearly results in me wining and earning the 10 points. If I don't make that move, O could very easily win. And I don't want O to win, so my goal here, as the first player, should be to pick the maximum scoring move.

But What About O? What do we know about O? Well we should assume that O is also playing to win this game, but relative to us, the first player, O wants obviously wants to chose the move that results in the worst score for us, it wants to pick a move that would minimize our ultimate score. Let's look at things from O's perspective, starting with the two other game states from above in which we don't immediately win:

image

The choice is clear, O would pick any of the moves that result in a score of -10.

Describing Minimax The key to the Minimax algorithm is a back and forth between the two players, where the player whose "turn it is" desires to pick the move with the maximum score. In turn, the scores for each of the available moves are determined by the opposing player deciding which of its available moves has the minimum score. And the scores for the opposing players moves are again determined by the turn-taking player trying to maximize its score and so on all the way down the move tree to an end state.

A description for the algorithm, assuming X is the "turn taking player," would look something like:

If the game is over, return the score from X's perspective. Otherwise get a list of new game states for every possible move Create a scores list For each of these states add the minimax result of that state to the scores list If it's X's turn, return the maximum score from the scores list If it's O's turn, return the minimum score from the scores list You'll notice that this algorithm is recursive, it flips back and forth between the players until a final score is found.

Let's walk through the algorithm's execution with the full move tree, and show why, algorithmically, the instant winning move will be picked:

image

  • It's X's turn in state 1. X generates the states 2, 3, and 4 and calls minimax on those states.
  • State 2 pushes the score of +10 to state 1's score list, because the game is in an end state.
  • State 3 and 4 are not in end states, so 3 generates states 5 and 6 and calls minimax on them, while state 4 generates states 7 and 8 and calls minimax on them.
  • State 5 pushes a score of -10 onto state 3's score list, while the same happens for state 7 which pushes a score of -10 onto state 4's score list.
  • State 6 and 8 generate the only available moves, which are end states, and so both of them add the score of +10 to the move lists of states 3 and 4.
  • Because it is O's turn in both state 3 and 4, O will seek to find the minimum score, and given the choice between -10 and +10, both states 3 and 4 will yield -10.
  • >Finally the score list for states 2, 3, and 4 are populated with +10, -10 and -10 respectively, and state 1 seeking to maximize the score will chose the winning move with score +10, state 2.
  • ##A Coded Version of Minimax Hopefully by now you have a rough sense of how th e minimax algorithm determines the best move to play. Let's examine my implementation of the algorithm to solidify the understanding:

    Here is the function for scoring the game:

    @player is the turn taking player

    def score(game) if game.win?(@player) return 10 elsif game.win?(@opponent) return -10 else return 0 end end Simple enough, return +10 if the current player wins the game, -10 if the other player wins and 0 for a draw. You will note that who the player is doesn't matter. X or O is irrelevant, only who's turn it happens to be.

    And now the actual minimax algorithm; note that in this implementation a choice or move is simply a row / column address on the board, for example [0,2] is the top right square on a 3x3 board.

    def minimax(game) return score(game) if game.over? scores = [] # an array of scores moves = [] # an array of moves

    # Populate the scores array, recursing as needed
    game.get_available_moves.each do |move|
        possible_game = game.get_new_state(move)
        scores.push minimax(possible_game)
        moves.push move
    end
    
    # Do the min or the max calculation
    if game.active_turn == @player
        # This is the max calculation
        max_score_index = scores.each_with_index.max[1]
        @choice = moves[max_score_index]
        return scores[max_score_index]
    else
        # This is the min calculation
        min_score_index = scores.each_with_index.min[1]
        @choice = moves[min_score_index]
        return scores[min_score_index]
    end
    

    end


    Program

    '''py

    class TicTacToe:

    def __init__(self):
        self.board = [' ']*9
        self.players = ['X', 'O']
        self.active_player = 'X'
    
    def print_board(self):
        # Print the current state of the board
        for i in range(0, 9, 3):
            print('|'.join(self.board[i:i+3]))
            if i < 6:
                print('-'*5)
    
    def get_available_moves(self):
        # Return a list of available moves (empty cells)
        return [i for i, mark in enumerate(self.board) if mark == ' ']
    
    def apply_move(self, move):
        # Apply the move to the board
        self.board[move] = self.active_player
        # Switch active player
        self.active_player = self.players[(self.players.index(self.active_player) + 1) % 2]
    
    def is_winner(self, player):
        # Check if the given player has won
        winning_combinations = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],  # Rows
            [0, 3, 6], [1, 4, 7], [2, 5, 8],  # Columns
            [0, 4, 8], [2, 4, 6]              # Diagonals
        ]
        for combo in winning_combinations:
            if all(self.board[i] == player for i in combo):
                return True
        return False
    
    def is_full(self):
        # Check if the board is full
        return ' ' not in self.board
    
    def is_terminal(self):
        # Check if the game is in a terminal state (win, draw)
        return self.is_winner('X') or self.is_winner('O') or self.is_full()
    
    def get_score(self):
        # Return the score of the current state
        if self.is_winner('X'):
            return 1
        elif self.is_winner('O'):
            return -1
        else:
            return 0
    

    def minimax(game): if game.is_terminal(): return game.get_score()

    scores = []
    moves = []
    
    for move in game.get_available_moves():
        possible_game = TicTacToe()
        possible_game.board = game.board[:]
        possible_game.active_player = game.active_player
        possible_game.apply_move(move)
        scores.append(minimax(possible_game))
        moves.append(move)
    
    if game.active_player == 'X':
        return max(scores)
    else:
        return min(scores)
    

    def find_best_move(game): scores = [] moves = []

    for move in game.get_available_moves():
        possible_game = TicTacToe()
        possible_game.board = game.board[:]
        possible_game.active_player = game.active_player
        possible_game.apply_move(move)
        scores.append(minimax(possible_game))
        moves.append(move)
    
    if game.active_player == 'X':
        best_move_index = scores.index(max(scores))
    else:
        best_move_index = scores.index(min(scores))
    
    return moves[best_move_index]
    

    Example usage:

    game = TicTacToe() game.print_board() while not game.is_terminal(): if game.active_player == 'X': move = int(input("Enter your move (0-8): ")) else: print("Computer is thinking...") move = find_best_move(game) game.apply_move(move) game.print_board()

    Print result

    if game.is_winner('X'): print("Congratulations! You won!") elif game.is_winner('O'): print("Computer wins!") else: print("It's a draw!")

    '''

    Sample Input and Output

    image image image image image


    output

    Screen Shot 1946-01-27 at 20 31 48 copy Screen Shot 1946-01-27 at 20 36 25

    Result:

    Thus,Implementation of Minimax Search Algorithm for a Simple TIC-TAC-TOE game was done successfully.

19ai405expno6's People

Contributors

meyyappan-t avatar natsaravanan avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.