我已经实现了一个带有AI的井字游戏,但现在我面临一个问题,如何评估井字游戏的棋盘?
也许我应该先描述一下它应该如何工作:
- 我们有n个井字游戏棋盘(有不同的变体)
- 我们的AI应该评估哪个棋盘是最佳选择/对对手最不利
- AI通过极小化极大算法计算移动(已完成)
问题在于第2点。有没有办法“评估”一个棋盘?
我想说的是,我不希望任何人为我编写代码,只是帮助我找到算法或其他方法 🙂
感谢大家的帮助!
编辑 #1
好的,我有极小化极大算法来玩一个棋盘,但如何评估多个棋盘并选择最佳的呢?也许我没有清楚地表达我的需求,所以我会展示一下。
e = 空位
* x | e | e e | o | e * ---+---+--- ---+---+--- * x | e | e e | o | e * ---+---+--- ---+---+--- * o | e | e x | x | e
现在,我的极小化极大算法实现只是告诉我应该在哪里放置我的符号(假设是o),但我需要告诉在哪个棋盘上,所以如何使用它来评估整个棋盘以选择在哪个棋盘上玩?
极小化极大代码:
minimax : function(tempBoard,depth){ if (CheckForWinner(tempBoard) !== 0) return score(tempBoard, depth); depth+=1; var scores = new Array(); var moves = new Array(); var availableMoves = Game.emptyCells(tempBoard); var move, possibleGame, maxScore, maxScoreIndex, minScore,minScoreIndex; for(var i=0; i < availableMoves.length; i++) { move = availableMoves[i]; possibleGame = Game.getNewBoard(move,tempBoard); scores.push(Ai.minimax(possibleGame, depth)); moves.push(move); tempBoard = Game.undoMove(tempBoard, move); } if (Game.turn === "ai") { maxScore = Math.max.apply(Math, scores); maxScoreIndex = scores.indexOf(maxScore); choice = moves[maxScoreIndex]; return scores[maxScoreIndex]; } else { minScore = Math.min.apply(Math, scores); minScoreIndex = scores.indexOf(minScore); choice = moves[minScoreIndex]; return scores[minScoreIndex]; }}
回答:
这里有一个你可以用来评估棋盘的公式:
value = (10 * x3 + 3 * x2 + x1) - (10 * o3 + 3 * o2 + o1)
其中:
- xN => 行/列/对角线上只有
N
个x
且没有o
的数量 - oN => 行/列/对角线上只有
N
个o
且没有x
的数量
这假设max-player
是X
。如果情况相反,你可以更改符号。