As a personal exercise, I'm trying to implement a minimax game with tick-to-tick. I study examples in different languages ββthat I found on the Internet. My implementation is at a point where it seems to work, but then AI loses in certain cases. You can play my version here
If you choose 3 corners and then center, you win. Otherwise, it seems to be working correctly. I can manually run my minmax () function with different game states and it seems that it incorrectly evaluates the first AI move. I am worried that there is something fundamentally wrong with the way I implement the algorithm.
Here is my code:
function State(old) {
if (typeof old !== 'undefined') {
this.board = old.board.slice(0);
} else {
this.board = ['E','E','E','E','E','E','E','E','E'];
}
this.result = 'active';
this.turn = "X";
this.element = "";
this.advanceTurn = function() {
this.turn = this.turn === "X" ? "O" : "X";
}
this.isTerminal = function() {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (this.board[a] !== 'E' && this.board[a] === this.board[b] && this.board[a] === this.board[c]) {
this.result = this.board[a];
return true;
}
}
if (this.moves().length < 1) {
this.result = 'DRAW';
return true;
}
return false;
}
this.moves = function() {
arr = this.board.reduce(function(array,el,index){
if (el === 'E') {
array.push(index);
}
return array;
},[]);
return arr;
}
}
function minmax(state) {
if (state.isTerminal() === true) {
if (state.result === 'X') {
return -10;
} else if (state.result === 'O') {
return 10;
} else {
return 0;
}
}
newStatesSet = state.moves().map(function (el) {
var newState = new State(state);
newState.board[el] = state.turn.slice(0);
newState.advanceTurn();
newState.element = el;
return newState;
});
var newStateScores = [];
newStatesSet.forEach(function(newState) {
var newStateScore = minmax(newState);
newStateScores.push(newStateScore);
});
stateScore = Math.min(...newStateScores);
return stateScore;
}
function aiMove(state) {
var possibleScores = [];
var possibleMoves = [];
var possibleStates = state.moves().map(function(el) {
var newState = new State(state);
possibleMoves.push(el);
newState.board[el] = 'O';
possibleScores.push(minmax(newState));
return newState;
});
if (possibleMoves.length < 1) {
return -1;
}
console.log(possibleStates);
console.log(possibleScores);
function indexOfMax(arr) {
var max = arr.reduce(function(a,b) {
return b > a ? b : a;
});
return arr.indexOf(max);
}
return possibleMoves[indexOfMax(possibleScores)];
}
var game = new State();
game.board = ['E','E','E',
'O','E','E',
'X','E','X']
game.turn = 'O';
console.log(aiMove(game));