小项目-别碰方块【半成品】

这是一个简单的C++程序,创建了一个小球在游戏窗口中下落并碰撞到移动方块的游戏。游戏包括小球的位置、速度、重力、得分以及方块的移动速度和高度。玩家可以通过空格键给小球一个向上的初速度。当方块移动到屏幕左侧时会在右侧重新出现,高度和速度随机变化。游戏过程中,小球碰到方块会导致得分清零。
摘要由CSDN通过智能技术生成

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值