#include <Windows.h>
#include <iostream>
const int X=200,Y=50; //程序窗口左上角相对于屏幕的坐标
const int WIDTH=640,HEIGHT=480; // //程序窗口的宽与高
DWORD tPre,tNow; //tPre记录上一次绘图的时间,tNow记录此次准备绘图的时间
int x=0,y=0,vx=3,vy=0,gy=1; //x、y表示物体的初始位置,vx、vy表示速度的变化量,gy表示重力加速度
HDC hdc,mdc,bufdc;
HBITMAP bg,dra;
RECT rect;
void MyPaint(HDC);
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
const std::string szTitle="加速运动";
WNDCLASS winclass={CS_HREDRAW|CS_VREDRAW,WndProc,0,0,hInstance,LoadIcon(NULL,IDI_APPLICATION),
LoadCursor(NULL,IDC_ARROW),(HBRUSH)GetStockObject(WHITE_BRUSH),NULL,szTitle.c_str()};
if(!RegisterClass(&winclass))
return false;
HWND hWnd=CreateWindow(szTitle.c_str(),szTitle.c_str(),WS_OVERLAPPEDWINDOW,X,Y,WIDTH,HEIGHT,
NULL,NULL,winclass.hInstance,NULL);
if(0==hWnd)
return 0;
ShowWindow(hWnd,SW_SHOWDEFAULT);
UpdateWindow(hWnd);
MSG msg;
ZeroMemory(&msg,sizeof(MSG));
while(msg.message!=WM_QUIT)
{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
tNow=GetTickCount();
while(tNow-tPre>=40)
MyPaint(hdc);
}
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
{
HBITMAP bmp;
switch(message)
{
case WM_CREATE:
{
hdc=GetDC(hWnd);
mdc=CreateCompatibleDC(hdc);
bufdc=CreateCompatibleDC(hdc);
bmp=CreateCompatibleBitmap(hdc,WIDTH,HEIGHT);
SelectObject(mdc,bmp);
//加载物体位图
bg=(HBITMAP)LoadImage(NULL,"bg.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
dra=(HBITMAP)LoadImage(NULL,"dra.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
GetClientRect(hWnd,&rect); //取得内部窗口区域大小
}
break;
case WM_KEYDOWN:
{
if(wParam==VK_ESCAPE)
DestroyWindow(hWnd);
}
break;
case WM_DESTROY:
{
DeleteDC(bufdc);
DeleteDC(mdc);
DeleteObject(bg);
DeleteObject(dra);
ReleaseDC(hWnd,hdc);
PostQuitMessage(0);
}
break;
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}
void MyPaint(HDC hdc)
{
//贴背景图
SelectObject(bufdc,bg);
BitBlt(mdc,0,0,WIDTH,HEIGHT,bufdc,0,0,SRCCOPY);
//贴物体图
SelectObject(bufdc,dra);
BitBlt(mdc,x,y,50,50,bufdc,50,0,SRCAND);
BitBlt(mdc,x,y,50,50,bufdc,0,0,SRCPAINT);
BitBlt(hdc,0,0,WIDTH,HEIGHT,mdc,0,0,SRCCOPY);
x+=vx; //计算x轴方向物体坐标
vy+=gy; //计算y轴方向速度分量
y+=vy; //计算y轴方向贴图坐标
if(x<=rect.right)
{
if(y>=rect.bottom-50)
{
y=rect.bottom-50;
vy=-vy-1;
}
}
else
{
x=0;
if(y>=rect.bottom-50)
{
y=rect.bottom-50;
vy=-vy-1;
}
}
tPre=GetTickCount();
}