温馨提示×

c++实现五子棋的代码怎么写

c++
小亿
128
2024-04-26 22:17:11
栏目: 编程语言

以下是一个简单的C++实现五子棋的代码示例:

#include <iostream>
#include <vector>

const int BOARD_SIZE = 15;

char board[BOARD_SIZE][BOARD_SIZE];

void initBoard() {
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            board[i][j] = '.';
        }
    }
}

void printBoard() {
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            std::cout << board[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

bool checkWin(int x, int y, char player) {
    // 检查横向
    int count = 1;
    for (int i = 1; i < 5; i++) {
        if (x+i >= BOARD_SIZE || board[x+i][y] != player) {
            break;
        }
        count++;
    }
    for (int i = 1; i < 5; i++) {
        if (x-i < 0 || board[x-i][y] != player) {
            break;
        }
        count++;
    }
    if (count >= 5) {
        return true;
    }

    // 检查纵向
    count = 1;
    for (int i = 1; i < 5; i++) {
        if (y+i >= BOARD_SIZE || board[x][y+i] != player) {
            break;
        }
        count++;
    }
    for (int i = 1; i < 5; i++) {
        if (y-i < 0 || board[x][y-i] != player) {
            break;
        }
        count++;
    }
    if (count >= 5) {
        return true;
    }

    // 检查斜向
    count = 1;
    for (int i = 1; i < 5; i++) {
        if (x+i >= BOARD_SIZE || y+i >= BOARD_SIZE || board[x+i][y+i] != player) {
            break;
        }
        count++;
    }
    for (int i = 1; i < 5; i++) {
        if (x-i < 0 || y-i < 0 || board[x-i][y-i] != player) {
            break;
        }
        count++;
    }
    if (count >= 5) {
        return true;
    }

    // 检查反斜向
    count = 1;
    for (int i = 1; i < 5; i++) {
        if (x+i >= BOARD_SIZE || y-i < 0 || board[x+i][y-i] != player) {
            break;
        }
        count++;
    }
    for (int i = 1; i < 5; i++) {
        if (x-i < 0 || y+i >= BOARD_SIZE || board[x-i][y+i] != player) {
            break;
        }
        count++;
    }
    if (count >= 5) {
        return true;
    }

    return false;
}

int main() {
    initBoard();

    char player = 'X';
    int x, y;

    while (true) {
        printBoard();

        std::cout << "Player " << player << ": ";
        std::cin >> x >> y;

        if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || board[x][y] != '.') {
            std::cout << "Invalid move, try again." << std::endl;
            continue;
        }

        board[x][y] = player;

        if (checkWin(x, y, player)) {
            printBoard();
            std::cout << "Player " << player << " wins!" << std::endl;
            break;
        }

        player = (player == 'X') ? 'O' : 'X';
    }

    return 0;
}

这段代码实现了一个简单的五子棋游戏,玩家可以轮流下棋,当有玩家连成五子时游戏结束并宣布胜利。您可以在此基础上进行更多的扩展和优化。

0