在VS2022中用EasyX实现一小球在一矩形框内的任意位置,初始时以随机角度,随机速度往下掉落,每次碰到边框时以随机角度,随机速度继续运行,按ESC键结束。
效果展示
在指定范围内若干小球自由随机运动
代码展示
#include <graphics.h>
#include <conio.h>
#include <time.h>
#include <math.h>
#define M_PI 3.14159265358979323846
#define n 5// 小球数量
// 定义小球结构体
typedef struct {
double x, y; // 小球中心坐标
double radius; // 小球半径
double angle; // 小球运动角度(弧度)
double speed; // 小球运动速度
} Ball;
// 更新小球位置
void updateBallPosition(Ball* ball, int width, int height) {
double dx = ball->speed * cos(ball->angle);
double dy = ball->speed * sin(ball->angle);
ball->x += dx;
ball->y += dy;
// 检查小球是否碰到矩形框边界
if (ball->x - ball->radius <= 0 || ball->x + ball->radius >= width) {
ball->angle =(rand() % 360)*M_PI/180; // 随机方向反弹
ball->speed = 5 + rand() % 15; // 随机速度
// 确保小球不会卡在边界上
if (ball->x - ball->radius <= 0) ball->x = ball->radius + 1;
if (ball->x + ball->radius >= width) ball->x = width - ball->radius - 1;
}
if (ball->y - ball->radius <= 0 || ball->y + ball->radius >= height) {
ball->angle =(rand() % 360)*M_PI/180; // 随机方向反弹
ball->speed = 5 + rand() % 15; // 随机速度
// 确保小球不会卡在边界上
if (ball->y - ball->radius <= 0) ball->y = ball->radius + 1;
if (ball->y + ball->radius >= height) ball->y = height - ball->radius - 1;
}
}
int main() {
// 初始化随机数种子
srand((unsigned int)time(NULL));
// 窗口设置
int width = 640;
int height = 480;
initgraph(width, height, EW_SHOWCONSOLE);
setbkcolor(RGB(108, 237, 119));
cleardevice(); // 清屏
// 设置小球初始位置
Ball ball[n];
for (int i = 0; i < n; i++) {
ball[i].x = rand() % (width - 20) + 10;
ball[i].y = rand() % (height - 20) + 10;
ball[i].radius = 20;
ball[i].angle = (rand() % 360) * M_PI / 180; // 随机角度,转换为弧度
ball[i].speed = 5 + rand() % 15; // 随机速度
}
//开始绘制
while (!_kbhit() || (_getch() != VK_ESCAPE)) {
cleardevice(); // 清屏
// 绘制矩形框
rectangle(0, 0, width, height);
for (int i = 0; i < n; i++) {
// 更新小球位置
updateBallPosition(&ball[i], width, height);
// 绘制小球
setfillcolor(RGB(83, 211, 237));
setlinecolor(BLACK);
circle(ball[i].x, ball[i].y, ball[i].radius);
fillcircle(ball[i].x, ball[i].y, ball[i].radius);
}
Sleep(10); // 延迟一段时间
}
closegraph();
return 0;
}