Ok, i have my tic tac toe game almost complete, i just need a loop or if statement or both that checks if somebody won. My board is board[3][3]. HOw do i do this? Thanks
Ok, i have my tic tac toe game almost complete, i just need a loop or if statement or both that checks if somebody won. My board is board[3][3]. HOw do i do this? Thanks
The easiest way would be lots of if statements.....
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
check for each possible victory condition.
there are eight.
2 diagonal, 3 horizontal, 3 vertical
I think this should do it but I don't have a compiler here.
bool CheckForWin( char board[3][3], char ch )
{
// check for diagonal cases
if( ch == board[0][0] && ch == board[1][1] && ch == board[2][2] )
return( true );
if( ch == board[0][2] && ch == board[1][1] && ch == board[2][0] )
return( true );
// check for horizontal cases
if( ch == board[0][0] && ch == board[0][1] && ch == board[0][2] )
return( true );
if( ch == board[1][0] && ch == board[1][1] && ch == board[1][2] )
return( true );
if( ch == board[2][0] && ch == board[2][1] && ch == board[2][2] )
return( true );
// check for vertical cases
if( ch == board[0][0] && ch == board[1][0] && ch == board[2][0] )
return( true );
if( ch == board[0][1] && ch == board[1][1] && ch == board[2][1] )
return( true );
if( ch == board[0][2] && ch == board[1][2] && ch == board[2][2] )
return( true );
// not a win yet
return( false );
}
Well, checking all 8 cases is a viable option if you're dealing with a tic-tac-toe game, but one thing to consider is you could ALSO just write a function that checks if the last move made is in a line of 3 (i.e. is game-winning).
For this game, it might be MORE work to do it like this, but if you wanted to program something like connect-4, you MUST check like this (see if each piece wins the game) because to try to check for every possible victory in a larger board wouldn't be viable.