您的位置:首页 > 编程语言 > C语言/C++

C语言实现简单的扫雷游戏

2020-04-22 15:23 274 查看

文章目录

1、头文件 game.h

#include<stdio.h>
#include"stdlib.h"
#include"time.h"
#define COL 9
#define ROW 9
#define COLS COL+2
#define ROWS ROW+2
#define EASY_COUNT 10

//初始化扫雷的棋盘
void InitBoard(char board[ROWS][COLS], int rows, int cols,char set);
//打印棋盘
void DisPlayBoard(char board[ROWS][COLS], int row, int col);
//布置雷
void SetMine(char board[ROWS][COLS],int row,int col);
//排查雷
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);

2、游戏主函数 test.c

#include"game.h"

void game(){
//存放布置好的雷的信息
char mine[ROWS][COLS] = { 0 };//0表示没有雷
//存放排查出的信息
char show[ROWS][COLS] = { 0 };//* 表示 没有排查的位置
//初始化
InitBoard(mine, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
//打印棋盘
//DisPlayBoard(mine,ROW,COL);
//DisPlayBoard(show, ROW, COL);
//布置雷
SetMine(mine, ROW, COL);
//DisPlayBoard(mine, ROW, COL);
DisPlayBoard(show, ROW, COL);
//排查雷
FindMine(mine,show, ROW, COL);
}
void menu(){
printf("     (* ̄︶ ̄)     \n");
printf(" *** 1.play ***   \n");
printf("  ** 0.exit **    \n");
printf("     (* ̄︶ ̄)    \n");
}
void test(){
int input = 0;
srand((unsigned int)time(NULL));
do{
menu();
printf("请选择:>");
scanf_s("%d", &input);
switch (input){
case 1:
game();
break;
case 0:
printf("退出游戏!\n");
break;
default:
printf("选择错误!");
}
} while (input);
}

int main(){
test();
return 0;
}

3、函数实现函数 game.c

#include"game.h"

void InitBoard(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 DisPlayBoard(char board[ROWS][COLS], int row, int col){
int i = 0;
int j = 0;
for (i = 0; i <= col; i++){
printf("%d ", i);
}
printf("\n");
for (i = 1; i <= row; i++){
printf("%d ", i);
for (j = 1; j <= col; j++){
printf("%c ",board[i][j]);
}
printf("\n");
}
}

void SetMine(char mine[ROWS][COLS], int row, int col){
int count = EASY_COUNT;
while (count){
int x = rand() % row + 1;
int y = rand() % col + 1;
if (mine[x][y] = '0'){
mine[x][y] = '1';
count--;
}
}
}
int GetMineCount(char mine[ROWS][COLS],int x,int y){
return (mine[x - 1][y] +
mine[x - 1][y - 1] +
mine[x][y - 1] +
mine[x + 1][y - 1] +
mine[x + 1][y + 1] +
mine[x][y + 1] +
mine[x - 1][y + 1] - 8 * '0');
}
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col){
int x = 0;
int y = 0;
int win = 0;
while (win<row * col-EASY_COUNT){
printf("请输入要排查的坐标:>");
scanf_s("%d%d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col){
if (mine[x][y] == '1'){
printf("很遗憾您被炸死了\n");
DisPlayBoard(mine, row, col);
break;
}
else{
int count = GetMineCount(mine,x,y);
show[x][y] = count+'0';
DisPlayBoard(show, row, col);
win++;
}
}
else{
printf("您输入的坐标有误!请重新输入:\n");
}
}
if (win == row*col - EASY_COUNT){
printf("恭喜您排雷成功!\n");
}
}

4、实现说明



  • 点赞
  • 收藏
  • 分享
  • 文章举报
TB81266 发布了27 篇原创文章 · 获赞 2 · 访问量 410 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: