源码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<time.h>
#define WIDTH 600.0
#define HEIGHT 400.0
#define R 20 //radius 半径
int main() {
srand(time(NULL));
float gravity;
float ball_x, ball_y, ball_vy;
float rect_left_x, rect_top_y, rect_width, rect_height,rect_vx;//方块障碍物的相关参数
int score;
ball_x = WIDTH / 4;
ball_y = HEIGHT - R;
ball_vy = 0;
gravity = 0.6;
score = 0;
rect_height = 100;
rect_vx = -3;
rect_width = 20;
rect_left_x = WIDTH * 3 / 4;
//rect_top_y = HEIGHT - rect_height;
rect_top_y = HEIGHT - rect_height;
initgraph(WIDTH,HEIGHT,1);
while (1) {
BeginBatchDraw();
//rect_height = HEIGHT * (rand() / 2 + 1) / 4;
if (_kbhit()) {
char input = _getch();
if (input == ' ' ) { //当按下空格键,给小球一个向上的初速度
ball_vy = -17;
}
}
ball_vy += gravity;//根据重力加速度更新小球y方向的速度
ball_y += ball_vy;//根据小球y方向的速度更新y坐标
rect_left_x += rect_vx;//让障碍物从右向左移动
if (rect_left_x<=-rect_width) {//当障碍物到达最左段时从右端出现
rect_height = rand() % (int)(HEIGHT / 4) + HEIGHT / 4;
//rect_top_y = HEIGHT - rect_height;
rect_vx = rand() % 5 - 7;
printf("%f ", rect_height);
printf("%f\n", rect_vx);
score += 1;
rect_left_x = WIDTH;
}
if (ball_y>= HEIGHT - R) {//如果小球落地 y方向速度为零,
ball_vy = 0;
ball_y = HEIGHT - R;//规范其y坐标,避免落到地面上
}
if (rect_left_x<=ball_x+R && rect_left_x+rect_width>=ball_x-R
&& rect_top_y<=ball_y+R) {
score = 0;
Sleep(40);
}
cleardevice();
char str[50] = " ";
sprintf(str, "分数:%d", score);
settextstyle(20, 0, "宋体");
outtextxy(0, 0, str);
fillcircle(ball_x,ball_y,R);//画圆
fillrectangle(rect_left_x, HEIGHT - rect_height,
rect_left_x+rect_width,rect_top_y+rect_height);//画障碍物
Sleep(5);
EndBatchDraw();
}
closegraph();
return 0;
}
bug是小球在空中还能继续跳跃
解决bug
if (input == ' ' && ball_vy == 0) { //当按下空格键,给小球一个向上的初速度
ball_vy = -17;
}
或
int isBallOnFloor = 1;
if (input == ' ' && isBallOnFloor==1) { //当按下空格键,给小球一个向上的初速度
ball_vy = -17;
isBallOnFloor = 0;
}
if (ball_y>= HEIGHT - R) {//如果小球落地 使y方向速度为零,
ball_vy = 0;
ball_y = HEIGHT - R;//规范其y坐标,避免落到地面上
isBallOnFloor = 1;
}