Tic-Tac-Toe game in C
Below is a simple Tic-Tac-Toe game in C. Copy and paste this code into a C file (e.g., TicTacToe.c) and run it.
// Include stdio.h and stdbool.h #include #define SIZE 3 char board[SIZE][SIZE] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}}; char currentPlayer = 'X'; void printBoard() { printf("-------------\n"); for (int i = 0; i < SIZE; i++) { printf("| "); for (int j = 0; j < SIZE; j++) { printf("%c | ", board[i][j]); } printf("\n-------------\n"); } } bool isValidMove(int row, int col) { return row >= 0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] == ' '; } void switchPlayer() { currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; } bool checkWin() { // Check rows, columns, and diagonals return checkRows() || checkColumns() || checkDiagonals(); } bool checkRows() { for (int i = 0; i < SIZE; i++) { if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) { return true; } } return false; } bool checkColumns() { for (int i = 0; i < SIZE; i++) { if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) { return true; } } return false; } bool checkDiagonals() { return (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) || (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer); } bool isBoardFull() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (board[i][j] == ' ') { return false; } } } return true; } int main() { printBoard(); while (true) { printf("Player %c's turn.\n", currentPlayer); int row, col; do { printf("Enter row (0-2): "); scanf("%d", &row); printf("Enter column (0-2): "); scanf("%d", &col); if (!isValidMove(row, col)) { printf("Invalid move. Try again.\n"); } } while (!isValidMove(row, col)); board[row][col] = currentPlayer; printBoard(); if (checkWin()) { printf("Player %c wins!\n", currentPlayer); break; } else if (isBoardFull()) { printf("It's a draw!\n"); break; } switchPlayer(); } return 0; }