#include <graphics.h> //easyx图形库的头文件
#include <stdio.h>
#include <time.h>
#define WIN_WIDTH 504
#define BLOCK_W 61
#define BLOCK_H 68
IMAGE imgBlocks[3]; //用来保存各种小方块图片
IMAGE imgBg; //背景图片
int chaowei[7];//0表示空白 n表示第n种图片
int map[3][3]; //0表示空白 n表示第n种图片
//定义一个“二维数组”来表示9个小图块的布局
void initMap() {
//先把数组配置成:
//1 1 1
//2 2 2
//3 3 3
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
map[i][j] = i + 1;
}
}
//再随机打乱任意多次
for (int i = 0; i < 20; i++) {
int k1 = rand() % 3;
int k2 = rand() % 3;
int k3 = rand() % 3;
int k4 = rand() % 3;
int tmp = map[k1][k2];
map[k1][k2] = map[k3][k4];
map[k3][k4] = tmp;
}
}
void gameInit() {
//创建游戏窗口
initgraph(504, 900, 1);//窗口的大小 504 * 900
//绘制游戏背景
loadimage(0, "res/bg1.png");
//把各种小图片文件,加载到图片数组
loadimage(&imgBlocks[0], "res/1.png");
loadimage(&imgBlocks[1], "res/2.png");
loadimage(&imgBlocks[2], "res/3.png");
//配置随机种子
srand(time(NULL));
//初始化地图数组map
initMap();
for (int i = 0; i < 7; i++) {
chaowei[i] = 0;
}
loadimage(&imgBg,"res/bg1.png");
//直接从硬盘加载,把bg1图片放进imgBg
}
void updateWindow() {
int off = 10;
int marginX = (WIN_WIDTH - BLOCK_W * 3 - off * 2) / 2;
int marginY = 270;
BeginBatchDraw(); //开始渲染,把图片渲染到缓存
putimage(0,0,&imgBg);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int x = marginX + j * (BLOCK_W + off);
int y = marginY + i * (BLOCK_H +off);
int index = map[i][j] - 1;
putimage(x, y, &imgBlocks[index]);
}
}
//绘制羊槽中的图块
for (int i = 0; i < 7; i++) {
if (chaowei[i] >= 0) {
int x = 26 + i * (BLOCK_W + 5);
int y = 696;
int index = chaowei[i] - 1;
putimage(x, y, &imgBlocks[index]);
}
}
EndBatchDraw(); //一次性渲染到窗口
}
bool userClick(int *prow,int *pcol) {
ExMessage msg;
if (peekmessage(&msg) && msg.message == WM_LBUTTONDOWN) {
int off = 10;
int marginX = (WIN_WIDTH - BLOCK_W * 3 - off * 2) / 2;
int col=(msg.x - marginX) / (BLOCK_W + off);
int marginY = 270;
int row = (msg.y - marginY) / (BLOCK_H + off);
printf("[%d,%d]\n",row,col);
if (row < 0 || row >= 3 || col < 0 || col >= 3) {
return false;
}
*prow = row;
*pcol = col;
return true;
}
return false;
}
void work(int row, int col) {
//chao[7]
//0 0 0 0 0 0 0
//2 0 0 0 0 0 0
//2 1 0 0 0 0 0
int i = 0;
for (; chaowei[i] && i < 7; i++);
if (i < 7) {
chaowei[i] = map[row][col];
map[row][col] = 0;
}
}
int main() {
gameInit();
while (1){
int row, col;
if (userClick(&row, &col)) {
//把对应的方块放到羊槽里!
work(row,col);
}
updateWindow();
}
system("pause");
return 0;
}
原代码来自--“程序员Rock”