2.2 用函数实现反弹球消砖块

  本节将会升级我们在1.1节中的反弹球,将会增加显示边框、移动挡板反弹球消砖块。

2.2.1 代码重构

  我们首先对之前写的代码进行重构。

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>

//全局变量
int high, width;//游戏画面大小
int ball_x, ball_y;//小球的坐标
int ball_vx, ball_vy;//小球的速度

//数据初始化
void startup() {
    high = 15;
    width = 20;
    ball_x = 0;
    ball_y = width / 2;
    ball_vx = 1;
    ball_vy = 1;
}

//将光标移动到(x,y)位置
void gotoxy(int x, int y) {
    HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(handle, pos);
}

//隐藏光标
void HideCursor() {
    CONSOLE_CURSOR_INFO cursor_info = { 1,0 };//第二个值为0表示隐藏光标
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

//显示画面
void show() {
    gotoxy(0, 0);//光标移动到原点
    int i, j;
    for (int i = 0; i < high; i++) {
        for (int j = 0; j < width; j++) {
            //优先度:小球>空格
            if ((i == ball_x) && (j == ball_y))
                printf("O");//输出小球
            else
                printf(" ");//输出空格5
        }
        printf("\n");
    }
}

//与用户输入无关的更新
void updateWithoutInput() {
    ball_x += ball_vx;
    ball_y += ball_vy;
    
    if ((ball_x == 0) || (ball_x == high - 1))
        ball_vx *= -1;
    if ((ball_y == 0) || (ball_y == width - 1))
        ball_vy *= -1;
    Sleep(50);
}

//与用户输入有关的更新
void updateWithInput() {

}

//主函数
int main() {
    HideCursor();//隐藏光标
    startup();//数据初始化
    while (true) {//游戏循环
        show();//显示画面
        updateWithoutInput();//与用户输入无关的更新
        updateWithInput();//与用户输入有关的更新
    }
    return 0;
}

2.2.2 显示边框

  我们将给小球准备一个边框,由于我们是以一个矩形进行输出的,我们可以很方便的判断边框的坐标并设定合适的优先级即可。(左右边界“ | ”,上下边界“ - ”)

//显示画面
void show() {
    gotoxy(0, 0);//光标移动到原点
    int i, j;
    for (int i = 0; i < high; i++) {
        for (int j = 0; j < width; j++) {
            //优先度:边框>小球>空格
            if ((j == 0) || (j == width-1))
                printf("|");//输出左右边框
            else if ((i == 0) || (i == high-1))
                printf("-");//输出上下边框
            else if ((i == ball_x) && (j == ball_y))
                printf("O");//输出小球
            else
                printf(" ");//输出空格
        }
        printf("\n");
    }
}

2.2.3 显示移动挡板

  我们将实现一块可以左右移动的挡板,通过一个中心坐标 ( p o s i t i o n _ x , p o s i t i o n _ y ) (position\_x,position\_y) (position_x,position_y) 半径为 r i d u s ridus ridus 生成一块挡板。(挡板使用“ * ”, a , d a,d a,d 键移动)


2.2.4 反弹小球

  


2.2.5 消砖块

  


小结

  。。。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值