c++五子棋

#include <iostream>

#include <vector>

 

using namespace std;

 

const int BOARD_SIZE = 15;

const char EMPTY = '-';

const char BLACK = 'X';

const char WHITE = 'O';

 

vector<vector<char> > board(BOARD_SIZE, vector<char>(BOARD_SIZE, EMPTY));

 

bool isValidMove(int row, int col) {

    return (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && board[row][col] == EMPTY);

}

 

bool checkWin(int row, int col, char player) {

    int directions[4][2] = {{1, 0}, {0, 1}, {1, 1}, {-1, 1}};

    for (int i = 0; i < 4; i++) {

        int count = 1;

        int dx = directions[i][0], dy = directions[i][1];

        int r = row + dx, c = col + dy;

        while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] == player) {

            count++;

            r += dx;

            c += dy;

        }

        dx = -dx, dy = -dy;

        r = row + dx, c = col + dy;

        while (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] == player) {

            count++;

            r += dx;

            c += dy;

        }

        if (count >= 5)

            return true;

    }

    return false;

}

 

void printBoard() {

    for (int i = 0; i < BOARD_SIZE; i++) {

        for (int j = 0; j < BOARD_SIZE; j++) {

            cout << board[i][j] << " ";

        }

        cout << endl;

    }

    cout << endl;

}

 

bool isBoardFull() {

    for (int i = 0; i < BOARD_SIZE; i++) {

        for (int j = 0; j < BOARD_SIZE; j++) {

            if (board[i][j] == EMPTY)

                return false;

        }

    }

    return true;

}

 

int main() {

    int row, col;

    char currentPlayer = BLACK;

 

    while (true) {

        printBoard();

 

        cout << "Player " << currentPlayer << ", enter your move (row col): ";

        cin >> row >> col;

 

        if (!isValidMove(row, col)) {

            cout << "Invalid move! Try again." << endl;

            continue;

        }

 

        board[row][col] = currentPlayer;

 

        if (checkWin(row, col, currentPlayer)) {

            cout << "Player " << currentPlayer << " wins!" << endl;

            break;

        } else if (isBoardFull()) {

            cout << "It's a draw!" << endl;

            break;

        }

 

        currentPlayer = (currentPlayer == BLACK) ? WHITE : BLACK;

    }

 

    printBoard();

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值