反弹球消砖块

#include<stdio.h>
#include<windows.h> 
#include<stdlib.h>
#include<conio.h>
//定义全局变量
int ball_x,ball_y;				//小球的位置
int high,width;					//游戏的画面尺寸 
int v_x,v_y;					//小球的速度 
int position_x,position_y;		//挡板的中心坐标 
int radius;						//挡板的半径 
int left,right;					//挡板的左右边界
int ball_num;					//反弹小球次数
int block_x,block_y;			//砖块位置
int score;						//消掉的砖块数 

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()		//数据初始化
{
	high=18;
	width=30;
	
	ball_x=0;
	ball_y=width/2;
	
	v_x=1;
	v_y=1;			//开始小球向右下角运动 
	
	position_x=high;
	position_y=width/2;
	radius=5;
	left=position_y-radius;
	right=position_y+radius;
	
	block_x=0;
	block_y=width/2+1;
	
	score=0;		//消掉的砖块数 
	ball_num=0;		//记录小球碰挡板次数 
	
	HideCursor();   //隐藏光标 
}

void show()			//显示画面
{
	//system("cls");				//清屏 
	gotoxy(0,0);	//光标移动到原点位置,相当于清屏 
	int i,j;
	for(i=0;i<=high+1;i++){
		for(j=0;j<=width;j++){
			if(i==ball_x && j==ball_y){
				printf("o");	//输出小球o
			}
			else if(j==width){
				printf("#");	//输出右边界 
			}
			else if(i==high+1){
				printf("#");	//输出下边界 
			} 
			else if(i==high && (j>left && j<right)){
				printf("*");	//输出挡板 
			}
			else if(i==block_x && j==block_y){
				printf("B");	//输出砖块 
			} 
			else{
				printf(" ");	//输出空格 
			}	
		}
		printf("\n");
	}
	printf("反弹小球数: %d\n",ball_num); 
	printf("消掉的砖块数: %d\n",score); 
}
void updataWithoutInput()		//与用户输入无关的更新 
{
	if(ball_x==high-1){
		// 球与挡板相撞 
		if(ball_y>=left && ball_y<=right){
			ball_num++;
			v_y=-v_y; 
		}
		else{
			printf("Game over!\n");
			exit(0);			//游戏结束,退出 
		}
	}
	
	if(ball_x==block_x && ball_y==block_y){
		score++;
		block_y=rand()%width;	//随机产生新的砖块 
	}
	
	//根据速度更新小球的位置 
	ball_x=ball_x+v_x;
	ball_y=ball_y+v_y;
	//碰到边界后,改变速度的方向,实现反弹 
	if(ball_x==0 || ball_x==high-1){
		v_x=-v_x;
	} 
	if(ball_y==0 || ball_y==width-1){
		v_y=-v_y;
	}
	Sleep(100); 
}
void updateWithInput()		    	//与用户输入有关的更新
{
	char input;
	if(kbhit()){					//判断是否有输入
		input=getch();				//根据用户的不同输入来移动 
		if(input=='a'){
			position_y--;
			left=position_y-radius;
			right=position_y+radius;
		}
		if(input=='d'){
			position_y++;
			left=position_y-radius;
			right=position_y+radius;
		}	 
	} 
}
int main()
{
	startup();						//数据初始化
	
	while(1){						//游戏循环执行 
		
		show();						//显示画面
		updataWithoutInput();		//与用户输入无关的更新 
		updateWithInput();			//与用户输入有关的更新
		
	} 
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值