Tic-Tac-Toe Game

A simple console-based Tic-Tac-Toe game.

cppCopy code#include <iostream>
using namespace std;

char board[3][3] = { {'1','2','3'},{'4','5','6'},{'7','8','9'} };
char player = 'X';

void printBoard() {
    cout << endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}

bool isWinner() {
    for (int i = 0; i < 3; i++) {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
            return true;
        if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
            return true;
    }
    if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
        return true;
    if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
        return true;
    return false;
}

int main() {
    int move;
    for (int turns = 0; turns < 9; turns++) {
        printBoard();
        cout << "Player " << player << ", enter your move (1-9): ";
        cin >> move;

        int row = (move - 1) / 3;
        int col = (move - 1) % 3;

        if (move < 1 || move > 9 || board[row][col] != (move + '0')) {
            cout << "Invalid move! Try again." << endl;
            turns--;
            continue;
        }

        board[row][col] = player;

        if (isWinner()) {
            printBoard();
            cout << "Player " << player << " wins!" << endl;
            return 0;
        }

        player = (player == 'X') ? 'O' : 'X';
    }

    printBoard();
    cout << "It's a draw!" << endl;
    return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *