跳到正文

剪贴板

剪贴板 h1t60cdj

原文
剪贴板信息

剪贴板信息

收录
更新

五子棋!!!

C++
#include <iostream>
#include <vector>
#include <iomanip>

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() {
    // 打印列号
    cout << "  "; // 对齐行号区域
    for (int j = 0; j < BOARD_SIZE; j++) {
        cout << setw(2) << j << " ";
    }
    cout << endl;

    for (int i = 0; i < BOARD_SIZE; i++) {
        // 打印行号
        cout << setw(2) << 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;
}