DEV Community

loading...
Cover image for Unbeatable Tic Tac Toe in C++

Unbeatable Tic Tac Toe in C++

salroid profile image Sajal Gupta Updated on ・1 min read

What is a min-max algorithm?

Minimax is a decision rule used in artificial intelligence, decision theory, game theory, statistics, and philosophy for minimizing the possible loss for a worst-case scenario.

In this set, there are two players one is going to be the Winner (Maximizer) and the other is going to be the Loser (Minimizer).

In our case, we want to create the computer that is always the winner so it is supposed to make the best move always?

How does the computer decide on the best move?

After the player has made its turn the computer simulates every possible move on the board. The computer assumes that the player will always make the worst move and reach the end case.

If (Computer Wins) {
   return 10; // Winning moves gives 10
} else {
   return 0; // Losing moves gives 0
}
Enter fullscreen mode Exit fullscreen mode

Every time we get 10 that's the move computer is going to make in order to win.

There can be multiple 10 values then what to choose?

Let's say we have a value called "DEPTH" - which tells you how fast the computer is going to win.

Suppose 2 moves, Depth = 2;

If (Computer Wins) {
   return 10 - Depth(2); //  Distinct values
} else {
   return 0; // Losing moves gives 0
}
Enter fullscreen mode Exit fullscreen mode

Now the values will become distinct and the computer will always make the move where it gets the highest value after subtracting the depth.

Watch my youtube video on Biased Dice UI.

Unbeatable Tic Tac Toe code available at

GitHub logo salRoid / UnbeatableTicTacToe

❌⭕ An unbeatable Tic Tac Toe game with reliable artificial intelligence.

UnbeatableTicTacToe

An unbeatable Tic Tac Toe game with reliable artificial intelligence.

Discussion (0)

pic
Editor guide