我一直在尝试为“进化的”井字游戏(9x9)编写miniMax算法。然而,似乎每当我调用这个算法时它就会在迷你部分崩溃。 getAvailableMoves函数为每个移动分配一个“得分”。如果它给第一名球员带来优势,那么得分会更高。如果我做第一步似乎有点工作,但是,如果我是迷你(第二个做出移动)它只是获得第一个可用的移动,总是。我一直想弄清楚我做错了什么,但我无法发现问题。有人有任何想法吗?
public Move mini( Field field, int depth, int player )
{
if( depth == 0 || field.isFull() )
{
ArrayList<Move> moves = field.getAvailableMoves(-player);
if( moves.isEmpty() ) return null;
int miniProfit = moves.get(0).getBenefit(), index = 0;
for( int i = 1 ; i < moves.size() ; i++ )
{
if( miniProfit < moves.get(i).getBenefit() )
{
miniProfit = moves.get(i).getBenefit();
index = i;
}
}
moves.get(index).benefit = - moves.get(index).benefit;
return moves.get(index);
}
ArrayList<Move> moves = field.getAvailableMoves(player);
Move miniMove = new Move();
miniMove.benefit = Move.Inf;
for( Move move : moves )
{
field.applyMove(move, player);
Move move2 = maxi( field, depth - 1, -player );
if( move2 == null ) continue;
int mini = move2.getBenefit();
if( mini <= miniMove.benefit )
{
miniMove = move;
}
field.unapplyMove(move, player);
}
return miniMove;
}
public Move maxi( Field field, int depth, int player )
{
if( depth == 0 || field.isFull() )
{
ArrayList<Move> moves = field.getAvailableMoves(player);
if( moves.isEmpty() ) return null;
int maxiProfit = moves.get(0).getBenefit(), index = 0;
for( int i = 1 ; i < moves.size() ; i++ )
{
if( maxiProfit < moves.get(i).getBenefit() )
{
maxiProfit = moves.get(i).getBenefit();
index = i;
}
}
return moves.get(index);
}
ArrayList<Move> moves = field.getAvailableMoves(player);
Move maxiMove = new Move();
maxiMove.benefit = 0 - Move.Inf;
for( Move move : moves )
{
field.applyMove(move, player);
Move move2 = mini( field, depth - 1 , -player );
if( move2 == null ) continue;
int maxi = move2.getBenefit();
if( maxi >= maxiMove.benefit )
{
maxiMove = move;
}
field.unapplyMove(move, player);
}
return maxiMove;
}
public Move makeTurn(Field field) {
int depth = 5;
if( myId == 1 )
{
return maxi(field, depth, 1);
}
else
{
return mini(field, depth, -1);
}
}