#include
#include
#include
#include
using namespace std;
int main() {
float width, height;
width = 600; height = 400;
initgraph(width, height);
float ball_x, ball_y, ball_vy, gravity,radius;
radius = 20; ball_x = width / 4; ball_y = radius; ball_vy = 0; gravity = 0.5;
float rect_left_x,rect_top_y,rect_width,rect_height;
rect_height = 100; rect_left_x = width * 3 / 4; rect_top_y = height - rect_height; rect_width = 20;
float rect_vx;
rect_vx = -3;
int score=0;
int isBallonFloor = 1;
while(1)
{
if (_kbhit())//检测空格按键,用户按下空格,小球就起跳
{
char input = _getch();
if (input == ' '&& isBallonFloor==1)
{
ball_vy = -16;//每次按下空格都给小球一个向上的初速度但是加速度还是向下的所以会跳起来又落下
isBallonFloor = 0;//isBallFloor是为了避免空中起跳
}
}
ball_vy += gravity;
ball_y += ball_vy;
if (ball_y >= height - radius)//小球落到底时是一个关键节点
{
ball_vy = 0;
ball_y = height - radius;
isBallonFloor = 1;
}
rect_left_x += rect_vx;
if (rect_left_x <= rect_width)//方块运动到最左边时也是一个关键节点
{
score += 1;
rect_left_x = width;
rect_height = rand() % int(height / 4) + height / 4;
rect_vx = rand()/float(RAND_MAX) *4 - 7;
}
if ((rect_left_x <= ball_x + radius) //碰撞检测
&& (rect_left_x + rect_width >=ball_x - radius) && (rect_top_y <= ball_y + radius))
{
score = -1;
Sleep(80);
}
cleardevice();
fillrectangle(rect_left_x, height-rect_height, rect_left_x + rect_width, height);
fillcircle(ball_x, ball_y, radius);
if (score >= 0)//显示计分
{
TCHAR s[20];
swprintf_s(s, _T("%d"), score);
settextstyle(40, 0, _T("宋体"));
outtextxy(50, 30, s);
}
Sleep(30);
}
closegraph();
return 0;
}