#include<iostream>
#include<graphics.h>
#include<stdio.h>
#include<conio.h>
using namespace std;
int main()
{
float width, height, gravity;//游戏画面宽高
float ball_x, ball_y, ball_vy, radius;//小球圆心坐标,y方向速度,半径
//方块障碍物的相关参数
float rect_left_x, rect_top_y, rect_width, rect_height, rect_vx;
int score = 0;//得分
width = 600;
height = 400;
gravity = 0.6;
initgraph(width, height);//新建一个画布
radius = 20;
ball_x = width / 4;
ball_y = height - radius;
ball_vy = 0;
rect_width = 20;
rect_height = 100;
rect_left_x = width * 3/4;
rect_top_y = height - rect_height;
rect_vx = -3;
while (1)
{
if (_kbhit())//当按键时
{
char input = _getch();
if (input == ' ')//当按下空格键,给小球一个向上的速度
{
ball_vy = -17;
}
}
ball_vy += gravity;//根据重力加速度更新小球y方向速度
ball_y += ball_vy;//根据小球y方向速度更新其y坐标
if (ball_y >= height - radius)//如果小球落到地面上
{
ball_vy = 0;
ball_y = height - radius;//规范其y坐标,避免落到地面以下
}
rect_left_x += rect_vx;
if (rect_left_x <= 0)//如果方块跑到最左边
{
rect_left_x = width;//在最右边重新出现
score++;
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) && (height - rect_height <= ball_y + radius))
{
Sleep(100);//慢动作效果
score = 0;//得分清零
}
cleardevice();//清空画面
fillcircle(ball_x, ball_y, radius);//绘制小球
fillrectangle(rect_left_x, height - rect_height, rect_left_x + rect_width, height);//绘制方块
TCHAR s[20];//定义字符串数组
swprintf_s(s, _T("%d"), score);//将score转为字符串
settextstyle(40, 0, _T("宋体"));
outtextxy(50, 30, s);//输出文字得分
Sleep(10);//暂停10毫秒
}
closegraph();
return 0;
}
小项目-别碰方块【半成品】
最新推荐文章于 2024-08-09 22:34:59 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)