用C++写出一款详细五子棋游戏
时间: 2024-09-08 22:03:28 浏览: 62
编写一个详细的五子棋游戏涉及到多个方面,包括游戏逻辑、界面设计、用户交互等。在这里,我将提供一个简化版的五子棋游戏的C++代码框架,它将包括基本的游戏逻辑和简单的文本界面。请注意,这个示例不包括AI对战,只支持两名玩家轮流进行游戏。
```cpp
#include <iostream>
#include <vector>
const int kBoardSize = 15; // 定义棋盘大小
enum class Player { kNone, kPlayer1, kPlayer2 };
// 打印棋盘的函数
void PrintBoard(const std::vector<std::vector<Player>>& board) {
std::cout << " ";
for (int i = 0; i < kBoardSize; ++i) {
std::cout << (i < 10 ? " " : "") << i << " ";
}
std::cout << std::endl;
for (int i = 0; i < kBoardSize; ++i) {
std::cout << (i < 10 ? " " : "") << i << " ";
for (int j = 0; j < kBoardSize; ++j) {
if (board[i][j] == Player::kNone) {
std::cout << ". ";
} else if (board[i][j] == Player::kPlayer1) {
std::cout << "X ";
} else {
std::cout << "O ";
}
}
std::cout << std::endl;
}
}
// 检查胜利条件的函数
bool CheckWin(const std::vector<std::vector<Player>>& board, Player player) {
// 检查行、列、两个对角线
for (int i = 0; i < kBoardSize; ++i) {
for (int j = 0; j < kBoardSize; ++j) {
// 检查横向
if (j <= kBoardSize - 5 &&
board[i][j] == player && board[i][j + 1] == player && board[i][j + 2] == player &&
board[i][j + 3] == player && board[i][j + 4] == player) {
return true;
}
// 检查纵向
if (i <= kBoardSize - 5 &&
board[i][j] == player && board[i + 1][j] == player && board[i + 2][j] == player &&
board[i + 3][j] == player && board[i + 4][j] == player) {
return true;
}
// 检查对角线
if (i <= kBoardSize - 5 && j <= kBoardSize - 5 &&
board[i][j] == player && board[i + 1][j + 1] == player && board[i + 2][j + 2] == player &&
board[i + 3][j + 3] == player && board[i + 4][j + 4] == player) {
return true;
}
// 检查反对角线
if (i >= 4 && j <= kBoardSize - 5 &&
board[i][j] == player && board[i - 1][j + 1] == player && board[i - 2][j + 2] == player &&
board[i - 3][j + 3] == player && board[i - 4][j + 4] == player) {
return true;
}
}
}
return false;
}
int main() {
std::vector<std::vector<Player>> board(kBoardSize, std::vector<Player>(kBoardSize, Player::kNone));
Player currentPlayer = Player::kPlayer1;
int x, y;
bool game_over = false;
while (!game_over) {
PrintBoard(board);
std::cout << "Player " << (currentPlayer == Player::kPlayer1 ? "1" : "2") << " turn. Enter row and column: ";
std::cin >> x >> y;
if (x < 0 || x >= kBoardSize || y < 0 || y >= kBoardSize || board[x][y] != Player::kNone) {
std::cout << "Invalid move. Try again." << std::endl;
continue;
}
board[x][y] = currentPlayer;
if (CheckWin(board, currentPlayer)) {
PrintBoard(board);
std::cout << "Player " << (currentPlayer == Player::kPlayer1 ? "1" : "2") << " wins!" << std::endl;
game_over = true;
} else {
currentPlayer = (currentPlayer == Player::kPlayer1) ? Player::kPlayer2 : Player::kPlayer1;
}
}
return 0;
}
```
这段代码提供了一个基本的五子棋游戏,玩家通过文本输入进行游戏,程序会检查每次落子后的胜利条件。当一名玩家连成五子时,程序会宣布胜者并结束游戏。
阅读全文