欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > c语言实战-极简扫雷

c语言实战-极简扫雷

2025/4/19 9:26:59 来源:https://blog.csdn.net/FENGCHEN____/article/details/140294888  浏览:    关键词:c语言实战-极简扫雷

C语言/c++写的C语言实战项目扫雷

结构比较清晰,仅供参考:

核心是扫雷的递归算法实现

上代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>#define SIZE 10
#define MINES 15char board[SIZE][SIZE]; // 游戏棋盘// 初始化棋盘,'-'表示未揭示的区域
void initBoard() {for (int i = 0; i < SIZE; ++i) {for (int j = 0; j < SIZE; ++j) {board[i][j] = '-';}}
}// 在棋盘上显示当前状态
void displayBoard() {printf("   ");for (int i = 0; i < SIZE; ++i) {printf("%d ", i);}printf("\n");for (int i = 0; i < SIZE; ++i) {printf("%d  ", i);for (int j = 0; j < SIZE; ++j) {printf("%c ", board[i][j]);}printf("\n");}
}// 随机布置地雷
void placeMines() {srand(time(NULL));int count = 0;while (count < MINES) {int x = rand() % SIZE;int y = rand() % SIZE;if (board[x][y] != '*') {board[x][y] = '*';count++;}}
}// 检查坐标是否有效
int isValid(int x, int y) {return (x >= 0 && x < SIZE && y >= 0 && y < SIZE);
}// 计算周围的地雷数量
int countAdjacentMines(int x, int y) {int count = 0;for (int i = x - 1; i <= x + 1; ++i) {for (int j = y - 1; j <= y + 1; ++j) {if (isValid(i, j) && board[i][j] == '*') {count++;}}}return count;
}// 揭示某个位置的内容
void reveal(int x, int y) {if (!isValid(x, y)) {return;}if (board[x][y] != '-') {return;}int mines = countAdjacentMines(x, y);if (mines > 0) {board[x][y] = mines + '0';} else {board[x][y] = ' ';for (int i = x - 1; i <= x + 1; ++i) {for (int j = y - 1; j <= y + 1; ++j) {reveal(i, j);}}}
}int main() {int x, y;char action;initBoard();placeMines();do {displayBoard();printf("Enter action (r for reveal, q to quit): ");scanf(" %c", &action);if (action == 'r') {printf("Enter coordinates (x y): ");scanf("%d %d", &x, &y);if (isValid(x, y)) {reveal(x, y);} else {printf("Invalid coordinates!\n");}} else if (action == 'q') {printf("Quitting game.\n");break;} else {printf("Invalid action!\n");}} while (1);return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词