我正在尝试为tic-tac-toe应用程序实现negamax搜索功能,但它并没有返回最佳值,相反,它似乎是半随机猜测的。以下是我的代码的相关部分:
public int negamax(Result result, Token token) {
if (result == Result.WIN) {
return 1;
} else if (result == Result.DRAW) {
return 0;
}
int best = -1;
for (Coordinate move : Board.getAvailableMoves()) {
Token other = token.getOther();
Result r = Board.makeMove(move, other);
int eval = -negamax(r, other);
Board.unmakeMove(move);
if (eval > best) {
best = eval;
}
}
return best;
}
public Coordinate getNegamaxMove(Token token) {
int score = -1;
Coordinate bestMove = null;
for (Coordinate move : Board.getAvailableMoves()) {
Result result = Board.makeMove(move, token);
int newScore = negamax(result, token);
Board.unmakeMove(move);
if (newScore >= score) {
score = newScore;
bestMove = move;
}
}
return bestMove;
}重要的是要注意,我不是将棋盘作为参数传递,而是将移动的结果作为参数传递,可以是WIN,be,VALID或either (最后两个与当前讨论无关),这些都是不言而喻的。Coordinate类只保存移动的行值和列值。
非常感谢:)
发布于 2015-05-17 20:29:01
我已经设法让它工作了,负极最大方法有两个问题。首先,应该在循环遍历所有可用移动之前更改令牌,而不是在循环内部。其次,由于我在getNegamaxMove方法中检查最佳走法,在negamax方法中,我必须跟踪最差的走法而不是最好的走法。下面是使用注释掉的旧部分的工作实现,以供比较:
public int negamax(Result result, Token token) {
if (result == Result.WIN) {
return 1;
} else if (result == Result.DRAW) {
return 0;
}
int worst = 1;
// int best = -1
Token other = token.getOther();
for (Coordinate move : Board.getAvailableMoves()) {
// Token other = token.getOther();
Result r = Board.makeMove(move, other);
int eval = -negamax(r, other);
Board.unmakeMove(move);
// if (eval > best) {
// best = eval;
// }
if (eval < worst) {
worst = eval;
}
}
// return best
return worst;
}https://stackoverflow.com/questions/30202563
复制相似问题