C语言之路——扫雷C语言实现
引言
进来学习了使用C语言实现扫雷游戏,今天写博客来纪念一下
初步框架
void menu(){
printf("**********************
");
printf("********1.play********
");
printf("********0.exit********
");
printf("**********************
");
}
void game() {
char mine[ROWS][COLS] = {
0 };
char show[ROWS][COLS] = {
0 };
//初始化棋盘
unitBoard(mine, ROWS, COLS, 0);
unitBoard(show, ROWS, COLS, *);
//设置棋盘,布置雷
setMine(mine, ROW, COL, SET_EASY);
//展示棋盘
showBoard(mine,ROW,COL);
showBoard(show, ROW, COL);
//排雷
countMine(mine, show, ROW, COL);
}
void test() {
int i = 1;
srand((unsigned int)time(NULL));
do {
menu();
printf("请选择:");
scanf("%d",&i);
switch (i) {
case 0:
printf("退出
");
break;
case 1:
game();
break;
default:
printf("选择错误
");
break;
}
}while(i);
}
int main() {
test();
return 0;
}
这是test.c文件的全部代码,但是大部分工程都是在game.c和game.h中实现的,game.c和game.h都是服务于test.c的。
函数的实现
#include "game.h"
void unitBoard(char board[ROWS][COLS], int rows, int cols, char set) {
int i = 0;
int j = 0;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
board[i][j] = set;
}
}
}
void showBoard(char board[ROWS][COLS], int row, int col) {
int i = 1;
int j = 1;
int k = 0;
for (k = 0; k < col; k++) {
printf("%d ",k);
}
printf("%d
", k);
for (i = 1; i <= row; i++) {
printf("%d ",i);
for (j = 1; j < col; j++) {
printf("%c ",board[i][j]);
}
printf("%c
", board[i][j]);
}
}
void setMine(char mine[ROWS][COLS], int row, int col, int number) {
int count = number;
while(count) {
int x = rand() % row + 1;
int y = rand() % col + 1;
if (mine[x][y] == 0) {
mine[x][y] = 1;
count--;
}
}
}
void countMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col) {
int x = 0;
int y = 0;
int n = 0;
while (n<ROW*COL- SET_EASY) {
printf("请输入坐标:");
scanf("%d %d", &x, &y);
if (x > 0 && x <= row && y > 0 && y <= col) {
if (mine[x][y] == 0) {
show[x][y] = count(mine, x, y) + 0;
showBoard(show, ROW, COL);
n++;
}
else {
printf("很遗憾,你被炸死了
");
showBoard(show, ROW, COL);
break;
}
}
else {
printf("越界了,请重新输入
");
}
}
if (n == ROW * COL - SET_EASY) {
printf("排雷成功
");
showBoard(show, ROW, COL);
}
}
int count(char mine[ROWS][COLS],int x,int y) {
return mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1] + mine[x][y - 1] + mine[x][y + 1] + mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - 8 * 0;
}
#include <stdio.h> #include <stdlib.h> #include <time.h> #define ROW 9 #define COL 9 #define ROWS ROW+2 #define COLS COL+2 #define SET_EASY 80 void unitBoard(char board[ROWS][COLS], int rows, int cols, char set); void showBoard(char board[ROWS][COLS], int row, int col); void setMine(char mine[ROWS][COLS], int row, int col, int number); void countMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
上面是game.c,下面是game.h,相对而言并不复杂,只不过一步一步构造实现这个功能对于初学者来说并不友好。
可添加功能
还可以实现一些选择难度模式、扩散功能。
下一篇:
QT——程序打包成软件
