利用printf函数实现一个在屏幕上弹跳的小球,弹跳的小球也是反弹球消砖块、接金币、台球等很多游戏的基础。
实现小球的弹跳,我们可分解为以下过程:
(1)显示静止的小球
(2)小球下落
(3)上下弹跳的小球
(4)斜着弹跳的小球
(5)控制小球弹跳的速度
本文代码,笔者均通过VC++6.0运行
显示静止的小球
/*
显示静止的小球
时间:2020年5月1日14:56:42
利用 printf 函数在屏幕坐标(x,y)处显示一个静止的小球字符 'o' ,
坐标系的原点为屏幕左上角。
y
____________________
|
|
|
x|
|
|
|
*/
# include <stdio.h>
int main()
{
int x=5, y=10, i, j; //x,y为小球在屏幕上显示的坐标位置
for(i=0; i<x; i++)
printf("\n");
for(j=0; j<y; j++)
printf(" ");
printf("o\n");
return 0;
}
小球下落
/*
小球下落
时间:2020年5月1日15:00:37
在 “显示静止的小球” 的基础上
相当于通过 无数张图像重合 的形式
运用清屏 来实现这个小球下落的动态过程
y
____________________
|
|
|
x|
|
|
|
让小球的x坐标增加,从而让小球下落
*/
# include <stdio.h>
# include <stdlib.h> //含清屏函数 system("cls")
int main()
{
int i, j;
int x = 1;
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");
printf("\n");
}
return 0;
}
上下弹跳的小球
/*
上下弹跳的小球
时间:2020年5月2日16:32:31
设定小球弹跳的上下边界为[0,20],小球从坐标为[5,10]开始下落,然后反复弹跳。
y
____________________
|
|
|
x|
|
|
|
*/
# include <stdio.h>
# include <stdlib.h> //含清屏函数 system("cls")
int main()
{
int i, j;
int x = 5;
int y = 10;
int height = 20; // 下边界,即小球坐标为20时,开始反弹
int velocity = 1; // 小球运动速度
while(1) // 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 == height)
velocity = -velocity;
if(x == 0)
velocity = -velocity;
}
return 0;
}
斜着弹跳的小球
/*
斜着弹跳的小球
时间:2020年5月3日09:10:28
基于 上下弹跳的小球 的基础上
上下弹跳的小球 只需纵坐标变换
斜着弹跳的小球 在 上下弹跳的小球 的基础上添加一个横坐标的变换
边界坐标尽量不在语句中直接写数值,可以用定义的变量或变量标识符
这样程序的可读性更好,后续容易调整
y
____________________
|
|
|
x|
|
|
|
*/
# include <stdio.h>
# include <stdlib.h>
int main()
{
int i, j;
int x = 0;
int y = 5;
int velocity_x = 1; // x方向的速度控制变量
int velocity_y = 1; // y方向的速度控制变量
int left = 0; // y轴区间为【0,20】
int right = 20;
int top = 0; // x轴区间为【0,10】
int bottom = 10;
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 == bottom))
velocity_x = -velocity_x;
if((y == left) || (y == right))
velocity_y = -velocity_y;
}
return 0;
}
控制小球弹跳的速度
/*
控制小球弹跳的速度
时间:2020年7月1日21:12:11
反弹球的速度可能过快,为降低反弹球的速度,
可以使用 Sleep 函数,如 Sleep(10) 程序执行到此处暂停 10ms ,
从而控制小球速度
根据编译器的不同可以选择:
# include <windows.h>
# include <cwindows.h>
y
____________________
|
|
|
x|
|
|
|
*/
# 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 = 20;
int top = 0;
int bottom = 10;
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");
Sleep(50);
if((x == top) || (x == bottom))
velocity_x = -velocity_x;
if((y == left) || (y == right))
velocity_y = -velocity_y;
}
return 0;
}