Tic-Tac-Toe的javaminmax算法
我正试着做的tic-tac-toe(总是电脑赢)的最小最大值,但我无法让它工作。 所有的后继者只返回0(平局)作为分数,因此计算机总是选择沿着矩阵的自然方向移动
注:矩阵(类)是他们玩的棋盘,包含9个位置的数组
| X | O | X | O | ... | like this.
处理Tic Tac趾板的全局变量称为Main,是矩阵的一个实例
public void minMax(Matrix p) {
Matrix bestvalue = maxValue(p);
print(bestvalue);
System.out.println(bestvalue.getScore());
main = searchSucessorWithScore(p, bestvalue.getScore());
}
public Matrix maxValue(Matrix p) {
if(endState(p)) { p.setScore(utility(p)); return p; } //always sets score to 0 but the method utility is correct...
Matrix bestmove = new Matrix();
bestmove.setScore(Integer.MIN_VALUE);
LinkedList<Matrix> list = addSucessors(p, plays.PLAY_X);
for(Matrix s : list) {
Matrix move = minValue(s);
if(move.getScore() > bestmove.getScore()) {
bestmove = move;
}
}
return bestmove;
}
public Matrix minValue(Matrix p) {
if(endState(p)) { p.setScore(utility(p)); return p;}
Matrix bestmove = new Matrix();
bestmove.setScore(Integer.MAX_VALUE);
LinkedList<Matrix> list = addSucessors(p, plays.PLAY_O);
for(Matrix s : list) {
Matrix move = maxValue(s);
if(move.getScore() < bestmove.getScore()) { // <
bestmove = move;
}
}
return bestmove;
}
Auxiliar methods:
public LinkedList<Matrix> addSucessors(Matrix k, plays l) {
LinkedList<Matrix> list = new LinkedList<Matrix>();
for(int i=0; i<9; i++) {
if(k.getRow(i).equals(plays.BLANK)) {
Matrix p = k.clone();
p.setRow(i, l);
list.add(p);
}
}
return list;
}
/* RETURNS 0 FOR DRAW, 1 FOR PC WIN, -1 FOR USER WIN */
public int utility(Matrix p) {
for(int i=0; i<9; i=i+3) {
if(main.getRow(i).equals(plays.PLAY_X) && main.getRow(i+1).equals(plays.PLAY_X) && main.getRow(i+2).equals(plays.PLAY_X)) return 1;
if(main.getRow(i).equals(plays.PLAY_O) && main.getRow(i+1).equals(plays.PLAY_O) && main.getRow(i+2).equals(plays.PLAY_O)) return -1;
}
for(int i=0; i<3; i++) {
if(main.getRow(i).equals(plays.PLAY_X) && main.getRow(i+3).equals(plays.PLAY_X) && main.getRow(i+6).equals(plays.PLAY_X)) return 1;
if(main.getRow(i).equals(plays.PLAY_O) && main.getRow(i+3).equals(plays.PLAY_O) && main.getRow(i+6).equals(plays.PLAY_O)) return -1;
}
if(main.getRow(0).equals(plays.PLAY_X) && main.getRow(4).equals(plays.PLAY_X) && main.getRow(8).equals(plays.PLAY_X)) return 1;
if(main.getRow(2).equals(plays.PLAY_X) && main.getRow(4).equals(plays.PLAY_X) && main.getRow(6).equals(plays.PLAY_X)) return 1;
if(main.getRow(0).equals(plays.PLAY_O) && main.getRow(4).equals(plays.PLAY_O) && main.getRow(8).equals(plays.PLAY_O)) return -1;
if(main.getRow(2).equals(plays.PLAY_O) && main.getRow(4).equals(plays.PLAY_O) && main.getRow(6).equals(plays.PLAY_O)) return -1;
return 0;
}
public Matrix searchSucessorWithScore(Matrix p, Integer v) {
for(Matrix s : addSucessors(p, plays.PLAY_X) {
if(s.getScore() == v) return s;
}
return null;
}
method实用程序是正确的,但内部递归仅返回0,即使对于有赢家的矩阵也是如此
帮助:D
# 1 楼答案
没有发布足够的代码来正确评估,但这几乎不起作用
Integer v s.getScore() == v
你应该使用
Integer.intValue()