I found this code of a tic tac toe game in c++, but got confused with the side^1 in GetComputerMove function-->randMove = GetWinningMove(board, side ^ 1); If anything raise to the power of one will only be the value itself, why should it be ^1? Cos it gave me an error when I remove ^1 :D Can anyone help me to explain this? Thanks!
enum { NOUGHTS, CROSSES, BORDER, EMPTY };
enum { HUMANWIN, COMPWIN, DRAW };
const int directions[4] = { 1, 7, 6, 8 };
const int ConvertTo49[25] =
{
8, 9, 10,11,12,
15,16,17,18,19,
22,23,24,25,26,
29,30,31,32,33,
36,37,38,39,40
};
int GetWinningMove(int* board, const int side)
{
int ourMove = -1;
int winFound = 0;
int index = 0;
for (index = 0; index < 25; ++index)
{
if (board[ConvertTo49[index]] == EMPTY)
{
ourMove = ConvertTo49[index];
board[ourMove] = side;
if (FindFourInARow(board, ourMove, side) == 4)
{
winFound = 1;
}
board[ourMove] = EMPTY;
if (winFound == 1)
{
return ourMove;
}
ourMove = -1;
};
}
return ourMove;
}
int GetComputerMove(int* board, const int side)
{
int index;
int numFree = 0;
int availableMoves[25];
int randMove = 0;
//Set random number to randomly run a function
int randFunction = 0;
randFunction = (rand() % 2);
//Go for the winning move
randMove = GetWinningMove(board, side);
if (randMove != -1)
{
return randMove;
}
//If random function is 1, stop any winning move from the human
if (randFunction == 1)
{
randMove = GetWinningMove(board, side ^ 1);
if (randMove != -1)
{
return randMove;
}
}
randMove = 0;
//Loop through all squares and put piece in random place
for (index = 0; index < 25; ++index)
{
if (board[ConvertTo49[index]] == EMPTY)
{
availableMoves[numFree++] = ConvertTo49[index];
};
}
randMove = (rand() % numFree);
return availableMoves[randMove];
}