分享扫雷小游戏
实现
头文件如下
#pragma once
#define ROW 9
#define COL 9
#define ROWS ROW + 2
#define COLS COL + 2
#define EASY_count 10
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//初始化雷盘
void Init_board(char board[ROWS][COLS], int rows, int cols, char set);
//打印
void show_board(char board[ROWS][COLS], int row, int col);
//埋雷
void set_mine(char mine[ROWS][COLS], int row, int col);
//找雷
void find_mine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
说明:我们实际在9*9的盘上扫雷,但多加两行是便于周围雷的统计。
(1)初始化
我们采用两个数组,来进行扫雷,一个存放雷的信息,另一个存放排雷情况。
char mine[ROWS][COLS] = { 0 };//埋雷
char show[ROWS][COLS] = { 0 };//排雷信息的显示
//初始化
Init_board(mine, ROWS, COLS, '0');
//打印
//show_board(mine, ROW, COL);
Init_board(show, ROWS, COLS, '*');
我们用‘0’来表示无雷,用‘1’来表示有雷,show数组存放周围雷的个数,show初始化为‘*’
(2)打印
为方便游戏,我们打印出行和列。
void show_board(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");
}
}
(3)随机埋雷
void set_mine(char mine[ROWS][COLS], int row, int col)
{
int count = EASY_count;
int x = 0;
int y = 0;
while (count)
{
x = rand() % 9 + 1;
y = rand() % 9 + 1;
if (mine[x][y] == '0')
{
mine[x][y] = '1';
count--;
}
}
}
采用随机数埋雷,跳过已埋坐标。
(4)找雷(拓展式)
void find(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y)
{
if (x == 0 || y == 0 || x == ROWS - 1 || y == COLS - 1)
return;
if (show[x][y] != '*')
return;
int count = mine_count(mine, x, y);
if (count > 0)
{
show[x][y] = count + '0';
}
if (count == 0)
{
show[x][y] = ' ';
find(mine, show, x - 1, y - 1);
find(mine, show, x - 1, y);
find(mine, show, x - 1, y + 1);
find(mine, show, x, y - 1);
find(mine, show, x, y + 1);
find(mine, show, x + 1, y - 1);
find(mine, show, x + 1, y);
find(mine, show, x + 1, y + 1);
}
}
int is_win(char show[ROWS][COLS], int row, int col)
{
int count = 0;
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < row; j++)
{
if (show[i][j] == '*')
count++;
}
}
if (count == EASY_count)
return 1;
return 0;
}
void find_mine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x = 0;
int y = 0;
while (1)
{
printf("请输入查找坐标->");
scanf("%d%d", &x, &y);
if (mine[x][y] == '0')
{
find(mine, show, x, y);
show_board(show, row, col);
if (is_win(show, row, col))
{
printf("恭喜\n");
}
}
else
{
printf("你死了\n");
break;
}
}
}