I have some javascript code while trying to code a Tic tac toe game.
So the AI (Artificial Intelligence) plays "X" and respectively "Human" player is "O";
For test I put a board as
['e', 'e', 'o',
'x', 'o', 'e',
'e', 'e', 'e']
It is AI turn to move. So obviously the best move for AI (Artificial Intelligence) is
['e', 'e', 'o',
'x', 'o', 'e',
'x', 'e', 'e'].
But it returns me
['x', 'e', 'o',
'x', 'o', 'e',
'e', 'e', 'e']
variant.
I would be appreciated, for good hints, that would redirect me in the right way.
And yes I've read for a week a bunch of articles about Minimax. Personally I used as a prototype this tutorial http://blog.circuitsofimagination.com/2014/06/29/MiniMax-and-Tic-Tac-Toe.html.
So please have a look at my code:
var board = ['e', 'e', 'o', 'x', 'o', 'e', 'e', 'e', 'e'];
var signPlayer = 'o';
var signAI = (signPlayer === 'x') ? 'o' : 'x';
//Circuits Of Imagination
game = {
over: function(board) {
for (var i = 0; i < board.length; i += 3) {
if (board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {
return board[i] !== 'e' ? board[i] : false;
}
}
for (var j = 0; j < board.length; j++) {
if (board[j] === board[j + 3] && board[j + 3] === board[j + 6]) {
return board[j] !== 'e' ? board[j] : false;
}
}
if ((board[4] === board[0] && board[4] === board[8]) ||
(board[4] === board[2] && board[4] === board[6])) {
return board[4] !== 'e' ? board[4] : false;
}
var element;
if (board.every(function(element) {
return element !== 'e';
})) {
return true;
}
},
winner: function(board) {
return game.over(board);
},
possible_moves: function(board, sign) {
var testBoard = [],
nextBoard;
for (var i = 0; i < board.length; i++) {
nextBoard = board.slice();
if (nextBoard[i] === 'e') {
nextBoard[i] = sign;
testBoard.push(nextBoard);
}
}
return testBoard;
}
}
function score(board) {
if (game.winner(board) === signPlayer) {
return -10;
} else if (game.winner(board) === signAI) {
return +10;
} else {
return 0;
//Game is a draw
}
}
function max(board) {
if (game.over(board)) {
return score(board);
}
var newGame = [];
var best_score = -10;
var movesArray = game.possible_moves(board, signAI);
for (var i = 0; i < movesArray.length; i++) {
newGame = movesArray[i].slice();
score = min(newGame);
if (score > best_score) {
best_score = score;
}
console.log('maxnewGame', newGame);
return best_score;
}
}
function min(board) {
if (game.over(board)) {
return score(board);
}
var newGame = [];
var worst_score = 10;
var movesArray = game.possible_moves(board, signPlayer);
for (var i = 0; i < movesArray.length; i++) {
newGame = movesArray[i].slice();
score = max(newGame);
if (score < worst_score) {
worst_score = score;
}
console.log('minnewGame', newGame);
return worst_score;
}
}
max(board);