A 'win' state checker:
Code:
char *checkwin(char board[2][2]) // Prototype might be a bit off, adjust accordingly ;)
{
// Check horizontal
for(int y=0;y<3;y++) {
int xs, os;
for(int x=0;x<3;x++) {
xs += (board[x][y] = = 'X');
os += (board[x][y] = = 'O');
}
}
if(xs= =3) return("X Wins");
if(os= =3) return("O Wins");
// Check vertical
for(int x=0;x<3;x++) {
int xs, os;
for(int y=0;y<3;y++) {
xs += (board[x][y] = = 'X');
os += (board[x][y] = = 'O');
}
}
if(xs= =3) return("X Wins");
if(os= =3) return("O Wins");
// Check left-right diag
for(int a=0,xs=0,os=0;a<3;a++) {
xs += (board[a][a] = = 'X');
os += (board[a][a] = = 'O');
}
if(xs= =3) return("X Wins");
if(os= =3) return("O Wins");
// Check right-left diag
for(int a=0,xs=0,os=0;a<3;a++) {
xs += (board[a][2-a] = = 'X');
os += (board[a][2-a] = = 'O');
}
if(xs= =3) return("X Wins");
if(os= =3) return("O Wins");
// No winnar.
return;
}
There is almost certainly better ways of doing this (making a string of 3 characters in the array and matching that against a string of 'XXX' or 'OOO', for instance). This was just a 60 second slap together that'll do the job and demonstrate the logic cleanly.
