Articles / AI · Part 26

Minimax Algorithm in Artificial Intelligence

Learn how the Minimax Algorithm helps AI make strategic decisions in competitive games. Explore game trees, MAX and MIN players, utility functions, Python implementation, complexity, and its limitations.

Minimax Algorithm in Artificial Intelligence

Imagine playing a game of Tic-Tac-Toe against a computer.

You place your X on the board. The computer now has several possible moves. It could choose any empty square, but a good computer player should do more than select a random position.

It should consider what might happen after each move. If it chooses one position, what will you do next? Could you win? Could you force a draw? Is there a move that prevents you from winning?

This is the central idea behind the Minimax Algorithm.

Instead of looking only at its immediate move, the algorithm explores possible future moves and considers how an opponent might respond.

It is one of the fundamental decision-making algorithms used in two-player competitive games.

1. What Is the Minimax Algorithm?

The Minimax Algorithm is a decision-making algorithm used in Artificial Intelligence to select the best move in a competitive game.

It works by exploring possible future game states and assuming that both players make the best decisions available to them.

The two players are commonly represented as:

  • MAX: The player trying to maximise the score.
  • MIN: The opponent trying to minimise MAX’s score.

MAX wants the highest possible outcome, while MIN tries to prevent MAX from achieving it.

The algorithm examines possible moves, evaluates their outcomes, and chooses the move that provides the best result against an intelligent opponent.

Minimax is commonly used in two-player, turn-based, zero-sum games with perfect information, such as Tic-Tac-Toe, Chess, and Checkers.

2. Understanding the Basic Idea

Suppose MAX has two possible moves: A and B.

After MAX selects a move, MIN gets an opportunity to respond.

Consider this game tree:

                  MAX
                 /   \
                A     B
               / \   / \
              3   5 2   9

The numbers at the bottom represent the possible outcomes from MAX’s perspective.

Let’s examine the choices.

If MAX chooses A:

MIN can choose between 3 and 5. Since MIN wants to minimise MAX’s score, it selects 3.

\[
\min(3,5)=3
\]

If MAX chooses B:

MIN can choose between 2 and 9. It selects 2.

\[
\min(2,9)=2
\]

Now MAX compares the outcomes of its two choices:

\[
\max(3,2)=3
\]

Therefore, MAX chooses A because it guarantees an outcome of 3, assuming MIN plays optimally.

This is the basic working principle of Minimax.

3. How Does Minimax Work?

The algorithm explores the game tree from the current position towards the possible future outcomes.

It then evaluates the tree from the bottom upwards.

The process follows these steps:

  1. Start with the current game state.
  2. Generate all legal moves available to the current player.
  3. Explore the resulting states.
  4. Continue until reaching terminal states or a chosen search depth.
  5. Assign a score to each evaluated position.
  6. Propagate scores upwards through the tree.
  7. At MAX levels, select the highest value.
  8. At MIN levels, select the lowest value.
  9. Choose the move with the best resulting value.

The algorithm works backwards from the outcomes to determine which move should be selected at the beginning.

4. Understanding the Minimax Function

The decision rule can be expressed mathematically.

For a MAX player:

\[
V(s)=\max_{a\in A(s)}V(Result(s,a))
\]

For a MIN player:

\[
V(s)=\min_{a\in A(s)}V(Result(s,a))
\]

Here:

  • \(V(s)\) represents the value of a game state.
  • \(A(s)\) represents the legal actions available in state \(s\).
  • \(Result(s,a)\) represents the new state after taking action \(a\).

The algorithm uses the maximum value at MAX levels and the minimum value at MIN levels.

For a terminal state, the value comes from the game’s utility function.

For example, a simple Tic-Tac-Toe evaluation from MAX’s perspective could be:

Result Score
MAX wins +1
Draw 0
MIN wins -1

The algorithm tries to select a move that maximises the final score.

5. Python Implementation

Let’s implement a simple Minimax Algorithm using the game tree from our earlier example.

We will represent the tree using nested lists.

def minimax(node, is_maximizing):

    # A number represents a terminal value
    if isinstance(node, int):
        return node

    if is_maximizing:
        best_value = float("-inf")

        for child in node:
            value = minimax(child, False)
            best_value = max(best_value, value)

        return best_value

    else:
        best_value = float("inf")

        for child in node:
            value = minimax(child, True)
            best_value = min(best_value, value)

        return best_value


game_tree = [
    [3, 5],   # Move A
    [2, 9]    # Move B
]

best_value = minimax(game_tree, True)

print("Best possible value:", best_value)

Output:

Best possible value: 3

The algorithm explores the possible outcomes and returns 3 as the best value MAX can guarantee.

To identify the actual move, we can evaluate each available option:

for index, move in enumerate(game_tree):
    value = minimax(move, False)
    print(f"Move {index + 1}: {value}")

Output:

Move 1: 3
Move 2: 2

MAX should select Move 1 because it provides the higher guaranteed outcome.

This implementation demonstrates the Minimax decision process using a small game tree. A complete game-playing program also needs to generate legal moves and represent the changing game state.

6. Minimax in Tic-Tac-Toe

Tic-Tac-Toe is one of the easiest ways to understand Minimax in a practical game.

The board contains nine squares. Two players take turns placing X and O until one player wins or the board becomes full.

A Minimax-based AI can examine the possible future moves and choose the best one.

Suppose the computer plays as X and the human plays as O.

The AI considers:

  • Whether it can win immediately.
  • Whether the opponent can win on the next move.
  • Which moves lead to a draw.
  • Which moves allow the opponent to win.

It evaluates the possible outcomes and chooses the move with the highest Minimax value.

With a suitable implementation that searches the complete game tree, the AI can play Tic-Tac-Toe optimally. It will never lose against another optimal player.

7. Important Concepts in Minimax

A. Game Tree

A game tree represents the possible moves and future states of a game.

The algorithm uses it to explore the consequences of different decisions.

B. Utility Function

A utility function assigns numerical values to completed game outcomes.

These values help the algorithm compare possible results.

C. Evaluation Function

In complex games, searching until the end may not be practical.

An evaluation function estimates the quality of a non-terminal position.

For example, a chess evaluation function may consider material advantage, king safety, and control of the board.

D. Optimal Opponent

Minimax assumes that the opponent will also make the best possible decisions.

This is important because the algorithm does not simply choose a move that looks good immediately. It chooses a move based on the opponent’s strongest response.

8. Advantages of the Minimax Algorithm

Strategic Decision-Making: It considers future moves instead of choosing actions randomly.

Optimal Decisions in Suitable Games: With a complete search and accurate utility values, it finds an optimal move in finite, deterministic, two-player, zero-sum games with perfect information.

Systematic Approach: It provides a clear method for evaluating competing moves.

Useful for Game AI: It forms the foundation of many traditional game-playing systems.

9. Limitations of Minimax

Despite its effectiveness, Minimax has some important limitations.

A. Large Game Trees

The number of possible game states can grow extremely quickly.

For example, chess has a huge number of possible move sequences. Exploring every possible continuation is generally impractical.

B. High Time Complexity

If each position has an average of \(b\) possible moves and the algorithm searches to depth (d), its time complexity is:

\[
O(b^d)
\]

This means the amount of work can increase exponentially as the search depth grows.

C. Memory Requirements

A depth-first recursive implementation typically uses:

\[
O(bd)
\]

space for the search stack and generated moves, assuming successors are generated as needed.

Storing the entire game tree would require substantially more memory.

D. Dependence on Evaluation Functions

When the algorithm cannot search to the end of a game, it needs an evaluation function to estimate the quality of positions.

A poor evaluation function can lead to poor decisions.

E. Assumption of Optimal Opponents

Minimax assumes that the opponent will always choose the move that is worst for MAX.

Real opponents may make mistakes or use unpredictable strategies, which the basic algorithm does not explicitly model.

10. How Can Minimax Be Improved?

One major improvement is Alpha-Beta Pruning.

Minimax may explore many branches that cannot change the final decision. Alpha-Beta Pruning avoids exploring some of these unnecessary branches.

It uses two values:

  • Alpha (α): The best value MAX can guarantee so far.
  • Beta (β): The best value MIN can guarantee so far.

When the algorithm determines that a branch cannot influence the final decision, it stops exploring that branch.

This can significantly reduce the number of positions examined while preserving the Minimax result.

We will explore Alpha-Beta Pruning in the next article.

11. Minimax vs Hill Climbing

Both algorithms help AI systems make decisions, but they solve different kinds of problems.

Minimax Hill Climbing
Designed for competitive decision-making Designed for optimisation
Considers an opponent’s responses Examines neighbouring solutions
Uses MAX and MIN levels Moves towards a better evaluation value
Explores a game tree Usually improves a current state
Commonly used in board games Commonly used in optimisation problems

Minimax is particularly useful when decisions depend on an opponent’s actions. Hill Climbing is generally used when the objective is to improve a solution through local changes.

Conclusion

The Minimax Algorithm teaches an important lesson about intelligent decision-making: a good move is not necessarily the one that looks best immediately. It is the one that remains favourable after considering how the opponent might respond.

By exploring possible game states and assuming that both players make optimal decisions, Minimax provides a systematic way to choose moves.

However, large game trees make complete searches impractical in complex games. This is why improvements such as Alpha-Beta Pruning are important.

In the next article, we will learn how Alpha-Beta Pruning makes Minimax more efficient by avoiding unnecessary exploration.

Quick quiz

5 questions
What is the main purpose of the Minimax Algorithm?
What does MAX try to do?
What does MIN try to do?
What does a utility function provide?
Which technique improves Minimax by skipping unnecessary branches?

Keep a copy

Read offline as a printout or PDF.

farhanpaal.com

Keep reading

AI · Part 25

Game Playing in Artificial Intelligence

Explore how Artificial Intelligence plays competitive games using search, game trees, evaluation functions, and adversarial reasoning. Learn about game types, important algorithms,…

9 min read

Ask Farhan

Ask anything about Farhan