反弹球1.0

来源:互联网 发布:华资软件面试 编辑:程序博客网 时间:2024/06/07 09:12
#include <stdio.h>#include <Windows.h>#include <stdlib.h>#include <conio.h>int right, left, top, bottom;int ball_x, ball_y, speed_x, speed_y;int radius, position_x, position_y;int block_x, block_y;void setup(void);void gotoxy(int x, int y);//VS中未包括gotoxy函数,必须自己实现;使光标定位到指定位置void HideCursor();//隐藏光标void show(void);void update_with_input(void);void update_without_input(void);main(){    setup();    while (1)    {        HideCursor(); //不能放在setup里        show();        update_without_input();        update_with_input();    }    return 0;}void setup(void){    right = 50, left = 10, top = 10, bottom = 40;    ball_x = 15, ball_y = 15, speed_x = 1, speed_y = 1;    radius = 5, position_x = 30, position_y = 39;    block_x = 40, block_y = 11;}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(void){    CONSOLE_CURSOR_INFO cursor_info = { 1,0 };    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);}void show(void){    gotoxy(0, 10);    for (int i = top; i <= bottom; i++)    {        for (int j = left; j <= right; j++)        {            if (i == ball_y && j == ball_x) printf("*");            else if (i == top || i == bottom && j != left && j != bottom) printf("-");            else if (j == left || j == right) printf("|");            else if (i == block_y&&j == block_x) printf("B");            else if (i == position_y && j >= position_x - radius && j <= position_x + radius)                printf("=");//如果用循环输入挡板,则会使得右边的边界右移            else printf(" ");        }        printf("\n");    }}void update_without_input(void){    if (ball_x == left || ball_x == right) speed_x = -speed_x;    if (ball_y == top) speed_y = -speed_y;    if (position_x + radius >= right-1) position_x = right- radius-1;//左值只能有一个变量    if (position_x - radius <= left+1) position_x = left+ radius+1;    static int delay = 0;    if (delay < 4) delay++;    else if (delay == 4) //要注意delay必须为偶数,否则89行会变换奇数次,速度还是向下    {        ball_x += speed_x;        ball_y += speed_y;        delay = 0;    }    if (ball_y == 39 && (ball_x >= position_x - radius && ball_x <= position_x + radius)) speed_y = -speed_y;    else if(ball_y == 39 && (ball_x < position_x - radius || ball_x > position_x + radius))    {        printf("lose!");        Sleep(1000);//S要大写        exit(0);    }}void update_with_input(void){    char input;    if (_kbhit())//有输入为1,没输入为0    {        input = _getch();        switch (input)        {        case 'a': //单引号而不是双引号            position_x--;            break;        case'd':            position_x++;            break;        }    }}
原创粉丝点击