使用c语言与EASYX实现弹球小游戏

eg1:小球碰到窗体的四个墙实现反弹效果

#include <stdio.h>
#include <easyx.h>
#include <iostream>
#include <math.h>
#include <conio.h>
#define PI 3.14


int main()
{
	initgraph(800, 600);
	setorigin(400, 300);
	setaspectratio(1, -1);
	setbkcolor(RGB(164, 225, 202));
	cleardevice();
	// 让小球初始位置出现在圆心的位置
	int x = 0;
	int y = 0;
	int vx = 5;
	int vy = 5;
	int r = 40;
	while (1) {
		cleardevice();
		solidcircle(x, y, r);
		Sleep(40);
		//判断小球是否撞击到顶边
		if (y >= 300 || y <= -300) {
			vy = -vy;

		}
		// 在坐标轴中取反
		if (x >= 400 || x <= -400) {
			vx = -vx;
		}
		x += vx;
		y += vy;
	}



	getchar();
	closegraph();
	return 0;

}

实现弹球小游戏的具体代码

  • 使用c语言的库函数和控制台函数指针与结构体
#include <stdio.h>
#include <easyx.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define PI 3.14


// 函数的封装---》 结构体
typedef struct {
	int x ,y;
	int vx, vy;
	int r;
	int barLeft, barTop, barRight, barBottom;

}GameData;

void reset(GameData *gdata) {
	// 指针调用数值的方式是->
	gdata->x = rand() % (400 + 1) - 200;
	gdata->y = rand() % (300 + 1) - 150;
	gdata->vx = 5;
	gdata->vy = 5;
	if (rand() % 2 == 0) {
		gdata->vy = -gdata->vy;

	}if (rand() % 2 == 0) {
		gdata->vx = -gdata->vx;
	}
	gdata->r = 40;
	gdata->barLeft = -150;
	gdata->barRight = 150;
	gdata->barTop = -280;
	gdata->barBottom = -300;

}

int main()
{
	initgraph(800, 600);
	setorigin(400, 300);
	setaspectratio(1, -1);
	setbkcolor(RGB(164, 225, 202));
	cleardevice();
	// 将当前的时间作为随机种子
	srand((unsigned int)time(NULL));
	//声明GameData变量将其传入reset函数中用于初始化游戏数据
	GameData gdata;
	// 函数的调用将地址传递过去通过指针获取地址
	reset(&gdata);


	while (1) {
		cleardevice();
		solidcircle(gdata.x, gdata.y, gdata.r);
		solidrectangle(gdata.barLeft, gdata.barTop, gdata.barRight, gdata.barBottom);
		Sleep(40);
		
		//判断小球是否撞击到顶边,当小球的边缘撞击到窗体的顶部时历史反弹
		if (gdata.y >= 300- gdata.r) {
			gdata.vy = -gdata.vy;
		}
		// 在坐标轴中取反
		if (gdata.x >= 400- gdata.r || gdata.x <= -400+ gdata.r) {
			gdata.vx = -gdata.vx;
		}
		// 撞击或越过挡板的代码
		if (gdata.barLeft <= gdata.x && gdata.x <= gdata.barRight && gdata.y <= gdata.barTop + gdata.r) {
			gdata.vy = -gdata.vy;// vy 取反
		}


​		

		gdata.x += gdata.vx;
		gdata.y += gdata.vy;
	
		// 获取用户键盘输入,判断键盘的按钮是否被按下,控制挡板的移动
		if (_kbhit() != 0) {
			char c = _getch();
			if (c == 'a') {
				// 控制挡板的移动范围
				if (gdata.barLeft > -400) {
					gdata.barLeft -= 20;
					gdata.barRight -= 20;
				}
	
			}
			else if (c == 'd') {
				if (gdata.barRight < 400) {
					gdata.barLeft += 20;
					gdata.barRight += 20;
				}
			}
		}
		if (gdata.y <= -300) {
			reset(&gdata);
		}
	}
	
	getchar();
	closegraph();
	return 0;

}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值