Building an Unbeatable Tic-Tac-Toe AI with the Minimax Algorithm
I wanted to build something using AI. And it uses AI. I was thinking, what is the best thing to make 2026-7-13 20:44:16 Author: hackernoon.com(查看原文) 阅读量:14 收藏

I wanted to build something using AI. And it uses AI. I was thinking, what is the best thing to make? And it came to my mind: a game that everyone knows and plays and is easy to play. Tic-tac-toe.

But training an AI to play tic-tac-toe will take time. So it hit me: why not use minimax?

What is minimax?

The minimax algorithm is a decision-making algorithm that is basically used in two-player games like chess or tic-tac-toe.

  • The AI lists every legal move it can make.
  • For each move, it imagines the opponent's best possible response.

Not just that:

  • It assumes the opponent always makes the best move.
  • It evaluates every possible continuation before choosing.

But why choose tic-tac-toe?

Tic-tac-toe is small enough that it can be searched completely, while other games like chess need more because they have many more possibilities.

But the idea is not to make an AI that plays tic-tac-toe but an AI that doesn't lose in tic-tac-toe.

Here's how it works:

  • You can choose to make the first move.
  • Or you can choose AI to make the first move, and you play.

I made it so you can choose or the other person can make it even harder. This system usually chooses the best first move, but it will get boring very quickly, so I made the game so that the AI will start randomly each time.

Then you can try and beat the AI.

Now for the code.

Board Representation

let board = Array(9).fill(null);

Creates the 3×3 board as an array of 9 cells.

Winning Combinations

const winCombos = [

[0,1,2],[3,4,5],[6,7,8],

[0,3,6],[1,4,7],[2,5,8],

[0,4,8],[2,4,6]

];

Drawing the Board

drawBoard()

Starting the Game

startGame(mode)

Player Move

playerMove(i)

AI Move (Most Important)

bestMove()

This is the most important part of the code. The AI move.

Minimax Algorithm (The Heart of the AI)

minimax(newBoard, depth, isMaximizing)

Scoring

if (winner === ai) return 10 - depth;

if (winner === human) return depth - 10;

if (newBoard.every(cell => cell)) return 0;

Maximizing

best = Math.max(best, minimax(...));

Minimizing

best = Math.min(best, minimax(...));

Joe bou khalil 's image-9b5ce8

You can try the demo yourself here.

What are the benefits of this game?

  • Explain minimaxing. What is it? And its uses?
  • See the limits of AI.
  • And for people that don't care about coding as a fun game against a strong opponent.

Conclusion

The possibilities of AI in today's world are limitless; you can use AI for mostly anything, even to build an unbeatable game of tic-tac-toe. And not just that, it's becoming stronger and stronger every day. So what do you think I should build next?


文章来源: https://hackernoon.com/building-an-unbeatable-tic-tac-toe-ai-with-the-minimax-algorithm?source=rss
如有侵权请联系:admin#unsafe.sh