#define _CRT_SECURE_NO_WARNINGS 1
#include"game2.h"
void menu()
{
printf("\n");
printf("*****************************************\n");
printf("************ 1.play *************\n");
printf("************ 0.exit *************\n");
printf("*****************************************\n");
}
void test()
{
//随机数
srand((unsigned)time(NULL));
int input = 0;
do
{
menu();
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏");
break;
default:
printf("输入错误请重新输入!");
break;
}
} while (input);
}
int main()
{
test();
return 0;
}
void game()
{
char mine[ROWS][COLS] = { 0 };//存放布置好雷的信息
char show[ROWS][COLS] = { 0 };//存放排查出雷的信息
//初始化 mine 数组为全0,show 数组为全*
InitBoard(mine, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
//布置雷
SetMine(mine, ROW, COL);
//显示棋盘
DisplayBoard(show, ROW, COL);
//排雷
FindMine(mine,show,ROW,COL);
}
#pragma once
//头文件的包含:
#include
#include
#include
//初始化棋盘
void InitBoard(char board[ROWS][COLS], int row, int col,char set);
//打印棋盘
void DisplayBoard(char board[ROW][COL],int row,int col);
//布置雷
void SetMine(char mine[ROW][COL], int row, int col);
//排雷
void FindMine(char mine[ROWS][COLS],char show [ROWS][COLS],int row,int col);
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
这里我们设置 EASY_COUNT 便于修改雷的个数
#define EASY_COUNT 80
#define _CRT_SECURE_NO_WARNINGS 1
#include"game2.h"
void InitBoard(char board[ROWS][COLS], int row, int col, char set)
{
int i = 0;
int j = 0;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; 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--;
}
}
}
这里写的是以玩家选择的坐标为中心,计算周围一圈九个格子中雷的个数
static int get_mine_count(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] +
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
{
//计算x,y坐标周围有几个雷
int n = get_mine_count(mine, x, y);
//根据ascall码表“0”对应48,数字 + 字符 = 码值对应字符
show[x][y] = n + '0';
DisplayBoard(show, row, col);
win++;
}
}
else
{
printf("输入不合法,重新输入!");
}
}
if (win == row * col - EASY_COUNT)
{
printf("恭喜你排雷成功\n");
DisplayBoard(mine, row, col);
}
}