#include<graphics.h>
#include<stdio.h>
#include<conio.h>
#include<mmsystem.h>
#pragma comment(lib,"WINMM.lib")
struct
{
int x, y;//人物坐标
int _x, _y;//目的地坐标
int dir;//人物移动方向
/*
0 下 ,1 左 2,右 3,下
4 左下 5 右下 6,左上 7 右上
*/
int num;//人物动作
}person = {0,0,250,250,2,1};
IMAGE people[3];//图片 背景图 人物图 掩码图
void init()
{
initgraph(640, 480);
mciSendString(L"open 123.mp3 alias bgm", 0, 0, 0);
//播放mp3格式的音乐
mciSendString(L"play bgm", 0, 0, 0);
IMAGE img;
loadimage(&people[0], L"背景.jpg", 640, 480);
loadimage(&people[1], L"人物图.bmp");//不加后两个数据就是,以图片像素加载
loadimage(&people[2], L"掩码图.bmp");
}
void draw()
{
BeginBatchDraw();
putimage(0, 0, &people[0]);
//贴掩码图
putimage(person.x, person.y, 70, 124, &people[2], 70 * person.num, 124 * person.dir, SRCAND);
putimage(person.x, person.y, 70, 124, &people[1], 70 * person.num, 124 * person.dir,SRCPAINT);
EndBatchDraw();
if (person.num == 3)
{
person.num = 0;
}
else
{
person.num++;
}
Sleep(10);
}
/*
0 下 ,1 左 2,右 3,上
4 左下 5 右下 6,左上 7 右上
*/
void walk()
{
if (person.x > person._x&&person.y > person._y) { person.x -= 1, person.y -= 1,person.dir=6; return; }//左上方
if (person.x < person._x&&person.y > person._y) { person.x += 1, person.y -= 1, person.dir = 7; return; }//右上方
if (person.x > person._x&&person.y < person._y) { person.x -= 1, person.y += 1, person.dir = 4; return; }//左下方
if (person.x < person._x&&person.y < person._y) { person.x += 1, person.y += 1, person.dir = 5; return; }//右下方
if (person.x > person._x) { person.x -= 1, person.dir = 1; return; }//左
if (person.x < person._x) { person.x += 1, person.dir = 2; return; }//右
if (person.y > person._y) { person.y -= 1, person.dir = 3; return; }//上
if (person.y < person._y) { person.y += 1, person.dir = 0; return; }//下
}
void Changedir()
{
//得到鼠标消息
if (MouseHit())
{
MOUSEMSG msg = GetMouseMsg();
switch (msg.uMsg)
{
case WM_LBUTTONDOWN://左键按下
person._x = msg.x-35;
person._y = msg.y-62;
break;
}
}
}
int main()
{
init();
draw();
while (1)
{
Changedir();
walk();
draw();
}
getchar();
closegraph();
system("pause");
return 0;
}
运行效果