我有一些JavaScript代碼,而試圖編碼一個井字遊戲遊戲。
所以AI(人工智能)播放「X」,分別爲「人」播放器爲「O」;
對於測試我把板作爲
[ 'E', 'E', '0',
'X', 'O', 'E',
'E', 'e' 的,'e']
這是AI轉動。所以很明顯的AI(人工智能)的最佳舉措是
[ 'E', 'E', 'O',
'X', 'O', 'E',
'X', 'e','e']。
但它返回我
[ 'X', 'E', 'O',
'X', 'O', 'E',
'E', 'E',' e'] 變體。
我將不勝感激,爲好的提示,這將重新導向我以正確的方式。
是的,我讀了一個星期關於Minimax的文章一堆。我個人用作本教程的原型http://blog.circuitsofimagination.com/2014/06/29/MiniMax-and-Tic-Tac-Toe.html。
所以,請看看我的代碼:Minimax算法JS實現
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);
好了,這絕對代碼...你有問題嗎?代碼是否工作,但不符合你的要求?代碼不起作用嗎?控制檯中是否有錯誤? –