I have a function to check the valid moves in my reversi game. I look at the unoccupied spaces, and check if an adjacent space in any 8 directions are the opposite piece. (If I'm black, I search for white) Now, if I find a piece that's adjacent, I should keep looking towards that direction and see if my own piece is at the end, then I return true, else if its an unoccupied space or off the board boundaries, I return false.
My function doesn't seem to work properly as I print out the wrong moves.
bool checkLegalInDirection(char boardgame[26][26], int size, int row, int col, char color) {
int currentRow, currentCol;
for (int deltaRow = -1; deltaRow < 2; deltaRow++) {
for (int deltaCol = -1; deltaCol < 2; deltaCol++) {
if (deltaRow == 0 && deltaCol == 0) {
break;
} else {
row = row + deltaRow;
col = col + deltaCol;
if (positionInBounds(size, row, col)) {
while (boardgame[row][col] == OppositeColor(color)) {
currentRow = row + deltaRow;
currentCol = col + deltaCol;
if (positionInBounds(size, currentRow, currentCol)) {
if (boardgame[currentRow][currentCol] == color) {
return true;
} else {
return false;
}
}
}
}
}
}
}
}
deltaRow and deltaCol are the increments that go in each direction and add one time to keep searching in a specified location. PositioninBounds is a function I have to make sure my searches are within the board boundaries. My deltarow and deltacol cannot be both 0 at the same time, so somehow I need to skip that step, (which I probably did wrong). Oppositecolor is a function that returns me the opposite color of my own piece.
I think your code has multiple mistakes.
Your code is incorrectly breaking the for loop when you should be continuing with the next iteration (as mentioned by chux).
Change...
to either chux's suggestion...
or to an even simpler solution...
Inside the deltaRow/deltaCol loops, your code is incorrectly modifying the original row/col values which your code will need in later loop iterations.
You can change...
to...
Inside the while loop, your code is incorrectly returning false. You can not return false until you have completed all the for loops.
Before entering the while loop, you need to check that the adjacent space is in bounds and opposite color...
If so, then skip over all adjacent opposite colors...
After you have skipped over opposite colors then you need to check for same color. If so then return true.
You code should only return false after checking all directions...