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?
The minimax algorithm is a decision-making algorithm that is basically used in two-player games like chess or tic-tac-toe.
Not just that:
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.
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.
let board = Array(9).fill(null);
Creates the 3×3 board as an array of 9 cells.
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]
];
drawBoard()
startGame(mode)
Player Move
playerMove(i)
bestMove()
This is the most important part of the code. The AI move.
minimax(newBoard, depth, isMaximizing)
if (winner === ai) return 10 - depth;
if (winner === human) return depth - 10;
if (newBoard.every(cell => cell)) return 0;
best = Math.max(best, minimax(...));
best = Math.min(best, minimax(...));

You can try the demo yourself here.
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?