Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions tictactoe.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#include <stdio.h>
#include <stdlib.h>

#define SIZE 3

void initializeBoard(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
board[i][j] = '1' + i * SIZE + j;
}
}
}

void printBoard(char board[SIZE][SIZE]) {
printf("\n");
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
printf(" %c ", board[i][j]);
if (j < SIZE - 1) printf("|");
}
printf("\n");
if (i < SIZE - 1) printf("---+---+---\n");
}
printf("\n");
}

int checkWin(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; ++i) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
return board[i][0] == 'X' ? 1 : board[i][0] == 'O' ? 2 : 0;
if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
return board[0][i] == 'X' ? 1 : board[0][i] == 'O' ? 2 : 0;
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
return board[0][0] == 'X' ? 1 : board[0][0] == 'O' ? 2 : 0;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
return board[0][2] == 'X' ? 1 : board[0][2] == 'O' ? 2 : 0;
return 0;
}

int isDraw(char board[SIZE][SIZE]) {
for (int i = 0; i < SIZE; ++i)
for (int j = 0; j < SIZE; ++j)
if (board[i][j] != 'X' && board[i][j] != 'O')
return 0;
return 1;
}

int main(void) {
char board[SIZE][SIZE];
int currentPlayer = 1; // 1 -> X, 2 -> O
int choice;
initializeBoard(board);

while (1) {
printBoard(board);
printf("Player %d [%c], enter your move (1-9): ", currentPlayer, currentPlayer == 1 ? 'X' : 'O');
if (scanf("%d", &choice) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if (choice < 1 || choice > 9) {
printf("Invalid move. Try again.\n");
continue;
}
int row = (choice - 1) / SIZE;
int col = (choice - 1) % SIZE;
if (board[row][col] == 'X' || board[row][col] == 'O') {
printf("Cell already taken. Try again.\n");
continue;
}
board[row][col] = currentPlayer == 1 ? 'X' : 'O';
int result = checkWin(board);
if (result == 1) {
printBoard(board);
printf("Player 1 (X) wins!\n");
break;
} else if (result == 2) {
printBoard(board);
printf("Player 2 (O) wins!\n");
break;
} else if (isDraw(board)) {
printBoard(board);
printf("It's a draw!\n");
break;
}
currentPlayer = 3 - currentPlayer; // toggle between 1 and 2
}
return 0;
}