c语言实战-极简扫雷
C语言/c++写的C语言实战项目扫雷
结构比较清晰,仅供参考:
核心是扫雷的递归算法实现
上代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define MINES 15
char 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;
}
原文地址:https://blog.csdn.net/FENGCHEN____/article/details/140294888
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!