This is the Javascript code for my Tic-Tac-Toe algorithm:
function minimax(newGrid, depth, Player){
//debugger
const gameState = checkWin(newGrid,true);
if (gameState == false){
values = [];
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
const boardCopy = _.cloneDeep(newGrid);
if (boardCopy[i][j] !== '') continue;
boardCopy[i][j] = Player;
console.log(boardCopy);
const value = minimax(boardCopy, depth + 1, (Player === PLYR_TOKEN) ? COMP_TOKEN : PLYR_TOKEN);
values.push({
cost: value,
cell: {
i: i,
j: j
}
});
}
}
//debugger
if (Player === COMP_TOKEN){
const max = _.maxBy(values, (v) => {
return v.cost;
});
if( depth === 0 ){
return max.cell;
} else {
return max.cost;
}
}else{
const min = _.minBy(values, (v) => {
return v.cost;
});
if( depth === 0 ){
return min.cell;
} else {
return min.cost;
}
}
} else if (gameState === null){
return 0;
} else if (gameState === PLYR_TOKEN){
return depth - 10;
} else if (gameState === COMP_TOKEN){
return 10 - depth;
}
}
The problem with this "algorithm", "code" is simple: it doesn't block my moves Let's image this scenario:
X-> player O-> MM algorithm
X - O
- X -
- - -
Normal, a perfect MiniMax algorithm should take this choice to block me from winning (lower case o is the new move):
X - O
- X -
- - o
The problem is that my code dose this (lower case o is the new move):
X - O
- X o
- - -
Why? I dont know, but I think it take's any chance it has to win, ignoring my moves, ignoring the fact that I'm one move away from winning. To be honest with you, I don't really understand how this algorithm work's.
Other info: The main board is an two dimensional array and the result of the minimax function is an object with two proprieties (i,j) that represent coordinates on the main board.
const board = [
['','',''],
['','',''],
['','','']
];