Skip to content

Instantly share code, notes, and snippets.

@tasfik007
Last active May 11, 2020 08:56
Show Gist options
  • Save tasfik007/3bdd87bd9199ef631aba4a90874e01f6 to your computer and use it in GitHub Desktop.
Save tasfik007/3bdd87bd9199ef631aba4a90874e01f6 to your computer and use it in GitHub Desktop.
TicTacToe game using C
// *** This Template was created by Tasfik Rahman ***
#include <stdio.h>
#define SIZE 3
#define bool int
#define true 1
#define false 0
#define nl printf("\n")
int board[SIZE][SIZE];
void printBoard()
{
int i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (board[i][j] == 0)
printf("- ");
else if (board[i][j] == 1)
printf("O ");
else if (board[i][j] == 2)
printf("X ");
}
nl;
}
}
bool validMove(int x, int y)
{
return board[x][y] == 0 ? true : false;
}
void makeMove(bool player)
{
if (player)
printf("Player 1(true) move:\n");
else
printf("Player 2(false) move:\n");
int x, y;
scanf("%d %d", &x, &y);
if (validMove(x, y))
board[x][y] = (player) ? 1 : 2;
else
{
printf("Not a valid move!! try again.\n");
makeMove(player);
}
}
bool isRowMatch(bool player)
{
int count_match = 0, i, j;
int mv = player ? 1 : 2;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (board[i][j] == mv)
count_match++;
}
if (count_match == SIZE)
return true;
count_match = 0;
}
return false;
}
bool isColMatch(bool player)
{
int count_match = 0, i, j;
int mv = player ? 1 : 2;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (board[j][i] == mv)
count_match++;
}
if (count_match == SIZE)
return true;
count_match = 0;
}
return false;
}
bool isLeftDiagMatch(bool player)
{
int count_match = 0, i, j;
int mv = player ? 1 : 2;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (i == j)
{
if (board[i][j] == mv)
count_match++;
}
}
}
return count_match == SIZE;
}
bool isRightDiagMatch(bool player)
{
int count_match = 0, i, j;
int mv = player ? 1 : 2;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if ((SIZE - j + 1) == i)
{
if (board[i][j] == mv)
count_match++;
}
}
}
return count_match == SIZE;
}
bool isDraw()
{
int count_match = 0, i, j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
if (board[i][j] != 0)
count_match++;
}
}
return count_match == SIZE * SIZE;
}
bool isOver(bool player)
{
return ((isRowMatch(player)) || (isColMatch(player)) || (isLeftDiagMatch(player)) || (isRightDiagMatch(player)) || (isDraw()));
}
bool playGame()
{
printBoard();
bool player = true;
while (!isOver(!player))
{
makeMove(player);
system("cls");
printBoard();
player = !player;
// cout<<isRowMatch(player)<<", "<<isColMatch(player)<<", "<<isRightDiagMatch(player)<<", "<<isLeftDiagMatch(player)<<endl;
}
if (isDraw())
printf("Match is draw!!\n");
else if (!player)
printf("Player 1(true) won the match\n");
else
printf("Player 2(false) won the match\n");
}
int main()
{
playGame();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment