easyx图形库c++实现气泡碰撞的图像
时间: 2023-09-23 07:03:47 浏览: 57
实现气泡碰撞的图像可以通过easyx图形库的绘图函数和动画函数来实现。以下是一个简单的示例代码:
```c++
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10 // 气泡数量上限
// 定义气泡结构体
struct Bubble
{
int x; // x坐标
int y; // y坐标
int r; // 半径
int vx; // x轴速度
int vy; // y轴速度
COLORREF color; // 颜色
};
Bubble bubbles[MAX]; // 存储气泡的数组
// 初始化气泡
void InitBubble(Bubble& bubble)
{
bubble.x = rand() % 600 + 50; // 随机生成x坐标
bubble.y = rand() % 400 + 50; // 随机生成y坐标
bubble.r = rand() % 20 + 10; // 随机生成半径
bubble.vx = rand() % 6 - 3; // 随机生成x轴速度
bubble.vy = rand() % 6 - 3; // 随机生成y轴速度
bubble.color = RGB(rand() % 256, rand() % 256, rand() % 256); // 随机生成颜色
}
// 绘制气泡
void DrawBubble(Bubble& bubble)
{
setfillcolor(bubble.color); // 设置填充颜色
setlinecolor(WHITE); // 设置边框颜色
fillcircle(bubble.x, bubble.y, bubble.r); // 绘制气泡
}
// 更新气泡位置
void UpdateBubble(Bubble& bubble)
{
bubble.x += bubble.vx; // 更新x坐标
bubble.y += bubble.vy; // 更新y坐标
// 判断是否碰到边界,碰到则反弹
if (bubble.x - bubble.r < 0 || bubble.x + bubble.r > 800)
{
bubble.vx = -bubble.vx;
}
if (bubble.y - bubble.r < 0 || bubble.y + bubble.r > 600)
{
bubble.vy = -bubble.vy;
}
}
int main()
{
// 初始化图形界面
initgraph(800, 600);
srand(time(NULL)); // 初始化随机数生成器
// 初始化气泡
for (int i = 0; i < MAX; i++)
{
InitBubble(bubbles[i]);
}
// 绘制气泡
while (true)
{
cleardevice(); // 清空屏幕
// 绘制气泡
for (int i = 0; i < MAX; i++)
{
DrawBubble(bubbles[i]);
}
// 更新气泡位置
for (int i = 0; i < MAX; i++)
{
UpdateBubble(bubbles[i]);
}
Sleep(20); // 暂停20ms
// 检测是否有按键按下,如果有则退出程序
if (_kbhit())
{
break;
}
}
closegraph(); // 关闭图形界面
return 0;
}
```
在该示例代码中,我们使用了结构体来存储气泡的属性,包括位置、速度、半径和颜色等。我们使用了随机数生成器来初始化气泡的属性,然后使用绘图函数和动画函数来绘制和更新气泡的位置。在更新位置时,我们判断了气泡是否碰到了屏幕边界,如果碰到了则反弹。最后,我们使用了 `_kbhit()` 函数来检测是否有按键按下,如果有则退出程序。