核心思想就是,雷的分布看作是“答案”,落子的棋盘看作是“考卷”; 答卷的同时,需要去对一下“答案”,这个位置有没有雷,有则BOOM!无则判断周围9宫格的雷的数量,返回这个字符打印至“考卷”上! 同时,为了防止数组越界,保证每一个格子都有九宫格,需要在行与列均多加2; 最后,判断输赢的标准:总格子数量-雷数 = 落子次数,即可判定胜利!
下面为测试模块:
#include"game.h"
void meau() {
printf("****************************\n");
printf("********* 1.play ***********\n");
printf("********* 0.exit ***********\n");
printf("****************************\n");
}
void game() {
char mine[ROWS][COLS] = { 0 };
char show[ROWS][COLS] = { 0 };
Initboard(mine,ROWS,COLS,'0');
Initboard(show, ROWS, COLS,'*');
DisplayBoard(show, ROW, COL);
setboom(mine , ROW , COL);
FindBoom(mine,show,ROW,COL);
}
void main() {
int input = 0;
srand((unsigned int)time(NULL));
do
{
meau();
printf("请选择:\n");
scanf("%d",&input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误,重新输入");
break;
}
} while (input);
}
下面为游戏头文件模块
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ROW 9
#define COL 9
#define COUNT 80
#define ROWS ROW+2
#define COLS COL+2
void Initboard(char board[ROWS][COLS], int rows, int cols,char set);
void DisplayBoard(char board[ROWS][COLS], int rows, int cols);
void setboom(char board[ROWS][COLS], int row, int col);
void FindBoom(char mine[ROWS][COLS], char show[ROWS][COLS], int row ,int col);
下面是游戏程序模块
#include"game.h"
void Initboard(char board[ROWS][COLS], int rows, int cols, char set) {
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++) {
board[i][j] = set;
}
}
}
void DisplayBoard(char board[ROWS][COLS], int row, int col) {
printf("--------------------\n");
for (int i = 0; i <= col; i++)
{
printf("%d ", i);
}
printf("\n");
for (int i = 1; i <= row; i++)
{
printf("%d ",i);
for (int j = 1; j <= col; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
printf("--------------------\n");
}
void setboom(char board[ROWS][COLS], int row, int col) {
printf("雷区分布\n");
int x = 0;
int y = 0;
int count = COUNT;
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (board[x][y] != '1')
{
board[x][y] = '1';
count--;
}
}
}
int GetCount(char mine[ROWS][COLS],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 (mine[i][j] == '1') {
count++;
}
}
}
return count;
}
void FindBoom(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col) {
int x = 0;
int y = 0;
int count = 0;
int win = 0;
while (win < row*col - COUNT) {
printf("请输入要排查的坐标:->\n");
scanf("%d%d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col) {
if (mine[x][y] == '1') {
printf("你被BOOM BOOM BOOM了\n");
DisplayBoard(mine, ROW, COL);
break;
}
else {
count = GetCount(mine,x,y);
show[x][y] = count + '0';
DisplayBoard(show,ROW,COL);
win++;
}
}
else {
printf("坐标非法,重新输入");
}
}
if (win == row * col - COUNT) {
printf("排雷成功\n");
}
}
总结:扫雷游戏将二维数组运用凌厉精致,需要再多练习几次,将这种数组传参,数组操作,数组思维,数组与数组间的联动的思维 融入日常操作;
|