C语言实现弹跳小球

简单的控制台弹跳小球

#include <stdio.h>

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


// 全局变量
int x,y; //小球坐标 
int velocity_x,velocity_y ; //速度 
int left,right,top,bottom; //边界 


void gotoxy(int x,int y)  //光标移动到(x,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 startup() // 数据初始化
{
x = 1;
y = 5;
velocity_x = 1; //速度方向 
velocity_y = 1;
left = 0;
right = 30;
top = 0;
bottom = 15;


HideCursor(); // 隐藏光标
}


void show()  // 显示画面
{

int i,j;
for (i=0;i<=bottom;i++)
{
for (j=0;j<=right;j++)
{



if((i==x) && (j==y))
{
printf("o"); //打印小球 
}
else if ((i==0)||(i==bottom)||(j==0)||(j==right)) //打印边界 
{
printf("#");
}
else printf(" ");
}
printf("\n");
}
}
void automation()  // 与用户输入无关的更新
{
x = x + velocity_x;  
y = y + velocity_y;
if ((x==top)||(x==bottom))
{
velocity_x = -velocity_x;
printf("\a");
}

else if ((y==left)||(y==right))
{
velocity_y = -velocity_y;
printf("\a");
}

Sleep(100); //调低小球速度 
}
int main()
{
system("color 2f"); //改变控制台颜色 
startup();  // 数据初始化
while (1) //  游戏循环执行
{
gotoxy(0,0);  // 清屏 
show();  // 显示画面
automation();  // 与用户输入无关的更新
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40685101/article/details/80219561