# Minimax TicTacToe ai

If you already have a functioning tictactoe game made in javascript and you wanna learn how to make an ai to play with, then this how you will be doing it.

Basically we are making an algorithm which has the goal of selecting the best move possible, it does that by generating all possible moves and giving each move a score, then selects the move with the best score. By using the minimx algorithm we will be able to assume that the opponent will play the their best possible moves, which allows the ai to have the ability to look many moves in the future, we call that depth.

board is the variable that represents the board’s state in form of a double array,

## BestMove Function

BestMove is called when it’s the ai’s turn so after the player plays his move. This function firstly defines a variable called bestScore which is set to a really low number, then with a for loop we check all the possible moves and get each score (We do that by using the minimax funtion), the highest score will be saved in a move variable.

## MiniMax Function

MiniMax is a a recurring function which determines the best move for each player and gives them all their scores. First we check the game state, if it’s a draw, win or loss for the ai and depending on the game state we return a score. If the game is not over we keep checking moves for the best score for each player until the game is over.

```
function bestMove() {
let bestScore = -Infinity;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == " ") {
board[i][j] = ai;
let score = minimax(board, 0, false);
board[i][j] = " ";
if (score > bestScore) {
bestScore = score;
move = {i, j};
}
}
}
}
board[move.i][move.j] = ai;
currentPlayer = human;
}
let scores = {
"X": 10,
"O": -10,
"tie": 0
}
function minimax(board, depth, isMaximizing) {
let result = checkWinner();
if (result != null) {
return scores[result] - depth;
}
if (isMaximizing) {
let bestScore = -Infinity;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == " ") {
board[i][j] = ai;
let score = minimax(board, depth + 1, false);
board[i][j] = " ";
bestScore = Math.max(score, bestScore);
}
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == " ") {
board[i][j] = human;
let score = minimax(board, depth + 1, true);
board[i][j] = " ";
bestScore = Math.min(score, bestScore);
}
}
}
return bestScore;
}
}
```