X-O

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
6.2 kB
4
Indexable
#include <iostream>
#include <fstream>
#include <limits>
#include <random>
#include <cstring>

const char PLAYER_ONE = 'X';
const char PLAYER_TWO = 'O';
const char EMPTY = '-';

void drawBoard(const int fieldSize, char** board) {
    for (int i = 0; i < fieldSize; ++i) {
        for (int j = 0; j < fieldSize; ++j) {
            std::cout << board[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

bool checkWin(const int fieldSize, char** board, char player) {
    for (int i = 0; i < fieldSize; ++i) {
        bool rowWin = true;
        bool colWin = true;
        for (int j = 0; j < fieldSize; ++j) {
            rowWin &= (board[i][j] == player);
            colWin &= (board[j][i] == player);
        }
        if (rowWin || colWin) {
            return true;
        }
    }

    bool diagonalWin = true;
    bool reverseDiagonalWin = true;
    for (int i = 0; i < fieldSize; ++i) {
        diagonalWin &= (board[i][i] == player);
        reverseDiagonalWin &= (board[i][fieldSize - i - 1] == player);
    }

    return diagonalWin || reverseDiagonalWin;
}

void computerMove(const int fieldSize, char** board, char player) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distrib(0, fieldSize - 1);

    int row = distrib(gen);
    int col = distrib(gen);

    while (board[row][col] != EMPTY) {
        row = distrib(gen);
        col = distrib(gen);
    }

    std::cout << "Хід комп'ютера: рядок " << row + 1 << ", стовпчик " << col + 1 << std::endl;
    board[row][col] = player;
}

void printResults(const int result[], int numGames) {
    int playerOneWins = 0;
    int playerTwoWins = 0;
    int draws = 0;

    std::ofstream file("results.txt", std::ios::app); // Open the file in append mode

    for (int i = 0; i < numGames; ++i) {
        if (result[i] == 1) {
            ++playerOneWins;
            file << "Player " << i + 1 << ":1 Computer\n";
        } else if (result[i] == -1) {
            ++playerTwoWins;
            file << "Player " << i + 1 << ":0 Computer\n";
        } else {
            ++draws;
            file << "Player " << i + 1 << ":0 Player\n";
        }
    }

    std::cout << "Гравець виграв: " << playerOneWins << std::endl;
    std::cout << "Комп'ютер виграв: " << playerTwoWins << std::endl;
    std::cout << "Нічия: " << draws << std::endl;
}


int main() {
    std::string playerName;
    std::cout << "Введіть ваше ім'я: ";
    std::getline(std::cin, playerName);

    int fieldSize;
    std::cout << "Введіть розмір поля: ";
    if (!(std::cin >> fieldSize)) {
        std::cout << "Помилка. Розмір поля може бути заданий числом!" << std::endl;
        return 1;
    }

    std::ofstream file("results.txt", std::ios::app); // Open the file in append mode

    while (true) {
        char** board = new char*[fieldSize];
        for (int i = 0; i < fieldSize; ++i) {
            board[i] = new char[fieldSize];
            for (int j = 0; j < fieldSize; ++j) {
                board[i][j] = EMPTY;
            }
        }

        bool playerOneTurn = true;
        int moves = fieldSize * fieldSize;

        while (moves > 0) {
            drawBoard(fieldSize, board);

            if (playerOneTurn) {
                int row, col;
                std::cout << playerName << ", введіть свій хід через пробіл (рядок і стовпчик): ";
                std::cin >> row >> col;

                row -= 1; // subtract 1 from row
                col -= 1; // subtract 1 from column

                while (std::cin.fail() || row < 0 || row >= fieldSize || col < 0
                       || col >= fieldSize || board[row][col] != EMPTY) {
                    std::cin.clear();
                    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    std::cout << "Неправильний ввід. Будь ласка, введіть через пробіл рядок і стовпчик: ";
                    std::cin >> row >> col;
                    row -= 1; // subtract 1 from row
                    col -= 1; // subtract 1 from column
                }

                board[row][col] = PLAYER_ONE;
                if (checkWin(fieldSize, board, PLAYER_ONE)) {
                    drawBoard(fieldSize, board);
                    std::cout << "Ти переміг, " << playerName << "!" << std::endl;
                    file << "Результат: " << playerName << " виграв.\n";
                    // Rest of code ...
                break;
            }

            playerOneTurn = false;
        } 
        else {
            computerMove(fieldSize, board, PLAYER_TWO);
            if (checkWin(fieldSize, board, PLAYER_TWO)) {
                drawBoard(fieldSize, board);
                std::cout << "Комп'ютер переміг!" << std::endl;
                file << "Результат: Комп'ютер виграв.\n";
                break;
            }
            
            playerOneTurn = true;
        }

        --moves;
    }

    if (moves == 0) {
        drawBoard(fieldSize, board);
        std::cout << "Нічия!" << std::endl;
        file << "Результат: Нічия.\n";
    }

    // Release the memory for the board
    for (int i = 0; i < fieldSize; ++i) {
        delete[] board[i];
    }
    delete[] board;

    // Ask the user if they want to play again
    std::string playAgain;
    std::cout << "Бажаєте зіграти ще раз? (так/ні): ";
    std::cin >> playAgain;

    while (playAgain != "так" && playAgain != "ні") {
        std::cout << "Неправильний ввід. Будь ласка, введіть 'так' або 'ні': ";
        std::cin >> playAgain;
    }

    if (playAgain == "ні") {
        break;
    }
}

    file.close(); // Close the file at the end of the program
    return 0;
}