靜止小球
#include<stdio.h>
int main()
{
int i, j;
int x = 5;
int y = 10;
for(i = 0; i < x; i++)
printf("\n");
for(j = 0; j < y; j++)
printf(" ");
printf("o\n");
return 0;
}
運行結果如下:
下落小球
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, j;
int x;
int y = 10;
for(x = 1; x < 10; x++)
{
system("cls"); //清屏函數
for(i = 0; i < x; i++)
printf("\n");
for(j = 0; j < y; j++)
printf(" ");
printf("o\n");
}
return 0;
}
上下彈跳小球
這裏加入了速度變量velocity,如果小球到達上或下邊界,則改變velocity正負號
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, j;
int x = 5;
int y = 10;
int height = 30;
int velocity = 1;
while(1)
{
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 == height)
velocity = -velocity;
if(x == 0)
velocity = -velocity;
}
return 0;
}
這是彈跳效果,傳送門——
上下彈跳小球
斜着跳動的小球
這裏我們分別添加了x,y方向上的速度變量,使得模型更加科學
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, j;
int x = 0;
int y = 5;
int velocity_x = 1;
int velocity_y = 1;
int left = 0;
int right = 50;
int top = 0;
int bottom = 30;
while(1)
{
x += velocity_x;
y += velocity_y;
system("cls");
for(i = 0; i < x; i++)
printf("\n");
for(j = 0; j < y; j++)
printf(" ");
printf("o\n");
if((x == top) || (x == bottom))
velocity_x = -velocity_x;
if((y == left) || (y == right))
velocity_y = -velocity_y;
}
return 0;
}
如果想看運行狀態,這裏是傳送門:
斜着彈跳的小球
同時,如果添加sleep()函數可以控制小球彈跳的速度
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int main()
{
int i, j;
int x = 0;
int y = 5;
int velocity_x = 1;
int velocity_y = 1;
int left = 0;
int right = 50;
int top = 0;
int bottom = 30;
while(1)
{
x += velocity_x;
y += velocity_y;
system("cls");
for(i = 0; i < x; i++)
printf("\n");
for(j = 0; j < y; j++)
printf(" ");
printf("o\n");
sleep(1);
if((x == top) || (x == bottom))
velocity_x = -velocity_x;
if((y == left) || (y == right))
velocity_y = -velocity_y;
}
return 0;
}
爲了生動點我們可以添加響鈴效果
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int main()
{
int i, j;
int x = 0;
int y = 5;
int velocity_x = 1;
int velocity_y = 1;
int left = 0;
int right = 50;
int top = 0;
int bottom = 30;
while(1)
{
x += velocity_x;
y += velocity_y;
system("cls");
for(i = 0; i < x; i++)
printf("\n");
for(j = 0; j < y; j++)
printf(" ");
printf("o\n");
//sleep(1);
if((x == top) || (x == bottom))
{
velocity_x = -velocity_x;
printf("\a");
}
if((y == left) || (y == right))
{
velocity_y = -velocity_y;
printf("\a");
}
}
return 0;
}
傳送門
模擬小球彈跳