tictactoe

 avatar
unknown
plain_text
a year ago
2.6 kB
4
Indexable
#include <iostream>
#include <vector>
#include <string>

using namespace std;

//print board
void printBoard(const vector<vector<char>>& board) {
    for (const auto& row : board) {
        for (char cell : row) {
            cout << cell << " ";
        }
        cout << endl;
    }
}

//check if a player has won
bool checkWin(const vector<vector<char>>& board, char player) {
    // Check rows and columns
    for (int i = 0; i < 3; ++i) {
        if (board[i][0] == player && board[i][1] == player && board[i][2] == player)
            return true;
        if (board[0][i] == player && board[1][i] == player && board[2][i] == player)
            return true;
    }
    //check diagonals
    if (board[0][0] == player && board[1][1] == player && board[2][2] == player)
        return true;
    if (board[0][2] == player && board[1][1] == player && board[2][0] == player)
        return true;
    return false;
}

//check if the board is full
bool isBoardFull(const vector<vector<char>>& board) {
    for (const auto& row : board) {
        for (char cell : row) {
            if (cell == '-')
                return false;
        }
    }
    return true;
}

int main() {
    vector<vector<char>> board(3, vector<char>(3, '-')); // Initialize an empty board

    char currentPlayer = 'X';
    bool gameOver = false;

    while (!gameOver) {
        // Print the board
        cout << "Current board:" << endl;
        printBoard(board);

        // Get the player's move
        int row, col;
        cout << "Player " << currentPlayer << ", enter row (1-3) and column (1-3) to place your mark: ";
        cin >> row >> col;
        --row; --col;

        // check if the move is valid
        if (row < 0 || row >= 3 || col < 0 || col >= 3 || board[row][col] != '-') {
            cout << "Invalid move! Try again." << endl;
            continue;
        }

        // place player's mark on the board
        board[row][col] = currentPlayer;

        // check if player has won
        if (checkWin(board, currentPlayer)) {
            cout << "Player " << currentPlayer << " wins!" << endl;
            gameOver = true;
        } else if (isBoardFull(board)) { // Check for a draw
            cout << "It's a draw!" << endl;
            gameOver = true;
        }

        // switch players
        currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
    }

    // print the final board
    cout << "Final board:" << endl;
    printBoard(board);

    return 0;
}
Editor is loading...
Leave a Comment