别撞方块小游戏代码

#include<graphics.h> 
#include<conio.h>
#include<stdio.h>
#include <iostream>
using namespace std;

int main() {
    float width, height;
    width = 600; height = 400;
    initgraph(width, height);

    float ball_x, ball_y, ball_vy, gravity,radius;
    radius = 20; ball_x = width / 4; ball_y = radius; ball_vy = 0; gravity = 0.5;

    float rect_left_x,rect_top_y,rect_width,rect_height;
    rect_height = 100; rect_left_x = width * 3 / 4; rect_top_y = height - rect_height; rect_width = 20;

    float rect_vx;
    rect_vx = -3;

    int score=0;
    int isBallonFloor = 1;

    while(1)
    {
        if (_kbhit())//检测空格按键,用户按下空格,小球就起跳
        {
            char input = _getch();
            if (input == ' '&& isBallonFloor==1)
            {
                ball_vy = -16;//每次按下空格都给小球一个向上的初速度但是加速度还是向下的所以会跳起来又落下
                isBallonFloor = 0;//isBallFloor是为了避免空中起跳
            }
        }
        
        ball_vy += gravity;
        ball_y += ball_vy;

        if (ball_y >= height - radius)//小球落到底时是一个关键节点
        {
            ball_vy = 0;
            ball_y = height - radius;
            isBallonFloor = 1;
        }

        rect_left_x += rect_vx;
        
        if (rect_left_x <= rect_width)//方块运动到最左边时也是一个关键节点
        {
            score += 1;
            rect_left_x = width;
            rect_height = rand() % int(height / 4) + height / 4;
            rect_vx = rand()/float(RAND_MAX) *4 - 7;
        }

        if ((rect_left_x <= ball_x + radius) //碰撞检测
            && (rect_left_x + rect_width >=ball_x - radius) && (rect_top_y <= ball_y + radius))
        {
            score = -1;
            Sleep(80);
        }

        cleardevice();
        fillrectangle(rect_left_x, height-rect_height, rect_left_x + rect_width, height);
        fillcircle(ball_x, ball_y, radius);

        if (score >= 0)//显示计分
        {
            TCHAR s[20];
            swprintf_s(s, _T("%d"), score);
            settextstyle(40, 0, _T("宋体"));
            outtextxy(50, 30, s);
        }
        
        
        Sleep(30);
            
    }
    closegraph();
    return 0;
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值