C语言游戏1:弹跳的小球

目录

显示静止的小球:

小球下落:

上下弹跳的小球:

斜着弹跳的小球:

控制小球弹跳的速度


显示静止的小球:

首先利用printf函数在屏幕坐标(x,y)处显示一个静止的小球字符‘o’。

#include <stdio.h>
int main()
{
    int i,j;
    int x=6;
    int y=9;
    for ( i = 0; i < x; i++)  //输出小球上面的空行 
    printf("\n");
    for ( j = 0; j < y; j++)  //输出小球左边的空格 
    printf(" ");
    printf("o");
    printf("\n");
    return 0;   
}

小球下落:

改变小球的坐标变量,即让小球的x坐标增加,从而让小球下落。在每次显示之前使用了清屏函数system("cls"),注意需要包含新的头文件#include <stdlib.h>。

#include <stdio.h>
#include <stdlib.h>

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;
}

上下弹跳的小球:

在上一步代码的基础上增加记录速度的变量velocity,小球的新位置x=旧位置x+速度velocity。当判断小球到达上,下边界时改变方向,即改变velocity的正负号。

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int i,j;
	int x=5;
	int y=10;
	
	int height=20;
	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==height)
	    velocity=-velocity;
	    if(x==0)
	    velocity=-velocity;
	}return 0;
 } 

斜着弹跳的小球:

增加x,y两个方向的速度控制变量velocity_x,velocity_y,初值为1;velocity_x碰到上,下边界后改变正负号,velocity_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=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");
		
		if((x==top)||(x==bottom))
		    velocity_x=-velocity_x;
		if((y==left)||(y==right))
		    velocity_y=-velocity_y; 
	}return 0;
}

控制小球弹跳的速度:

以上反弹球的速度可能过快,为了降低反弹球的速度,可以使用sleep函数(#include <windows.h>)。比如sleep(10)标识程序执行到此处暂停10ms,从而控制小球弹跳的速度。

printf("o");  //输出小球

printf("\n");

sleep(50);  //在输出图形后等待50ms

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值