先给大家介绍的是弹跳的小球。
基本思路:
先让屏幕上出现一个小球,再实现弹跳,利用Sleep函数降低弹跳速度。
1.出现小球
#include<stdio.h>
int main()
{
int x=20,y=20; //坐标轴上小球的位置
int i,j;
for(i=0;i<x;i++)
printf("\n"); //输出小球上面的空行
for(j=0;j<y;j++)
printf(" "); //输出小球左边的空格
printf("O"); //输出小球
printf("\n");
}
2.实现弹跳
#include<stdio.h>
#include<stdlib.h> //使用清屏函数
int main()
{
int x=5,y=10;
int i,j;
int high=20;
int top=0;
int velocity=1; //用于记录速度
while(1)
{
x=x+velocity;
system("cls"); //清屏函数
for(i=0;i<x;i++)
printf("\n");
for(j=0;j<y;j++)
printf(" ");
printf("o"); //输出小球
printf("\n");
if(x==high||x==top) //当小球碰到顶端或低端时改变速度方向
velocity=-velocity;
}
}
3.上面的代码只能实现小球上下弹跳,不是很有意思,我们可以再增加两个速度变量实现上下左右弹跳
#include<stdio.h>
#include<stdlib.h> //使用清屏函数
#include<windows.h> //使用Sleep函数
int main()
{
int x=0,y=5;
int i,j;
int high=20;
int top=0;
int left=0;
int right=10;
int velocity_x=1; //控制上下方向的速度
int velocity_y=1; //控制左右方向的速度
while(1)
{
x=x+velocity_x;
y=y+velocity_y;
system("cls"); //清屏函数
for(i=0;i<x;i++)
printf("\n");
for(j=0;j<y;j++)
printf(" ");
printf("o"); //输出小球
printf("\n");
if(x==top||x==high)
{
velocity_x=-velocity_x;
}
if(y==right||y==left)
{
velocity_y=-velocity;
}
}
return 0;
}
4.以上就是小球弹跳的程序了但它弹跳的速度太快容易眼花,所以我们用Sleep函数让它慢点跳
#include<stdio.h>
#include<stdlib.h> //使用清屏函数
#include<windows.h> //使用Sleep函数
int main()
{
int x=5,y=10;
int i,j;
int high=20;
int top=0;
int velocity=1; //用于记录速度
while(1)
{
x=x+velocity;
system("cls"); //清屏函数
for(i=0;i<x;i++)
printf("\n");
for(j=0;j<y;j++)
printf(" ");
printf("o"); //输出小球
printf("\n");
Sleep(50);
if(x==high||x==top) //当小球碰到顶端或低端时改变速度方向
velocity=-velocity;
}
}
没了。