以下是一个简单的五子棋小游戏的 C++ 代码实现:

#include <iostream>
#include <vector>

using namespace std;

const int SIZE = 15;

vector<vector<int>> board(SIZE, vector<int>(SIZE, 0));

// 判断胜负
bool checkWin(int player, int row, int col) {
    // 水平方向
    int count = 0;
    for (int i = col - 4; i <= col + 4; i++) {
        if (i < 0 || i >= SIZE) continue;
        if (board[row][i] == player) {
            count++;
            if (count == 5) return true;
        } else {
            count = 0;
        }
    }

    // 垂直方向
    count = 0;
    for (int i = row - 4; i <= row + 4; i++) {
        if (i < 0 || i >= SIZE) continue;
        if (board[i][col] == player) {
            count++;
            if (count == 5) return true;
        } else {
            count = 0;
        }
    }

    // 左斜方向
    count = 0;
    for (int i = -4; i <= 4; i++) {
        int r = row + i;
        int c = col + i;
        if (r < 0 || r >= SIZE || c < 0 || c >= SIZE) continue;
        if (board[r][c] == player) {
            count++;
            if (count == 5) return true;
        } else {
            count = 0;
        }
    }

    // 右斜方向
    count = 0;
    for (int i = -4; i <= 4; i++) {
        int r = row + i;
        int c = col - i;
        if (r < 0 || r >= SIZE || c < 0 || c >= SIZE) continue;
        if (board[r][c] == player) {
            count++;
            if (count == 5) return true;
        } else {
            count = 0;
        }
    }

    return false;
}

// 打印棋盘
void printBoard() {
    cout << "  ";
    for (int i = 0; i < SIZE; i++) {
        cout << i << " ";
    }
    cout << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << i << " ";
        for (int j = 0; j < SIZE; j++) {
            if (board[i][j] == 0) cout << "+ ";
            else if (board[i][j] == 1) cout << "O ";
            else cout << "X ";
        }
        cout << endl;
    }
}

int main() {
    int player = 1;
    int row, col;

    while (true) {
        cout << "Player " << player << "'s turn. Enter row and column: ";
        cin >> row >> col;

        if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != 0) {
            cout << "Invalid move. Try again!" << endl;
            continue;
        }

        board[row][col] = player;
        printBoard();

        if (checkWin(player, row, col)) {
            cout << "Player " << player << " wins!" << endl;
            break;
        }

        player = (player == 1) ? 2 : 1;
    }

    return 0;
}

这个代码实现了一个简单的五子棋小游戏,玩家 1 用'O'表示,玩家 2 用'X'表示。玩家轮流输入行和列,程序会在棋盘上放置相应的棋子,并判断是否有玩家获胜。如果有玩家获胜,则游戏结束并输出获胜玩家的信息。

C++ 五子棋游戏代码实现 - 简单易懂的教程

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

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