qcode
  • 创作工场专业版,一问多答!更智能、更完整、更原创
  • 这是一个超强内容创作平台,它会写文章、做设计、绘图、敲代码,有问必答!
🔥点击使用-免登录深度版🔥

用c++实现一个扫雷的小游戏

时间2023-08-23 17:35:42 提问来自 江苏省徐州市 的网友 分类创作 浏览256
以下是一个简单的用C语言实现的扫雷小游戏的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 10 #define MINES 10 int board[SIZE][SIZE]; int revealed[SIZE][SIZE]; void initializeBoard() { int i, j; for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { board[i][j] = 0; revealed[i][j] = 0; } } } void placeMines() { int count = 0; while (count < MINES) { int x = rand() % SIZE; int y = rand() % SIZE; if (board[x][y] != -1) { board[x][y] = -1; count++; } } } void calculateNumbers() { int i, j; for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { if (board[i][j] != -1) { int count = 0; if (i > 0 && j > 0 && board[i - 1][j - 1] == -1) count++; if (i > 0 && board[i - 1][j] == -1) count++; if (i > 0 && j < SIZE - 1 && board[i - 1][j + 1] == -1) count++; if (j > 0 && board[i][j - 1] == -1) count++; if (j < SIZE - 1 && board[i][j + 1] == -1) count++; if (i < SIZE - 1 && j > 0 && board[i + 1][j - 1] == -1) count++; if (i < SIZE - 1 && board[i + 1][j] == -1) count++; if (i < SIZE - 1 && j < SIZE - 1 && board[i + 1][j + 1] == -1) count++; board[i][j] = count; } } } } void printBoard() { int i, j; for (i = 0; i < SIZE; i++) { for (j = 0; j < SIZE; j++) { if (revealed[i][j]) { if (board[i][j] == -1) { printf("* "); } else { printf("%d ", board[i][j]); } } else { printf(". "); } } printf(" "); } } void revealCell(int x, int y) { if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) return; if (revealed[x][y]) return; revealed[x][y] = 1; if (board[x][y] == 0) { revealCell(x - 1, y - 1); revealCell(x - 1, y); revealCell(x - 1, y + 1); revealCell(x, y - 1); revealCell(x, y + 1); revealCell(x + 1, y - 1); revealCell(x + 1, y); revealCell(x + 1, y + 1); } } int main() { srand(time(NULL)); initializeBoard(); placeMines(); calculateNumbers(); printBoard(); int x, y; while (1) { printf("Enter the coordinates (x y): "); scanf("%d %d", &x, &y); if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) { printf("Invalid coordinates. Try again. "); continue; } if (revealed[x][y]) { printf("Cell already revealed. Try again. "); continue; } if (board[x][y] == -1) { printf("Game over! You hit a mine. "); break; } revealCell(x, y); printBoard(); } return 0; } ``` 这个示例代码实现了一个10x10的扫雷游戏,其中有10个地雷。玩家通过输入坐标来揭开格子,如果揭开的格子是地雷,则游戏结束;否则,会显示该格子周围的地雷数量。玩家可以不断揭开格子直到游戏结束。 请注意,这只是一个简单的示例代码,可能还有一些功能和优化可以添加。你可以根据自己的需求进行修改和扩展。

不满意?免费深度重写!

免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。

上一篇 四大升级办公室管理服务升级 下一篇 国内江苏佳禾输送设备科技有限公司怎么样?