代码有三部分组成,游戏测试程序test.cpp,游戏代码game.cpp,头文件game.h,可以通过控制变量BombCount来控制雷的数量,代码自己刚开始练习不久,只供自己参考。
test.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "game.h"
void menu()
{
printf("****************************\n");
printf("*** 1.play 0.exit*****\n");
printf("****************************\n");
}
void game()
{
srand((unsigned)time(NULL));
char Bomb[ROWS][COLS] = {0};
char ShowBomb[ROWS][COLS] = { 0 };
Initboard(Bomb, ROWS, COLS,'0');
Initboard(ShowBomb, ROWS, COLS,'*');
SetBomb(Bomb, ROW, COL);
DisplayBoard(ShowBomb, ROW, COL);
DisplayBoard(Bomb, ROW, COL);
Minesweeper(Bomb, ShowBomb, ROW, COL);
}
void test()
{
int input = 0;
do
{
menu();//执行游戏菜单
printf("请输入数字\n"); scanf("%d", &input);
switch (input)
{
case 1:
printf("开始游戏\n");
game();//执行游戏主程序
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输错了!请重新输入!\n");
break;
}
} while (input);
}
int main()
{
test();
return 0;
}
game.h
#define ROW 9
#define COL 9
#define ROWS ROW+2
#define COLS COL+2
#define BombCount 10
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
void Initboard(char Board[ROWS][COLS], int rows, int cols,char ret);
void DisplayBoard(char Board[ROWS][COLS], int row, int col);
void SetBomb(char Board[ROWS][COLS], int row, int col);
void Minesweeper(char Board[ROWS][COLS], char ShowBomb[ROWS][COLS], int row, int col);
int ShowCount(char Board[ROWS][COLS], int x, int y);
game.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "game.h"
void Initboard(char Board[ROWS][COLS], int rows, int cols, char ret)
{
int i = 0, j = 0;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
Board[i][j] = ret;
}
}
}
void DisplayBoard(char Board[ROWS][COLS], int row, int col)
{
int i = 0, j = 0;
for (i = 0; i <=row; 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 SetBomb(char Board[ROWS][COLS], int row, int col)
{
int count=BombCount;
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (Board[x][y] == '0')
{
Board[x][y] = '1';
count--;
}
}
}
int ShowCount(char Board[ROWS][COLS], int x, int y)
{
int count=0,i=0,j=0;
for (i=0; i<3;i++)
{
for (j=0;j<3 ;j++)
{
count+=(Board[x-1+i][y-1+j]-'0');
}
}
return count;
}
void Minesweeper(char Board[ROWS][COLS],char ShowBomb[ROWS][COLS], int row, int col)
{
int x = 0, y = 0, count = 0, win = 0;
while (win<row*col-BombCount)
{
printf("请输入坐标");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)
{
if (Board[x][y] == '1')
{
printf("你被炸死了\n");
DisplayBoard(Board,row,col);
break;
}
else
{
count=ShowCount(Board, x, y);
printf("周围有%d个雷\n",count);
ShowBomb[x][y] = count + '0';
DisplayBoard(ShowBomb, ROW, COL);
win++;
}
}
else
{
printf("坐标输入错误,请重新输入\n");
}
if (win == row * col - BombCount)
{
printf("恭喜你,已经排除所有地雷\n");
}
}
}