Original Post
Hi, as you can see I've posted a couple of questions recently trying to get down the basics of the minimax algorithm. I decided to go with negamax and I THOUGHT I had it figured out and working...but I'm running into a couple problems using it with my connect 4 game. I was just hoping someone could maybe look at my code and let me know if anything seems wrong. I haven't yet implemented a function to 'evaluate' the strength of each move...I'm just trying to get the program to see moves that will result in a win. What I have works, if it is my turn and there is 3 in a row and a winning move, it will tell me that. However, if it is my turn and the oppenent has a winning move that I can block it doesn't tell me that. By examining the algorithm, it seems like it should tell me that. The recursion should stop when it finds the winning move and send that down. So the way I see it, for the oppenents move, there should be 6 moves that will result in his winning and return a winning value, but there should be the one move that won't because that move will have blocked his winning move. So it will send back 6 9999 values, which become negative...and the other value will be smaller than that, which becomes bigger when it is sent back negative...so it seems like it SHOULD detect that and recommend that move. However it isn't, which leads me to believe that I have messed up somewhere or that I have an error. I just can't seem to figure it out. Anyways, heres my code...if anyone takes a look I would be more than grateful.
int negaMax(int board[][BOARD_HEIGHT], int depth, int player) {
MOVE moveList[7] = {0};
int bestValue = -WIN;
int value, numMoves;
// used to keep track of which player's turn it is
switch(player) {
case 1: player = 2; break;
case 2: player = 1; break;
default: break;
}
// check for win
if(scanBoard(board))
return WIN;
// if reached searched depth, evaluate board
if(depth <= 0){
return evaluate(board);
}
numMoves = possibleMoves(board, moveList, player);
if(numMoves == 0)
return 0;
for(int i = 0; i < numMoves; i++) {
doMove(board, moveList);
value = -negaMax(board, depth-1, player);
undoMove(board, moveList);
if(value > bestValue)
bestValue = value;
}
return bestValue;
}
int getMove(int board[][BOARD_HEIGHT], int player) {
MOVE moveList[7] = {0};
int numMoves, returnValue, maxValue = -9999, returnMove = 0;
// put a list of possible moves into moveList array
numMoves = possibleMoves(board, moveList, player);
// for each of the possible moves, run negamax and get 'score' for each
for(int i = 0; i < numMoves; i++) {
doMove(board, moveList);
returnValue = negaMax(board, 5, player);
cout << returnValue << endl;
undoMove(board, moveList);
if(returnValue > maxValue){
maxValue = returnValue;
returnMove = moveList.x;
}
}
return returnMove+1;
}