java - TicTacToe 极小极大算法与 Java
问题描述
我正在用 Java 实现极小极大算法。我遵循了 Codding Trains 教程。问题是人工智能总是选择下一个可用的位置,而不是最好的。
game.put() 将玩家(或空白点)id 放在给定点上。
board 是游戏类的变量,它是二维字节数组。
如果游戏仍在进行,game.checkForWin() 返回 0,如果没有人获胜并且没有可能的移动(平局),则返回 -1,如果 AI 获胜,则返回 1,如果玩家获胜,则返回 2。
public Point bestMove(){
int bestScore = Integer.MIN_VALUE;
Point move = null;
for (int i=0; i<board.length; i++){
for(int j=0; j<board[i].length; j++){
if (board[i][j] == blank){
game.put(ai_id, new Point(i,j));
int score = minimax(false);
game.put(blank, new Point(i,j));
if(score > bestScore){
bestScore = score;
move = new Point(i, j);
}
}
}
}
return move;
}
public int minimax(boolean ai_turn){
int state = game.checkForWin();
if (state!=0){ // If game ended
if(state == -1){
return 0; //TIE
}
if( state == ai_id){
return 1; //AI wins
}
return -1; //Player wins
}
int bestScore = 0;
if(ai_turn){
bestScore = Integer.MIN_VALUE;
for (int i=0; i<board.length; i++){
for(int j=0; j<board[i].length; j++){
if (board[i][j] == blank){
game.put(ai_id, new Point(i,j));
int score = minimax(false);
game.put(blank, new Point(i,j));
bestScore = Math.max(score, bestScore);
}
}
}
}else{
bestScore = Integer.MAX_VALUE;
for (int i=0; i<board.length; i++){
for(int j=0; j<board[i].length; j++){
if (board[i][j] == blank){
game.put(player_id, new Point(i,j));
int score = minimax(true);
game.put(blank, new Point(i,j));
bestScore = Math.min(score, bestScore);
}
}
}
}
return bestScore;
}
编辑:我重写了整个游戏代码,这个函数算法按预期工作。
解决方案
2
如果玩家赢了,您不检查该值。立即检查有-1
什么问题。
推荐阅读
- java - 来自新 CSVReaderHeaderAware 的 FileNotFoundException
- java - 使用 jgoodies-looks WindowsLookAndFeel 时 JMenu 看起来很奇怪
- java - HttpUrlConnection 忽略输入的值
- javascript - 在 window.onload 之外定义时,Javascript“clearInterval”方法无法停止计时器
- javascript - 致命错误:接近堆限制的无效标记压缩分配失败 - 使用 fs 处理大文件时 JavaScript 堆内存不足
- r - 强制对 R 包进行串行编译
- node.js - 超级账本结构调用注册端点失败并出现错误
- c# - Admob 插页式 Unity 3D 问题
- javascript - 为什么我必须使用 window.onload 将图像绘制到画布上
- sql - 根据存储过程参数更改 SQL Server 查询