酷代码 AI
菜单

用c++设置在9x9棋盘上有一个x和四个y,x的走法和车相同,吃掉所有的y即可胜利

以下是一个用 C++ 实现的简单程序,模拟在 9x9 棋盘上,`x` 以车的走法吃掉所有 `y` 即可胜利的游戏。 ```cpp #include <iostream> #include <vector> // 定义棋盘大小 const int BOARD_SIZE = 9; // 打印棋盘 void printBoard(const std::vector<std::vector<char>>& board) { for (int i = 0; i < BOARD_SIZE; ++i) { for (int j = 0; j < BOARD_SIZE; ++j) { std::cout << board[i][j] << " "; } std::cout << std::endl; } } // 检查是否所有的 y 都被吃掉 bool allYAreEaten(const std::vector<std::vector<char>>& board) { for (int i = 0; i < BOARD_SIZE; ++i) { for (int j = 0; j < BOARD_SIZE; ++j) { if (board[i][j] == 'y') { return false; } } } return true; } // 检查移动是否合法 bool isValidMove(const std::vector<std::vector<char>>& board, int fromX, int fromY, int toX, int toY) { // 检查是否在棋盘内 if (toX < 0 || toX >= BOARD_SIZE || toY < 0 || toY >= BOARD_SIZE) { return false; } // 车的走法:只能沿水平或垂直方向移动 if (fromX != toX && fromY != toY) { return false; } // 检查路径上是否有障碍物 if (fromX == toX) { int step = (toY > fromY) ? 1 : -1; for (int y = fromY + step; y != toY; y += step) { if (board[fromX][y] != ' ') { return false; } } } else { int step = (toX > fromX) ? 1 : -1; for (int x = fromX + step; x != toX; x += step) { if (board[x][fromY] != ' ') { return false; } } } return true; } // 移动 x void moveX(std::vector<std::vector<char>>& board, int fromX, int fromY, int toX, int toY) { if (isValidMove(board, fromX, fromY, toX, toY)) { board[toX][toY] = 'x'; board[fromX][fromY] = ' '; if (board[toX][toY] == 'y') { board[toX][toY] = 'x'; } } else { std::cout << "无效的移动,请重新输入。" << std::endl; } } int main() { // 初始化棋盘 std::vector<std::vector<char>> board(BOARD_SIZE, std::vector<char>(BOARD_SIZE, ' ')); // 随机放置 x 和四个 y board[0][0] = 'x'; board[2][3] = 'y'; board[5][7] = 'y'; board[8][1] = 'y'; board[4][4] = 'y'; // 游戏循环 while (!allYAreEaten(board)) { printBoard(board); int fromX, fromY, toX, toY; std::cout << "请输入 x 的当前位置 (行 列): "; std::cin >> fromX >> fromY; std::cout << "请输入 x 的目标位置 (行 列): "; std::cin >> toX >> toY; moveX(board, fromX, fromY, toX, toY); } std::cout << "恭喜你,你胜利了!所有的 y 都被吃掉了。" << std::endl; return 0; } ``` 代码说明: 1. 棋盘初始化:使用二维向量 `board` 表示 9x9 的棋盘,初始时在随机位置放置一个 `x` 和四个 `y`。 2. 打印棋盘:`printBoard` 函数用于打印当前棋盘的状态。 3. 检查胜利条件:`allYAreEaten` 函数检查棋盘上是否还有 `y`,如果没有则表示胜利。 4. 检查移动合法性:`isValidMove` 函数检查 `x` 的移动是否合法,包括是否在棋盘内、是否符合车的走法以及路径上是否有障碍物。 5. 移动 `x`:`moveX` 函数根据用户输入的当前位置和目标位置移动 `x`,如果移动合法则更新棋盘状态,如果目标位置有 `y` 则将其吃掉。 6. 游戏循环:在 `main` 函数中,使用 `while` 循环不断获取用户输入,直到所有 `y` 都被吃掉为止。 注意事项: - 输入的行和列索引从 0 开始。 - 如果输入的移动不合法,程序会提示用户重新输入。 [2026-01-18 08:12:03 | AI问答 | 1257点数解答]

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