井字棋Dev-c++

#include 
#include 
#include 
using namespace std;
const int ROW = 3;
const int COL = 3;
char board[ROW][COL] = { {' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '} };
char player1 = 'O';
char player2 = 'X';
int turn = 1;
bool gameOver = false;

void drawBoard();
void play();
bool isMoveValid(int, int);
void makeMove(int, int, char);
bool isGameOver();
bool isWinner(char);

int main()
{
    drawBoard();
    while (!gameOver) {
        play();
        turn++;
        gameOver = isGameOver();
    }

    if (isWinner(player1)) {
        cout << "Player 1 (" << player1 << ") wins!" << endl;
    }
    else if (isWinner(player2)) {
        cout << "Player 2 (" << player2 << ") wins!" << endl;
    }
    else {
        cout << "It's a tie!" << endl;
    }

    return 0;
}

void drawBoard() {
    cout << " " << setw(3) << "1" << setw(3) << "2" << setw(3) << "3" << endl;
    for (int i = 0; i < ROW; i++) {
        cout << i + 1 << setw(3);
        for (int j = 0; j < COL; j++) {
            cout << "|" << setw(2) << board[i][j] << setw(2);
        }
        cout << "|" << endl;
    }
}

void play() {
    int row, col;
    char player;
    if (turn % 2 == 0) {
        player = player2;
    }
    else {
        player = player1;
    }

    cout << "Player " << turn << " (" << player << ") turn: ";
    cin >> row >> col;

    if (!isMoveValid(row - 1, col - 1)) {
        cout << "Invalid move! Try again." << endl;
        play();
        return;
    }

    makeMove(row - 1, col - 1, player);
    drawBoard();
}

bool isMoveValid(int row, int col) {
    if (row < 0 || row >= ROW || col < 0 || col >= COL) {
        return false;
    }
    if (board[row][col] != ' ') {
        return false;
    }
    return true;
}

void makeMove(int row, int col, char player) {
    board[row][col] = player;
}

bool isGameOver() {
    if (isWinner(player1) || isWinner(player2)) {
        return true;
    }
    for (int i = 0; i < ROW; i++) {
        for (int j = 0; j < COL; j++) {
            if (board[i][j] == ' ') {
                return false;
            }
        }
    }
    return true;
}

bool isWinner(char player) {
    for (int i = 0; i < ROW; 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;
}

以上是用c++写的井字棋,用来无聊时打发打发时间

你可能感兴趣的:(C/C++,c++,算法,开发语言)