TIC-TAC-TOE PROGRAM IN C
The program is quite long but logic is easy
Logic:-
1) Make a array in which minimun 9 values can be stored
2) Fill the values 1 to 9 in your array.
3) Now ask the user to give a values from 1 to 9
4) Now suppose user give 5;
5) Replace 5th index value by 'o' or '*' .
6)Similarly take values until winning conditions are fulfilled.
Note:- For knowing winning condition please check out program below,
----------------------------------------------------------
----------------------------------------------------------
#include <stdio.h>
#include<conio.h>
int result();
void displayBoard();
char game[10]={'u','1','2','3','4','5','6','7','8','9'};
int main()
{ int index,cw;
int player=1;
char sign;
do{
displayBoard();
printf("Press enter to start game! Have fun:\n");
player = (player % 2) ? 1 : 2;
printf("Player %d, enter a number: ", player);
scanf("%d", &index);
sign = (player == 1) ? 'X' : 'O';
if (index == 1 && game[1] == '1')
game[1] = sign;
else if (index == 2 && game[2] == '2')
game[2] = sign;
else if (index == 3 && game[3] == '3')
game[3] = sign;
else if (index == 4 && game[4] == '4')
game[4] = sign;
else if (index == 5 && game[5] == '5')
game[5] = sign;
else if (index == 6 && game[6] == '6')
game[6] = sign;
else if (index == 7 && game[7] == '7')
game[7] = sign;
else if (index == 8 && game[8] == '8')
game[8] = sign;
else if (index == 9 && game[9] == '9')
game[9] = sign;
else
{
printf("Invalid move ");
player--;
getch();
}
cw=result();
player++;}
while (cw == - 1);
displayBoard();
if (cw == 1)
printf("==>\aPlayer %d win ", --player);
else
printf("==>\aGame draw");
getch();
return 0 ;
}
void displayBoard(){
printf("|%c |%c |%c |\n",game[1],game[2],game[3]);
printf("+---+---+---+\n");
printf("|%c |%c |%c |\n",game[4],game[5],game[6]);
printf("+---+---+---+\n");
printf("|%c |%c |%c |\n",game[7],game[8],game[9]);
}
int result()
{
if (game[1] == game[2] && game[2] == game[3])
return 1;
else if (game[4] == game[5] && game[5] == game[6])
return 1;
else if (game[7] == game[8] && game[8] == game[9])
return 1;
else if (game[1] == game[4] && game[4] == game[7])
return 1;
else if (game[2] == game[5] && game[5] == game[8])
return 1;
else if (game[3] == game[6] && game[6] == game[9])
return 1;
else if (game[1] == game[5] && game[5] == game[9])
return 1;
else if (game[3] == game[5] && game[5] == game[7])
return 1;
else if (game[1] != '1' && game[2] != '2' && game[3] != '3' &&
game[4] != '4' && game[5] != '5' && game[6] != '6' && game[7]
!= '7' && game[8] != '8' && game[9] != '9')
return 0;
else
return - 1;
}
RESULT:- Do check out video below:
-----------------------------------------------
----------------------------------------------------------------------------------
VIDEO:-
Comments
Post a Comment