Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tic tac toe #30

Open
Hippowyatt opened this issue Feb 16, 2024 · 0 comments
Open

Tic tac toe #30

Hippowyatt opened this issue Feb 16, 2024 · 0 comments

Comments

@Hippowyatt
Copy link

#include
#include
#include

using namespace std;

// Function to draw the Tic Tac Toe board
void drawBoard(const vector<vector>& board) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
cout << board[i][j];
if (j < 2)
cout << " | ";
}
cout << endl;
if (i < 2)
cout << "---------" << endl;
}
}

// Function to check if a player has won
bool checkWin(const vector<vector>& board, char player) {
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;
}
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;
}

int main() {
vector<vector> board(3, vector(3, ' ')); // Initialize empty board
int row, col;
char currentPlayer = 'X';

cout << "Welcome to Tic Tac Toe!" << endl;

// Main game loop
while (true) {
    // Draw the board
    cout << endl;
    drawBoard(board);

    // Player input
    cout << "Player " << currentPlayer << ", enter your move (row and column): ";
    cin >> row >> col;

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

    // Update the board with the player's move
    board[row - 1][col - 1] = currentPlayer;

    // Check if the current player has won
    if (checkWin(board, currentPlayer)) {
        cout << endl << "Player " << currentPlayer << " wins!" << endl;
        drawBoard(board);
        break;
    }

    // Check for a draw
    bool isFull = true;
    for (const auto& row : board) {
        for (char cell : row) {
            if (cell == ' ') {
                isFull = false;
                break;
            }
        }
    }
    if (isFull) {
        cout << endl << "It's a draw!" << endl;
        drawBoard(board);
        break;
    }

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

return 0;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant