用easyX实现若干小球在规定框中随机自由运动

在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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值