酷代码 AI
菜单
服务商

用c++编写一个文字版围棋游戏

以下是一个简单的文字版围棋游戏的 C++ 实现: ```cpp #include <iostream> #include <vector> #include <cstring> const int BOARD_SIZE = 9; // 围棋棋盘大小,这里设置为 9x9 const char BLACK = 'X'; // 黑子 const char WHITE = 'O'; // 白子 const char EMPTY = '.'; // 空位 // 初始化棋盘 void initializeBoard(std::vector<std::vector<char>>& board) { board.resize(BOARD_SIZE, std::vector<char>(BOARD_SIZE, EMPTY)); } // 打印棋盘 void printBoard(const std::vector<std::vector<char>>& board) { std::cout << " "; for (int i = 0; i < BOARD_SIZE; ++i) { std::cout << i << " "; } std::cout << std::endl; for (int i = 0; i < BOARD_SIZE; ++i) { std::cout << i << " "; for (int j = 0; j < BOARD_SIZE; ++j) { std::cout << board[i][j] << " "; } std::cout << std::endl; } } // 检查落子位置是否合法 bool isValidMove(const std::vector<std::vector<char>>& board, int x, int y, char player) { if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) return false; if (board[x][y] != EMPTY) return false; return true; } // 落子 void makeMove(std::vector<std::vector<char>>& board, int x, int y, char player) { board[x][y] = player; } // 主游戏循环 void playGame() { std::vector<std::vector<char>> board; initializeBoard(board); char currentPlayer = BLACK; while (true) { printBoard(board); std::cout << "当前玩家: " << (currentPlayer == BLACK ? "黑子" : "白子") << std::endl; std::cout << "请输入落子位置 (x y): "; int x, y; std::cin >> x >> y; if (isValidMove(board, x, y, currentPlayer)) { makeMove(board, x, y, currentPlayer); currentPlayer = (currentPlayer == BLACK) ? WHITE : BLACK; } else { std::cout << "非法落子,请重新输入!" << std::endl; } } } int main() { playGame(); return 0; } ``` 代码说明: 1. 初始化棋盘:`initializeBoard` 函数用于创建一个 `BOARD_SIZE x BOARD_SIZE` 的二维向量,并将其所有元素初始化为 `EMPTY` 字符,表示空位。 2. 打印棋盘:`printBoard` 函数将当前的棋盘状态输出到控制台,方便玩家查看。 3. 检查落子合法性:`isValidMove` 函数检查玩家输入的落子位置是否在棋盘范围内,并且该位置是否为空。 4. 落子:`makeMove` 函数将指定位置的棋盘元素设置为当前玩家的棋子。 5. 主游戏循环:`playGame` 函数是游戏的主循环,它不断交替玩家,提示玩家输入落子位置,并检查落子的合法性。 注意事项: - 此代码仅实现了基本的落子功能,没有实现提子、禁入点、打劫等围棋规则。 - 游戏会一直运行,直到用户手动终止程序。 [2025-12-14 15:12:22 | AI问答 | 860点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多