I'm coding a tic tac toe game in 2d, everything has been going good so far, but the computer puts two pieces every time. I can't understand why the computer do this, but it's really hard to find any errors. Things have a tendancy to mess up at the very end when the game is almost finished, the computer is mean ://
I suspect it is any of these functions:
[SOURCE]
int Board::computerMove() {
if (turn == computer) {
for (int i=0;i<PIECES;i++) {
if (isLegal(i)) {
boardRows = computer;
if (winner() == computer) {
change_turn();
return 0;
}
boardRows = ' ';
}
}
for (int i=0;i<PIECES;i++) {
if (isLegal(i)) {
boardRows = player;
if (winner() == player) {
boardRows = computer;
change_turn();
return 0;
}
boardRows = ' ';
}
}
const int bestMoves[] = {4,0,2,6,8,1,3,5,7};
for (int i=0;i<PIECES;i++) {
int move = bestMoves;
if (isLegal(move)) {
boardRows[move] = computer;
change_turn();
return 0;
}
}
}
return 0;
}
[/SOURCE]
Or this function that checks who is the winner if there is any. I am using this function for the game loop.
[SOURCE]
char Board::winner() {
const int winningRows[8][3] = {0,1,2,
3,4,5,
6,7,8,
0,3,6,
1,4,7,
2,5,8,
0,4,8,
2,4,6};
for (int row=0;row<8;row++) {
if ((boardRows[winningRows[row][0]] != ' ') && (boardRows[winningRows[row][0]] == boardRows[winningRows[row][1]]) && (boardRows[winningRows[row][1]] == boardRows[winningRows[row][2]])) {
SDL_FillRect(screen, &pieces[boardRows[winningRows[row][0]]], SDL_MapRGB(screen->format, 0x55, 0x55, 0x55));
SDL_FillRect(screen, &pieces[boardRows[winningRows[row][1]]], SDL_MapRGB(screen->format, 0x55, 0x55, 0x55));
SDL_FillRect(screen, &pieces[boardRows[winningRows[row][2]]], SDL_MapRGB(screen->format, 0x55, 0x55, 0x55));
return boardRows[winningRows[row][0]];
}
}
int counter=0;
for (int i=0;i<PIECES;i++) {
if (boardRows != ' ') {
counter++;
}
if (counter==8)
return ('T');
}
return ('0');
}
[/SOURCE]
What have I tried to fix this error? Well, the only thing that is worth mentioning, is that I tried to remove the two first for loops in the computermove function, that didn't work.
The player variable is a char and have the value 'X'.
The computer variable is a char with the value 'O'.
I Appreciate any help or tips, can post rest of the source if necessary.