下面是一个使用C++面向对象的思想编写的三连棋游戏的示例代码:

#include <iostream>
#include <vector>

using namespace std;

class TicTacToe {
private:
    vector<vector<char>> board;
    char currentPlayer;

public:
    TicTacToe() {
        board = vector<vector<char>>(3, vector<char>(3, '-'));
        currentPlayer = '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;
        }
        cout << "------" << endl;
    }

    bool isBoardFull() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == '-') {
                    return false;
                }
            }
        }
        return true;
    }

    bool makeMove(int row, int col) {
        if (row < 0 || row >= 3 || col < 0 || col >= 3 || board[row][col] != '-') {
            return false;
        }
        board[row][col] = currentPlayer;
        return true;
    }

    bool checkWin() {
        // 检查行
        for (int i = 0; i < 3; i++) {
            if (board[i][0] != '-' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
                return true;
            }
        }
        // 检查列
        for (int j = 0; j < 3; j++) {
            if (board[0][j] != '-' && board[0][j] == board[1][j] && board[1][j] == board[2][j]) {
                return true;
            }
        }
        // 检查对角线
        if (board[0][0] != '-' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
            return true;
        }
        if (board[0][2] != '-' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
            return true;
        }
        return false;
    }

    void play() {
        while (!isBoardFull()) {
            printBoard();
            int row, col;
            cout << "Player " << currentPlayer << " make your move (row col): ";
            cin >> row >> col;
            if (makeMove(row, col)) {
                if (checkWin()) {
                    printBoard();
                    cout << "Player " << currentPlayer << " wins!" << endl;
                    return;
                }
                currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
            } else {
                cout << "Invalid move. Try again." << endl;
            }
        }
        printBoard();
        cout << "It's a tie!" << endl;
    }
};

int main() {
    TicTacToe game;
    game.play();
    return 0;
}

这里我们创建了一个TicTacToe类,包含了棋盘的状态、当前玩家以及游戏的各种操作方法。使用play()方法开始游戏,游戏会循环进行直到棋盘满或有玩家获胜。在每个回合中,玩家通过输入行和列来进行移动,如果移动有效,则切换玩家并检查是否有玩家获胜。最后,打印出游戏结果。

这个示例代码只是一个简单的实现,你可以根据需求进行修改和扩展

用C++面向对象的思想写一个三连棋游戏

原文地址: https://www.cveoy.top/t/topic/hZ1D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录