Friday, March 21, 2014

AI-- Minimax Algorithm


class ComputerPlayer
{
public:
static int min(Board *b,int alpha, int beta){
if(b->full_board())
return b->Evaluation();
int value= 10;
for(int i =1; i<=3; i++)
for(int j=1; j<=3; j++)
{
if(b->get_square(i,j)==0)
{
Board next = *b;
next.play_square(i,j,HUMANPLAYER);
value = MIN(value, max(&next, alpha,beta));
if(value <= alpha)
return value;
beta = MIN(value,beta);
}
}
return value;

}

static int max(Board *b, int alpha, int beta){
if(b->full_board())
return b->Evaluation();
int value = -10;
for(int i =1;i<=3;i++)
for(int j=1;j<=3;j++)
{
if(b->get_square(i,j)==0)
{
Board next = *b;
next.play_square(i,j,CPUPLAYER);  // =CPU;
value = MAX(value, min(&next,alpha,beta));
if(value>= beta)
return value;
alpha = MAX(alpha,value);
}
}
return value;

}

static pos miniMax(Board *b){
int value= -10;
pos next_ply;
for(int i =1;i<=3;i++)
for(int j=1;j<=3;j++)
{
if(b->get_square(i,j)==0)
{
Board next;
next= *b;
next.play_square(i,j,CPUPLAYER);
int tmp = min(&next,-10,10);
if( tmp > value)
{
value = tmp;
next_ply.x = i;
next_ply.y = j;
}
}
}
return next_ply;

}
};

No comments:

Post a Comment