A bunch of if statements should work.
How about a function that runs after each move the check for a winning pattern?
So there are 8 winning lines in tic-tac-toe (three horizontals, three verticals and two diagonals). Presuming your array represents the board like this:
0 1 2
3 4 5
6 7 8
Then you can see which array combinations are the winning ones. (0,1,2 or 1,4,7 are two examples).
So you could use a function to check those spaces and return true if a winner is found. It may be a bit crude and, with a bit of thought, there's probably a better way of doing it (for example, you could use different values for the user's pieces and tally up the scores to see if there's a winner), but here's the groundwork for one way:
1 2 3 4 5 6 7
|
bool HasWon(char board[])
{
if (board[0] == board[1] == board[2])
{
// There's a potential win here. All three points in a winning row are the same.
}
}
|
You might need an extra bit of validation on your check. I'm not quiet sure what's happening when you initialise your board in the for loop on line 41 (be careful when adding integers to chars). I'm presuming you're wanting it to display the numbers 1 - 9 unless there's an X or O in there. If a board is initialised with the same value in each square, that needs to be accounted for in a win check (yes, the three points may match, but if they're not populated with an X or O, it's not a win).
So you might want to expand on that above and add something that checks the positions are populated with an X or O:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
bool HasWon(char board[])
{
if (board[0] == board[1] == board[2])
{
if (board[0] == 'X')
{
// If board[0] is X, we can assume that [1] and [2] are X. X has won.
return true;
}
else if (board[0] == 'O')
{
// Same as above but for O.
return true;
}
else
{
// This depends on how the board is initialised, but if all three spaces are the same
// and they're not X or O, then they're probably unpopulated. Not a win here.
return false;
}
}
}
|
You'd need a check like that for each winning combination. Here's a thought, though. Instead of a bool function, why not try an integer returning function and make a couple of defines for return types?
1 2 3
|
#define NO_WIN 0
#define WIN_X 1
#define WIN_O 2
|
Then, you could change the returns in the function:
1 2 3 4 5 6 7
|
. . .
if (board[0] == 'X')
{
// If board[0] is X, we can assume that [1] and [2] are X. X has won.
return WIN_X;
}
. . .
|
That way, when you call the function, it's easy to tell from the returned value who the winner is.
Hope this is of some help.