我想为tictactoe实现MinMax算法。我有两种方法 min()和max()以及评估方法,但它不起作用。例如,当我打电话
max(9);
Field[bestCol][bestRow]='O';
min(8);
Field[bestCol][bestRow]='X';
主函数中的结果是
OX-
---
---
但最好的移动玩家' X'就是把'X'在中间。
这是我的代码,没有评估方法:
static char[][] Field = { { '-', '-', '-' },
{ '-', '-', '-' },
{ '-', '-', '-' } };
static char Player = 'O';
static char Computer = 'X';
static int Depth =9; // searchdepth
static int bestRow=0, bestCol=0; // best Move
public static int max(int depth) {
if (depth == 0) {
return evaluateMove();
}
int maxValue = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (Field[i][j] == '-') {
Field[i][j] = Computer;
int value = min(depth - 1);
Field[i][j] ='-';
if (value > maxValue) {
maxValue = value;
if (depth == Depth) {
bestCol=i;
bestRow=j;
}
}
}
}
}
return maxValue;
}
public static int min(int depth) {
int minValue = Integer.MAX_VALUE;
if (depth == 0) {
return evaluateMove();
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (Field[i][j] == '-') {
Field[i][j] = Player;
int value = max(depth - 1);
Field[i][j] = '-';
if (value < minValue) {
minValue = value;
bestCol=i;
bestRow=j;
}
}
}
}
return minValue;
}
最好的问候
编辑:
感谢您的回答。至于第一点,我忘了改变&#39; *&#39;到&#39; - &#39;这是我的评估方法:
public static int evaluateMove() {
for(int i=0; i<3; i++) {
int countX=0; int countY=0;
for(int j=0; j<3; j++) {
if(Feld[i][j]==Computer) countX++;
if(Feld[i][j]==Player) countY++;
}
if(countX==3) return 10;
if(countY==3) return -10;
}
for(int j=0; j<3; j++) { // Spalten
int countX=0; int countY=0;
for(int i=0; i<3; i++) {
if(Feld[i][j]==Computer) countX++;
if(Feld[i][j]==Player) countY++;
if(countX==3) return 10;
if(countY==3) return -10;
}
}
return 0; // Unentschieden
}
答案 0 :(得分:0)
令我印象深刻的一些事情:
编辑,最后(鼓声......):
也就是说,你实际做了什么:
public static void ComputeAndExecuteBestMove()
{
// since Player begins, we minimize the gain value for the first move
if ((MaxDepth-Depth) % 2 == 0)
{
max(Depth);
Field[bestCol,bestRow] = Player;
}
else
{
min(Depth);
Field[bestCol,bestRow] = Computer;
}
// next move
Depth--;
}
但你应该做什么:
public static void ComputeAndExecuteBestMove()
{
// since Player begins, we minimize the gain value for the first move
if ((MaxDepth-Depth) % 2 == 0)
{
min(Depth);
Field[bestCol,bestRow] = Player;
}
else
{
max(Depth);
Field[bestCol,bestRow] = Computer;
}
// next move
Depth--;
}