C++ 五子棋游戏代码示例 - 完整实现
#include
const int SIZE = 15; // 棋盘大小
enum class Player { None, Black, White };
// 棋盘类
class Board {
public:
Board() : board(SIZE, std::vector
// 打印棋盘
void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
switch (board[i][j]) {
case Player::None:
std::cout << "\.";
break;
case Player::Black:
std::cout << "X";
break;
case Player::White:
std::cout << "O";
break;
}
}
std::cout << std::endl;
}
}
// 判断某个位置是否合法
bool isValidMove(int row, int col) {
return row >= 0 && row < SIZE && col >= 0 && col < SIZE && board[row][col] == Player::None;
}
// 下棋
void makeMove(int row, int col, Player player) {
board[row][col] = player;
}
// 判断是否有玩家获胜
bool checkWin(Player player) {
// 横向
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j <= SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 纵向
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j <= SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[j + k][i] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 斜向(左上到右下)
for (int i = 0; i <= SIZE - 5; i++) {
for (int j = 0; j <= SIZE - 5; j++) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
// 斜向(右上到左下)
for (int i = 0; i <= SIZE - 5; i++) {
for (int j = SIZE - 1; j >= 4; j--) {
bool win = true;
for (int k = 0; k < 5; k++) {
if (board[i + k][j - k] != player) {
win = false;
break;
}
}
if (win) {
return true;
}
}
}
return false;
}
private:
std::vector<std::vector
int main() { Board board; Player currentPlayer = Player::Black;
int row, col;
while (true) {
std::cout << "当前玩家: " << (currentPlayer == Player::Black ? "黑棋(X)" : "白棋(O)") << std::endl;
board.printBoard();
std::cout << "请输入行和列(0-" << SIZE - 1 << "): ";
std::cin >> row >> col;
if (!board.isValidMove(row, col)) {
std::cout << "无效的位置,请重新选择!" << std::endl;
continue;
}
board.makeMove(row, col, currentPlayer);
if (board.checkWin(currentPlayer)) {
std::cout << "玩家 " << (currentPlayer == Player::Black ? "黑棋(X)" : "白棋(O)") << " 获胜!" << std::endl;
break;
}
currentPlayer = (currentPlayer == Player::Black ? Player::White : Player::Black);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/pLSy 著作权归作者所有。请勿转载和采集!