In: Computer Science
How to make a 2D array Tic Tac Toe game in C?
Below code demonstrates a Tic Tac Toe game in C language.
The variable and function names are self-explanatory:
For e.g. playersMove() function is for getting first player's i.e.
user's move, while the computersMove()
function gets the second player's, i.e. computer's move.
The displayGame() method displays the results on the output
screen.
Code starts below this line:
#include <stdio.h>
#include <stdlib.h>
char ticTacToe[3][3]; .
char findWinner(void);
void initializeGame(void);
void playersMove(void);
void computersMove(void);
void displayGame(void);
int main(void)
{
char gameOver;
printf("Tic Tac Toe.\n");
printf("Player 1: You\n");
printf("Player 2: Computer\n");
gameOver = ' ';
initializeGame();
do {
displayGame();
playersMove();
gameOver = findWinner();
if(gameOver!= ' ')
break;
computersMove();
gameOver = findWinner();
} while(gameOver== ' ');
if(gameOver=='X') printf("Congrats!! You won the
Game!\n");
else printf("Computer wins!! You Lose!!\n");
displayGame();
return 0;
}
void initializeGame(void)
{
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++) ticTacToe[i][j] = ' ';
}
void playersMove(void)
{
int x, y;
printf("Enter X,Y coordinates for your move: ");
scanf("%d%*c%d", &x, &y);
x--; y--;
if(ticTacToe[x][y]!= ' '){
printf("Not a valid move, play again.\n");
playersMove();
}
else ticTacToe[x][y] = 'X';
}
void computersMove(void)
{
int i, j;
for(i=0; i<3; i++){
for(j=0; j<3; j++)
if(ticTacToe[i][j]==' ') break;
if(ticTacToe[i][j]==' ') break;
}
if(i*j==9) {
printf("draw\n");
exit(0);
}
else
ticTacToe[i][j] = 'O';
}
void displayGame(void)
{
int t;
for(t=0; t<3; t++) {
printf(" %c | %c | %c ",ticTacToe[t][0],
ticTacToe[t][1], matrix [t][2]);
if(t!=2) printf("\n---|---|---\n");
}
printf("\n");
}
char findWinner(void)
{
int i;
for(i=0; i<3; i++)
if(ticTacToe[i][0]==ticTacToe[i][1] &&
ticTacToe[i][0]==ticTacToe[i][2]) return ticTacToe[i][0];
for(i=0; i<3; i++)
if(ticTacToe[0][i]==ticTacToe[1][i] &&
ticTacToe[0][i]==ticTacToe[2][i]) return ticTacToe[0][i];
if(ticTacToe[0][0]==ticTacToe[1][1] &&
ticTacToe[1][1]==ticTacToe[2][2])
return ticTacToe[0][0];
if(ticTacToe[0][2]==ticTacToe[1][1] &&
ticTacToe[1][1]==ticTacToe[2][0])
return ticTacToe[0][2];
return ' ';
}