C/C++项目源码——扫雷游戏
这是我自己写的一个扫雷的小游戏
分享给大家
希能和大家一起进步
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<graphics.h>
/*
课程内容:扫雷游戏
开发环境:vs+easyx C语言
二维数组
*/
#define ROW 10 //定义数组行列
#define COL 10
#define MINE 10 //雷的数量
#define SIZE 50
//全局变量自动初始化为0
int map[ROW][COL];
//保存图片
IMAGE img[12];
int row;
int col;
//初始化数据
void GameInit()
{
//创建窗口
initgraph(ROW * SIZE, COL * SIZE, SHOWCONSOLE);
//设置随机数种子
srand((unsigned)time(NULL));
//数组初始化为0
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
map[i][j] = 0;
}
}
//埋雷,用-1表示雷,要10个雷
for (int i = 0; i < MINE;)
{
int r = rand()%ROW;//0-9
int c = rand()%COL;
if (map[r][c] == 0)//不等于雷的时候,就设置为雷 -1
{
map[r][c] = -1;
i++; //每埋雷成功一次,加一次
}
}
//让雷周围的九宫格都加1(雷除外)
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
if (map[i][j] == -1)//如果是雷
{
for (int m = i - 1; m <= i + 1; m++)
{
for (int n = j - 1; n <= j + 1; n++)
{
//排除雷
if (map[m][n] != -1 && (m >= 0 && m < ROW && n >= 0 && n < COL))
{
map[m][n] ++;
}
}
}
}
}
}
//加载图片
for (int i = 0; i < 12; i++)
{
char file[20] = "";
sprintf(file, "./image/%d.jpg", i);
loadimage(&img[i], file,SIZE,SIZE);
}
//加密格子
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
map[i][j] += 20;
}
}
}
void GameDraw()
{
//绘图 0 1 2 3 4 5 6 7 8 9 10 11 -1
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
if (map[i][j] == -1)
{
putimage(j * SIZE, i * SIZE, &img[9]);
}
else if (map[i][j] >= 0 && map[i][j] <= 8)
{
putimage(j * SIZE, i * SIZE, &img[map[i][j]]);
}
else if (map[i][j] >= 19 && map[i][j] <= 28)
{
putimage(j * SIZE, i * SIZE, &img[10]);
}
else if(map[i][j]>30)
{
putimage(j * SIZE, i * SIZE, &img[11]);
}
}
}
}
void openNull(int row, int col);
//鼠标操作
int Mouse()
{
if (MouseHit())
{
MOUSEMSG msg = GetMouseMsg();
row = msg.y / SIZE;//通过鼠标点击的坐标,求出数组下标
col = msg.x / SIZE;
switch (msg.uMsg)
{
case WM_LBUTTONDOWN://鼠标左键点击
if (map[row][col] > 8)
{
map[row][col] -= 20;
openNull(row, col);
}
break;
case WM_RBUTTONDOWN://鼠标右键点击
if (map[row][col] <= 28 && map[row][col] >= 8)
{
map[row][col] += 20;
}
else
{
map[row][col] -= 20;
}
break;
}
return map[row][col];
}
}
//点击空白格子,打开一篇
void openNull(int row,int col)
{
if (map[row][col] == 0)
{
for (int i = row - 1; i <= row + 1; i++)
{
for (int j = col - 1; j <= col + 1; j++)
{
if ((map[i][j] == 20 || map[i][j] != 19) && map[i][j]>8
&& (i >= 0 && i < ROW && j >= 0 && j < COL))
{
map[i][j] -= 20;
openNull(i, j);
}
}
}
}
}
void show(int arr[][COL])
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
printf("%2d ",arr[i][j]);
}
putchar('n');
}
system("cls");
}
int main()
{
GameInit();
while (1)
{
//show(map);
int isok = Mouse();
GameDraw();
if (isok==-1)//点到雷了
{
int flag=MessageBox(GetHWnd(), "欢迎关注微信公众号:C语言爱好者", "提示", MB_OKCANCEL);
if (flag == IDOK)
{
map[row][col] += 40;//关上雷,并标记
}
else
{
//结束游戏
exit(666);
}
}
}
getchar();
return 0;
}