# include<stdio.h>
# include <graphics.h>
# include <mmsystem.h>
# pragma comment(lib,"winmm.lib")
# include <time.h>
# define WND_HEIGHT 630 //窗口的长 ,竖的
# define WND_WIDTH 630 //窗口的宽,横的
# define IMA_HEIGHT 630 //图片的长
# define IMA_WIDTH 630// 图片的宽
# define SIZE 210 //图片大小
# define ROW (IMA_HEIGHT/SIZE)
# define COL (IMA_WIDTH/SIZE)
void GameInit();
void DrawMap();
void GamePlay();
void MixImg();
void GameDone();
IMAGE image;
IMAGE img[ROW*COL];
int arr[ROW][COL];
bool State = false;
int main()
{
mciSendString(_T("open despacito.mp3 alias music"), 0, 0, 0);
mciSendString(TEXT("play music"),0,0,0);
GameInit();
MixImg();
while (1)
{
DrawMap();
GamePlay();
GameDone();
if (State == true)
{
Sleep(5000);
break;
}
}
getchar();
return 0;
}
//初始化游戏
void GameInit()
{
initgraph(WND_HEIGHT, WND_WIDTH);
//char s[] = "开始游戏";
//outtextxy(0,0,s);
loadimage(&image, L"warmbody.jpg", IMA_HEIGHT, IMA_WIDTH);
SetWorkingImage(&image); //这个函数用于设定当前的绘图设备。
int n = 0;
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
getimage(&img[n++], j*SIZE, i*SIZE, SIZE, SIZE);
}
}
SetWorkingImage(NULL); //把窗口设置为当前的绘图工作区
//将最后一块图片换成空格图片
loadimage(&img[ROW*COL - 1], L"blank.jpg", SIZE, SIZE);
n = 0;
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
arr[i][j] = n;
n++;
}
}
}
void DrawMap()
{
for (int i = 0; i <ROW; i++)
{
for (int j = 0; j <COL; j++)
{
putimage(j*SIZE, i*SIZE, &img[arr[i][j]]);
}
}
}
/*
玩游戏:
1、鼠标点击图片;
2、点击与空白相邻的图片时,会和空白图片交换;
*/
void GamePlay()
{
int Blank_i, Blank_j;//空白图片的列,行坐标;
int Mouse_i, Mouse_j;//鼠标的列,行坐标;
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
if (arr[i][j] == ROW*COL - 1)
{
Blank_i = i;
Blank_j = j;
}
}
}
MOUSEMSG msg = { 0 };//定义一个鼠标消息;
msg = GetMouseMsg();
switch (msg.uMsg)
{
case WM_LBUTTONDOWN:
//获取点击图片的坐标;
Mouse_i = msg.y / SIZE;
Mouse_j = msg.x / SIZE;
if (Mouse_i == Blank_i&&Mouse_j == Blank_j - 1 ||
Mouse_i == Blank_i&&Mouse_j == Blank_j + 1 ||
Mouse_j == Blank_j&&Mouse_i == Blank_i - 1 ||
Mouse_j == Blank_j&&Mouse_i == Blank_i + 1
)
{
//交换图片;
/*
int temp;
temp = arr[Blank_i][Blank_j];
arr[Blank_i][Blank_j] = arr[Mouse_i][Mouse_j];
arr[Mouse_i][Mouse_j] = temp;
*/
arr[Blank_i][Blank_j] = arr[Mouse_i][Mouse_j];
arr[Mouse_i][Mouse_j] = ROW*COL - 1;
}
break;
}
}
//打乱图片顺序;
void MixImg()
{
srand((unsigned)time(NULL));
// 0~ROW*COL-1的数;
int a[ROW*COL-1];
int i,j;
srand(time(NULL));
for (i = 0; i<ROW*COL-1; i++)
{
int n = rand() % (ROW*COL-1);
for (j = 0; j<i; j++)
{
if (a[j] == n) {
i--;
break;
}
}
if (j >= i)
a[i] = n;
}
int n=0;
for ( i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
arr[i][j] = a[n];
arr[ROW - 1][COL - 1] = ROW*COL - 1;
n++;
}
}
}
//完成游戏
void GameDone()
{
int i, j;
int n = 0;
int count = 0;
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
if (arr[i][j] == n)
{
count++;
}
n++;
}
}
if (count == ROW*COL)
{
loadimage(&image, L"win.jpg", IMA_HEIGHT, IMA_WIDTH);
putimage(0, 0, &image);
State = true;
}
}