C语言实现拼图

C语言实现拼图

一、效果图

C语言实现拼图

二、代码

#include <stdio.h>
#include <graphics.h>//需要安装Easyx库
#include <time.h>
int map[4][4] =
{
	0,1,2,3,
	4,5,6,7,
	8,9,10,11,
	12,13,15,14
};

IMAGE pic;//定义图片对象
IMAGE white;

void initMap();
void loadResource();
void drawMap();
int searchI();
int searchJ();
void playGame();
int gameOver();

int main()
{
	srand((unsigned int)time(NULL));//设置随机数种子
	initgraph(800, 800);//初始化绘图环境
	loadResource();
	initMap();
	playGame();
	closegraph();//关闭绘图环境
	return 0;
}

//打乱顺序
void initMap()
{
	int array[15] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14 };
	int length = 15;
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			if (i == 3 && j == 3)
			{
				map[i][j] = 15;
				return;
			}
			int pos = rand() % length;
			map[i][j] = array[pos];
			for (int k = pos; k < length - 1; k++)
			{
				array[k] = array[k + 1];
			}
			length--;
		}
	}
}

//加载资源
void loadResource()
{
	loadimage(&pic, L"1.jpg", 800, 800);//加载图片
	loadimage(&white, L"white.png", 200, 200);
}


void drawMap()
{
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			int x = 200 * j;
			int y = 200 * i;
			if (map[i][j] == 15)
			{
				putimage(x, y, &white);//贴上白色图片
			}
			else
			{
				int xj = map[i][j] % 4;
				int yi = map[i][j] / 4;
				int xx = xj * 200;
				int yy = yi * 200;
				putimage(x, y, 200, 200, &pic, xx, yy);//截取部分图片放在对应位置
			}
		}
	}
}

//寻找白块的行坐标,并返回
int searchI()
{
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			if (map[i][j] == 15)
				return i;
		}
	}
	return -1;
}

//寻找白块的列坐标,并返回
int searchJ()
{
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			if (map[i][j] == 15)
				return j;
		}
	}
	return -1;
}

//玩游戏,点击白块上下左右的图片,并让它们互换位置
void playGame()
{
	while (1)
	{
		drawMap();
		if (gameOver())//判断游戏是否结束,如果结束就弹一个确认的消息框,并结束循环
		{
			MessageBox(NULL, L"GameOver", L"GameOver", MB_OK | MB_SYSTEMMODAL);
			break;
		}
		MOUSEMSG m = GetMouseMsg();//获取鼠标消息
		int i = searchI();
		int j = searchJ();
		int row = 0;
		int col = 0;
		switch (m.uMsg)
		{
		case WM_LBUTTONDOWN:
			col = m.x / 200;
			row = m.y / 200;
			if (row == i + 1 && col == j)
			{
				map[i][j] = map[row][col];
				map[row][col] = 15;
			}
			if (row == i - 1 && col == j)
			{
				map[i][j] = map[row][col];
				map[row][col] = 15;
			}
			if (row == i && col == j + 1)
			{
				map[i][j] = map[row][col];
				map[row][col] = 15;
			}
			if (row == i && col == j - 1)
			{
				map[i][j] = map[row][col];
				map[row][col] = 15;
			}
		}
	}
}

//判断游戏是否结束,就是判断图片是否按顺序排列
int gameOver()
{
	int count = 0;
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			if (map[i][j] != count)
			{
				return 0;
			}
			count++;
		}
	}
	return 1;
}
上一篇:三子棋游戏


下一篇:【万人千题】一些有关矩阵题目的解题报告