利用C语言编写扫雷游戏
这个扫雷游戏没有设置玩家第一个扫雷的坐标一定不是雷
思路:
1.要定义两个数组,一个用来显示棋盘,一个用来储存棋盘的布局信息
2.如果设计一个9✖9的扫雷游戏,就需要定义一个11✖11的数组,这样才方便判断边界所显示的周围雷的个数
3.利用随机函数埋雷,每一次扫雷操作都要进行判定,来实现对玩家输赢的判断
Utili.h
#ifndef _UTILI_H_
#define _UTILI_H_
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#endif /* _UTILI_H_ */
Game.h
#ifndef _GAME_H_
#define _GAME_H_
#include"Utili.h"
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define EASY_COUNT 10
void InitBoard(char board[ROWS][COLS], int row, int col, char set);
void DisplayBoard(char board[ROWS][COLS], 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 FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col);
void StartGame();
#endif /* _GAME_H_ */
Game.c
#include"Game.h"
void InitBoard(char board[ROWS][COLS], int row, int col, char set)
{
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
board[i][j] = set;
}
}
}
void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
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");
}
}
void SetMine(char mine[ROWS][COLS], int row, int col)
{
int count = EASY_COUNT;
srand(time(0));
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (mine[x][y] == '0')
{
mine[x][y] = '1';
count--;
}
}
}
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 FindMine(char mine[ROWS][COLS], char show[ROWS][COLS],int row, int col)
{
int win = 0;
int x, y;
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')
{
DisplayBoard(mine, ROW, COL);
printf("游戏结束,你输了\n");
break;
}
int n = GetMineCount(mine, x, y);
show[x][y] = n + '0';
system("cls");
DisplayBoard(show, ROW, COL);
win++;
}
else
{
printf("输入错误,请重新输入\n");
}
}
if (win >= row * col - EASY_COUNT)
{
printf("游戏结束,你赢了\n");
DisplayBoard(mine, ROW, COL);
}
}
void StartGame()
{
char mine[ROWS][COLS];
char show[ROWS][COLS];
//初始化棋盘
InitBoard(mine, ROWS, COLS, '0');
InitBoard(show, ROWS, COLS, '*');
//埋雷
SetMine(mine, ROW, COL);
//展示雷区
DisplayBoard(show, ROW, COL);
//扫雷
FindMine(mine, show, ROW, COL);
}
MineMain.c
#include"Game.h"
int main(int argc, char* argv[])
{
int select = 1;
while (select)
{
printf("************************\n");
printf("* 1.play *\n");
printf("* 0.exit *\n");
printf("************************\n");
printf("请选择:>");
scanf("%d", &select);
if (select == 0)
break;
if (select != 1)
{
printf("输入错误,请重新输入\n");
continue;
}
StartGame();
}
printf("再见\n");
return 0;
}