this array has 9 elements and I am looking for combinations of three there are sixteen possible combinations I need to find if and when they occur so a switch would be better but I need to know how to start this switch and if there is an even easier way
its tic-tac-toe and Im splitting it up into several functions the one I am asking about checks wheather the game the game has ended or not and acts accordingly
There are 16 win conditions (8 per player) but the same check can be used for each.
Say that your array of 9 represents the board like this:
[0][1][2]
[3][4][5]
[6][7][8]
An example of a winning row is if 0,1 and 2 are all O or all X. So you can check them all in one statement:
1 2 3 4
if (board[0] == board[1] == board[2])
{
return board[0];
}
You could even store all of the winning positions sequentially in an array, and loop through that, effectively reducing your original 16 if statements down to just one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int win_array[24] = {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 i=0; i <= 21; i+=3)
{
if(board[win_array[i]] == board[win_array[i]+1] == board[win_array[i]+2])
{
return board[win_array[i]];
}
}
By returning the value in the check when there is a win, you can tell who's won in your function call:
1 2 3 4 5 6 7 8 9 10 11 12
if(HasWon() == 'O')
{
cout << "O has won";
}
elseif (HasWon() == 'X')
{
cout << "X has won";
}
else
{
// No winner yet
}
Correct me if I'm wrong but I don't think that would work. The operator == returns a bool value so say board[0] - [1] - [2] all equal 'a' then the first "==" will check
I want it to return the appropriate value (1 or 2) depending on which char is in the three squares (gameBoard[0], [1], [2]) how can I get this to happen