C++代码实现 五子棋
下面是一个简单的C++代码实现五子棋的示例:
#include <iostream>
#include <vector>
using namespace std;
const int SIZE = 15;
enum class ChessPiece { None, Black, White };
class GobangGame {
public:
GobangGame() {
board.resize(SIZE, vector<ChessPiece>(SIZE, ChessPiece::None));
currentPlayer = ChessPiece::Black;
}
void play() {
while (true) {
printBoard();
int row, col;
cout << "Player " << (currentPlayer == ChessPiece::Black ? "Black" : "White") << ", enter your move: ";
cin >> row >> col;
if (isValidMove(row, col)) {
board[row][col] = currentPlayer;
if (isWinningMove(row, col)) {
printBoard();
cout << "Player " << (currentPlayer == ChessPiece::Black ? "Black" : "White") << " wins!" << endl;
break;
}
currentPlayer = (currentPlayer == ChessPiece::Black ? ChessPiece::White : ChessPiece::Black);
} else {
cout << "Invalid move. Try again." << endl;
}
}
}
private:
vector<vector<ChessPiece>> board;
ChessPiece currentPlayer;
bool isValidMove(int row, int col) {
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) {
return false;
}
if (board[row][col] != ChessPiece::None) {
return false;
}
return true;
}
bool isWinningMove(int row, int col) {
int dx[] = {1, 0, 1, 1};
int dy[] = {0, 1, 1, -1};
for (int i = 0; i < 4; i++) {
int count = 1;
for (int j = 1; j < 5; j++) {
int newRow = row + dx[i] * j;
int newCol = col + dy[i] * j;
if (newRow < 0 || newRow >= SIZE || newCol < 0 || newCol >= SIZE || board[newRow][newCol] != currentPlayer) {
break;
}
count++;
}
if (count == 5) {
return true;
}
}
return false;
}
void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
switch (board[i][j]) {
case ChessPiece::None:
cout << ".";
break;
case ChessPiece::Black:
cout << "X";
break;
case ChessPiece::White:
cout << "O";
break;
}
}
cout << endl;
}
}
};
int main() {
GobangGame game;
game.play();
return 0;
}
这个代码实现了一个简单的五子棋游戏。玩家可以通过输入行和列的坐标来下棋,游戏会检查是否有玩家获胜。游戏使用二维向量来表示棋盘,并使用枚举类型ChessPiece来表示棋子。play()方法是游戏的主循环,isValidMove()方法用于检查是否是有效的落子位置,isWinningMove()方法用于检查是否有玩家获胜,printBoard()方法用于打印当前棋盘状态。在main()函数中创建游戏对象并开始游戏
原文地址: https://www.cveoy.top/t/topic/hR6W 著作权归作者所有。请勿转载和采集!