C++图形开发(15):C++小游戏——别碰方块

53 篇文章 3 订阅
19 篇文章 8 订阅

经过了十几篇文章的开发,“别碰方块”小游戏已经完成啦!
直接下载地址(不是静态编译不能单EXE文件运行,所以上传的是整个项目):一个C++小游戏“别碰方块”
注意:源代码若要成功编译,请确保满足以下条件:
1.使用Visual Stdio进行编译
2.已正确安装graphics.h图形库(安装教程见:C++图形开发(1):graphics图形库简介与安装
3.已正确修改项目预处理器(修改教程见:C++问题解决:Visual Studio编译时显示“‘_swprintf: This function or variable may be unsafe.”怎么办?

内容分析等可以见专栏:C++图形开发
源代码如下:

#include<graphics.h> 
#include<conio.h>
#include<stdio.h>

int main() {
	double width, height;//定义画面长度、宽度
	width = 600;
	height = 400;
	initgraph(width, height);

	double ball_x, ball_y, ball_vy, r, g;//定义小球x轴、y轴、y轴方向的速度、半径、重力加速度
	g = 0.6;
	r = 20;
	ball_x = width / 4;//x坐标等于整个画面x轴长度的四分之一
	ball_y = height - r;//y坐标等于画面的y轴长度减去圆的半径(保证圆在画面的最底端)
	ball_vy = 0; //最初小球落在地面上时y轴方向的速度为0

	double rect_left_x, rect_top_y, rect_width, rect_height;//定义方块的各个位置变量
	rect_width = 20;
	rect_height = 100;
	rect_left_x = width * 3 / 4;
	rect_top_y = height - rect_height;

	double rect_vx = -3;//定义方块的移动速度

	int score = 0;//定义得分
	while (1) {
		if (_kbhit()) {
			char input = _getch();
			if (input == ' ' && ball_y == 380) {
				ball_vy = -16;
			}
		}
		ball_vy = ball_vy + g;//根据牛顿力学定律得
		ball_y = ball_y + ball_vy;//小球y轴方向的变化
		if (ball_y >= height - r) {
			ball_vy = 0;//小球落地以后速度清零
			ball_y = height - r;
		}
		rect_left_x = rect_left_x + rect_vx;
		if (rect_left_x <= 0) {//如果方块移动到最左边
			score++;
			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 + r) && (rect_left_x + rect_width >= ball_x - r) && (height - rect_height <= ball_y + r)) {
			score = 0;
			Sleep(100);//碰到方块慢动作
		}
		cleardevice();
		fillrectangle(rect_left_x, height - rect_height, rect_left_x + rect_width, height);
		fillcircle(ball_x, ball_y, r);

		TCHAR s[20];//定义字符串数组
		_swprintf(s, _T("%d"), score);//把score转换为字符串并储存在字符串数组s中
		settextstyle(40, 0, _T("宋体"));//设置文本大小
		outtextxy(50, 30, s);//输出得分
		Sleep(10);
	}
	_getch();
	closegraph();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值