📄 ball.h
字号:
#include <windows.h>
#include <math.h>
TCHAR szAppName[] = TEXT("Bounce");
#define PI 3.14159
#define TWO_PI 2*PI
class MovableObject{
public:
virtual void Draw(HDC hdc) = 0;
virtual void GetUpdateRect(RECT *rc) = 0;
virtual void SetImage(HDC hdc) = 0;
virtual ~MovableObject(){DeleteObject(_image);}
void Move();
void SetDirection(double direction)
{_direction = direction;}
void SetSpeed(LONG x,LONG y)
{_speed.x = x;_speed.y = y;}
void SetPosition(LONG x,LONG y)
{_position.x = x;_position.y = y;}
void GetPostion(POINT &pos)
{pos = _position;}
//protected:
protected:
POINT _speed;
/*Distance object can move in x and y direction
every time interval*/
HBITMAP _image;
POINT _position;
double _direction; //in arc
};
void MovableObject::Move(){
_position.x += _speed.x;
_position.y += _speed.y;
}
class Ball : public MovableObject{
public:
~Ball(){DeleteObject(_image);}
void SetColor(COLORREF color)
{_color = color;}
void Draw(HDC hdc);
void SetRadius(UINT radius)
{_radius = radius;}
void GetUpdateRect(RECT *rc);
void CheckCollide(Ball &ball2);
void AdjustSpeed(UINT cxClient, UINT cyClient);
void SetImage(HDC hdc);
private:
UINT _radius;
COLORREF _color;
};
void Ball::SetImage(HDC hdc){
HDC hdcMem = CreateCompatibleDC(hdc);
_image = CreateCompatibleBitmap(hdc,2*_radius,2*_radius);
SelectObject(hdcMem, _image);
Rectangle(hdcMem,-1,-1,2*_radius+1,2*_radius+1);
HBRUSH hBrush = CreateSolidBrush(_color);
hBrush = (HBRUSH)SelectObject(hdcMem,hBrush);
SetBkColor(hdcMem,RGB(0,0,0));
SelectObject(hdcMem,GetStockObject(NULL_PEN));
Ellipse(hdcMem,0,0,2*_radius,2*_radius);
DeleteObject(SelectObject(hdcMem,hBrush));
DeleteDC(hdcMem);
}
void Ball::Draw(HDC hdc){
HDC hdcMem = CreateCompatibleDC(hdc);
SelectObject(hdcMem,_image);
BitBlt(hdc,_position.x-_radius,_position.y-_radius,
2*_radius,2*_radius,hdcMem,0,0,SRCCOPY);
DeleteDC(hdcMem);
}
void Ball::GetUpdateRect(RECT *rc){
rc->left = _position.x-_radius;
rc->top = _position.y-_radius;
rc->right = _position.x+_radius;
rc->bottom = _position.y+_radius;
}
void Ball::CheckCollide(Ball &ball2){
UINT distance = sqrt(pow((_position.x-ball2._position.x),2)+
pow((_position.y-ball2._position.y),2));
if(distance <= _radius+ball2._radius){
//exchange speed
POINT speed_tmp;
speed_tmp.x = _speed.x;
speed_tmp.y = _speed.y;
_speed.x = ball2._speed.x;
_speed.y = ball2._speed.y;
ball2._speed.x = speed_tmp.x;
ball2._speed.y = speed_tmp.y;
}
}
void Ball::AdjustSpeed(UINT cxClient, UINT cyClient){
//adjust speed for specified ball to keep it in the client area
if(_position.x+_radius>=cxClient ||
int(_position.x-_radius)<=0){
_speed.x = -_speed.x;
_position.x = min(cxClient-_radius,
max(_radius,(int)_position.x));
}
if(_position.y+_radius>=cyClient ||
int(_position.y-_radius)<=0){
_speed.y = -_speed.y;
_position.y = min(cyClient-_radius,
max(_radius,(int)_position.y));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -