C语言和easyx制作的弹球小游戏

代码

#include <easyx.h>

#include <stdio.h>

#include <conio.h>

#include <time.h>

 

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);

    // 坐标系原点在窗体中心,X轴正方向向右,Y轴正方向向上

    setorigin(400, 300);

    setaspectratio(1, -1);

    // 设置背景色

    setbkcolor(RGB(164, 225, 202));

    // 使用背景色清空窗体

    cleardevice();

 

    // 当前时间作为随机数种子

    srand((unsigned int)time(NULL));

 

    // 游戏数据

    GameData gdata;

    // 初始化游戏数据

    reset(&gdata);

 

    while (1)

    {

        cleardevice();

        // 绘制小球

        solidcircle(gdata.x, gdata.y, gdata.r);

        // 绘制挡板

        solidrectangle(gdata.barLeft, gdata.barTop, gdata.barRight, gdata.barBottom);

 

        // 每帧之间休眠40ms

        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;

        }

 

        // 小球位置变化

        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);

        }

    }

 

    closegraph();

    return 0;

}

其他

欢迎大家加入墨奇游戏盒​​​​​​

转载自:http://t.csdnimg.cn/2eaW4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值