In: Computer Science
In a game of tic tac toe. How do you check if all the positions in a double array are taken, the double arrays are used to store the x's and o's?
Answer :
In a tic tac toe game there is 8 combinations to win,
3 Columns, 3 Rows and 2 Diagonal.
Let's say we use 2D array to store the tic tac toe game board.
Let the first player letter be 'X' and the second player letter be 'O'. Let second player be computer.
Initially all the cells will be filled with spaces(' ').
For every second player we should check if there is any cell left to fill the letter.('O')
If there is no empty cell remaining then, we should display the game as Draw.
HERE IS CODE FOR THAT:
void second_player_move(void)
{
int i, j;
for(i=0; i<3; i++){
for(j=0; j<3; j++){
if(matrix[i][j]==' ') break;
}
if(matrix[i][j]==' ') break;
}
if(i*j==9) {
printf("draw\n");
exit(0);
}
else
matrix[i][j] = 'O';
}
When there is no empty cell in the board i*j will result to 9. Which displays draw and the game will end.
Player 1 Moves : 1, 3, 5, 7, 9
Player 2 Moves : 2, 4, 6, 8
After 9th move all cells will be filled,
At 10th move there will be no cell left to be filled.
Else letter 'O' will be entried to empty cell on the board.
Hence, by this way we could check whether all the positions of the double array are used to store 'X' and 'O' s.