目录
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void menu()
{
printf("************************************\n");
printf("********* 1.play ********\n");
printf("********* 0.exit ********\n");
printf("************************************\n");
}
void game()
{
//show数组为排查出的雷的信息
char show[ROWS][COLS] = { 0 };
//mine数组为布置好的雷的信息
char mine[ROWS][COLS] = { 0 };
//初始化棋盘
InitBoard(show, ROWS, COLS, '*');
InitBoard(mine, ROWS, COLS, '0');
//打印棋盘
DisplayBoard(show, ROW, COL);
//布置雷
SetMine(mine, ROW, COL);
//DisplayBoard(mine, ROW, COL);
//排查雷
FineMine(mine, show, ROW, COL);
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误,请重新输入。\n");
break;
}
} while (input);
return 0;
}
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
//初始化棋盘
void InitBoard(char board[ROWS][ROWS], int rows, int cols, char set)
{
memset(&board[0][0], set, rows * cols * sizeof(board[0][0]));
}
//打印棋盘
void DisplayBoard(char board[ROWS][ROWS], int row, int col)
{
printf("****** 扫雷 ******\n");
for (int j = 0; j <= col; j++)
{
printf("%d ", j);
}
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");
}
}
//布置雷
void SetMine(char mine[ROWS][COLS], int row, int col)
{
int cnt = EASY_COUNT;
while (cnt)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (mine[x][y] == '0')
{
mine[x][y] = '1';
cnt--;
}
}
}
//计算周围雷的数量
int GetMineCount(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');
}
//排查雷
void FineMine(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("%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 cnt = GetMineCount(mine, x, y);
show[x][y] = cnt + '0';
DisplayBoard(show, ROW, COL);
win++;
}
}
else
{
printf("坐标输入错误,请重新输入\n");
}
}
if (win == row * col - EASY_COUNT)
{
printf("恭喜你排雷成功!!!\n");
}
}
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//棋盘大小
#define ROW 9
#define COL 9
#define ROWS ROW + 2
#define COLS COL + 2
//雷的个数
#define EASY_COUNT 10
//初始化棋盘
void InitBoard(char board[ROWS][ROWS], int rows, int cols, char set);
//打印棋盘
void DisplayBoard(char board[ROWS][ROWS], int row, int col);
//布置雷
void SetMine(char mine[ROWS][COLS], int row, int col);
//计算周围雷的数量
int GetMineCount(char mine[ROWS][COLS], int x, int y);
//排查雷
void FineMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
代码里的注释感觉已经很清楚啦,就不多讲解啦
感谢各位大佬的支持!!!