game.c
#include<stdio.h>
#include"game.h"
void Initarr(char arr[ROWS][COLS], int row, int col, char set)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
arr[i][j] = set;
}
}
}
void DisplayArr(char arr[ROWS][COLS], int row, int col)
{
printf("---------扫雷--------\n");
for (int i = 0; i <= row; 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 ", arr[i][j]);
}
printf("\n");
}
printf("---------扫雷--------\n");
}
void AddMine(char arr[ROWS][COLS], int row, int col)
{
int count = easy_mode;
while (count)
{
int x = rand() % row + 1;
int y = rand() % row + 1;
if (arr[x][y] == '0')
{
arr[x][y] = '1';
count--;
}
}
}
static int get_mine(char mine[ROWS][COLS], int x, int y)
{
return mine[x][y + 1] +
mine[x][y - 1] +
mine[x + 1][y + 1] +
mine[x + 1][y] +
mine[x + 1][y - 1] +
mine[x - 1][y + 1] +
mine[x - 1][y] +
mine[x - 1][y - 1] - 8 * '0';
}
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
//输入
//踩到雷——展示mine棋盘——游戏结束
//没踩到雷——显示周围有几个雷——记录到show棋盘里面——游戏继续
int win = 0;
while (win < row * col - easy_mode)
{
int x = 0;
int y = 0;
printf("请输入坐标:\n");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= 9 && y >= 1 && y <= 9)
{
if (mine[x][y] == '1')
{
printf("游戏结束\n");
break;
}
else
{
int count = get_mine(mine, x, y);
show[x][y] = count + '0';
win++;
//DisplayArr(show, ROW, COL);
DisplayArr(show, row, col);
}
}
else
{
printf("输入错误,请重新输入\n");
}
}
if (win = row * col - easy_mode)
{
printf("游戏胜利\n");
}
}
game.h
#pragma once
#include<stdlib.h>
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define easy_mode 80
void Initarr(char arr[ROWS][COLS], int row, int col, char set);
void DisplayArr(char arr[ROWS][COLS], int row, int col);
void AddMine(char arr[ROWS][COLS], int row, int col);
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
test.c
#include<stdio.h>
#include"game.h"
void game();
void manu();
int main()
{
srand(time(NULL));
int input = 0;
do
{
manu();
printf("请选择\n");
scanf("%d", &input);
switch (input)
{
case 1:
printf("扫雷\n");
game();
break;
case 2:
printf("退出\n");
break;
default:
printf("输入错误,请重新输入:\n");
break;
}
} while (input);
return 0;
}
void manu()
{
printf("*************************\n");
printf("***** 1.玩游戏 *****\n");
printf("***** 0.退出 *****\n");
printf("*************************\n");
}
void game()
{
char mine[ROWS][COLS];
char show[ROWS][COLS];
//初始化
Initarr(mine, ROWS, COLS, '0');
Initarr(show, ROWS, COLS, '*');
//展示
//DisplayArr(mine, ROW, COL);
DisplayArr(show, ROW, COL);
//布置雷
AddMine(mine, ROW, COL);
//开挂时打开:DisplayArr(mine, ROW, COL);
//排查雷
FindMine(mine, show, ROW, COL);
}