帮我用c++写一个五子棋
好的,下面是一个简单的五子棋的C++代码示例:
#include <iostream>
#include <vector>
const int SIZE = 15; // 棋盘大小
enum Player {
NONE,
BLACK,
WHITE
};
class Gomoku {
private:
std::vector<std::vector<Player>> board; // 棋盘
Player currentPlayer; // 当前玩家
public:
Gomoku() {
// 初始化棋盘
board.resize(SIZE, std::vector<Player>(SIZE, NONE));
currentPlayer = BLACK;
}
// 下棋
void makeMove(int row, int col) {
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != NONE) {
std::cout << "Invalid move!" << std::endl;
return;
}
board[row][col] = currentPlayer;
std::cout << "Player " << currentPlayer << " placed a stone at (" << row << ", " << col << ")." << std::endl;
// 检查是否有五子连珠
if (checkWin(row, col)) {
std::cout << "Player " << currentPlayer << " wins!" << std::endl;
return;
}
// 切换玩家
currentPlayer = (currentPlayer == BLACK) ? WHITE : BLACK;
}
// 检查是否有五子连珠
bool checkWin(int row, int col) {
Player player = board[row][col];
// 水平方向
int count = 1;
int r = row, c = col;
while (--c >= 0 && board[r][c] == player) {
count++;
}
c = col;
while (++c < SIZE && board[r][c] == player) {
count++;
}
if (count >= 5) {
return true;
}
// 垂直方向
count = 1;
r = row, c = col;
while (--r >= 0 && board[r][c] == player) {
count++;
}
r = row;
while (++r < SIZE && board[r][c] == player) {
count++;
}
if (count >= 5) {
return true;
}
// 左斜方向
count = 1;
r = row, c = col;
while (--r >= 0 && --c >= 0 && board[r][c] == player) {
count++;
}
r = row, c = col;
while (++r < SIZE && ++c < SIZE && board[r][c] == player) {
count++;
}
if (count >= 5) {
return true;
}
// 右斜方向
count = 1;
r = row, c = col;
while (--r >= 0 && ++c < SIZE && board[r][c] == player) {
count++;
}
r = row, c = col;
while (++r < SIZE && --c >= 0 && board[r][c] == player) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
// 打印棋盘
void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
std::cout << board[i][j] << " ";
}
std::cout << std::endl;
}
}
};
int main() {
Gomoku game;
int row, col;
while (true) {
game.printBoard();
std::cout << "Player " << game.getCurrentPlayer() << ", make your move (row col): ";
std::cin >> row >> col;
game.makeMove(row, col);
}
return 0;
}
这是一个简单的五子棋实现,支持两个玩家交替下棋,检查输赢并打印棋盘。你可以根据需要进行修改和扩展
原文地址: https://www.cveoy.top/t/topic/h8Yq 著作权归作者所有。请勿转载和采集!