C语言实现反弹球小游戏

2020-02-25 00:00:11于丽

本文为大家分享了C语言反弹球游戏的具体代码,供大家参考,具体内容如下

这是利用函数写的C语言小游戏,用来检验自己的学习成果

反弹球的实现主要有几个子函数组成

问题也在于如何实现小球的下落,以及碰撞得分等情况

#include<stdio.h>
 
#include<windows.h>
#include<conio.h>
 
//定义全局变量
int high,width;  //游戏边界 
int ball_x,ball_y;  //小球位置
int ball_vx,ball_vy; //小球速度
int position_x,position_y; //挡板中心坐标
int radius;   //挡板半径 
int left,right; //键盘左右边界 
int ball_number; //反弹小球次数
int block_x,block_y; //方块的位置 
int score;  //消掉方块的个数 
 
void HideCursor()  //隐藏光标 
{
 CONSOLE_CURSOR_INFO cursor_info = {1, 0};
 SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
 
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 startup()  //数据初始化 
{
 high=18;  //定义边界 
 width=26;
 
 ball_x=0;  //小球坐标 
 ball_y=width/2;
 
 ball_vx=1;  //小球速度方向 
 ball_vy=1;
 
 position_x=high-1; //挡板中心坐标
 position_y=width/2; 
 
 radius=5;  //挡板半径
 
 left=position_y-radius; //键盘边界 
 right=position_y+radius;
 
 block_x=0;   //方块位置
 block_y=width/2-4; 
 
 ball_number=0; //反弹小球个数
 
 score=0;  //消掉小球个数 
 
 HideCursor(); 
 } 
 
void show()  //显示界面
{
 gotoxy(0,0);
 int i,j;
 for(i=0;i<=high;i++)
 {
 for(j=0;j<=width;j++)
 {
  if((i==ball_x) && (j==ball_y)) //输出小球 
  printf("0");
  else if((i==block_x)&& (j==block_y)) //输出滑块   //输出下边界 
   printf("@");
  else if(i==high)   //输出下边界 
   printf("-");
  else if(j==width)   //输出右边界 
   printf("|");
  else if((i==high-1)&&(j>left)&&(j<right)) 
   printf("*");
  else printf(" ");
 }
 printf("n");
 }
 printf("反弹小球次数:%dn",ball_number);
 printf("消掉小球个数:%dn",score);
 } 
 
void updateWithoutInpute() //与用户输入无关的更新
{
 if(ball_x==position_x-1)   //小球撞到挡板 
 {
 if((ball_y>=left)&&(ball_y<=right))
 {
  ball_number++;
  //printf("a");
 }
 else
 {
  printf("游戏失败n");
  system("pause");
  exit(0);
 }
 }
 
 
 ball_x = ball_x + ball_vx;  //小球向速度方向移动 
 ball_y = ball_y + ball_vy;
 
 if((ball_x==0) || (ball_x==high-2)) //小球撞到上下边界 
 ball_vx=-ball_vx;
 if((ball_y==0) || (ball_y==width-1)) //小球撞到左右边界 
 ball_vy=-ball_vy;
 
 if((block_x==ball_x) && (block_y==ball_y)) //小球撞到滑块 
 {
 block_y=rand()%width-1;
 score++;
 }
 Sleep(120);
 
 } 
 
void updateWithInpute()  //与用户输入有关的更新
{
 char input;
 if(kbhit())
 {
 input=getch();
 if((input=='a')&&(left>=0))
 {
  position_y--;
  left=position_y-radius; //键盘边界 
  right=position_y+radius;
 }
 if((input=='d')&&(right<width))
 {
  position_y++;
  left=position_y-radius; //键盘边界 
  right=position_y+radius;
 } 
 }
 }
 
int main()
{
 system("color 2f");     //改变控制台颜色
 startup();
 while(1)
 { 
 show();          //显示界面
 updateWithoutInpute();    //与用户输入无关的更新
 updateWithInpute();     //与用户输入有关的更新
 }
 }