游戏描述
用c语言实现反弹球消砖块小游戏。
效果
代码
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <cwindow.h>
// 全局变量
int high,width; // 游戏画面大小
int ball_x,ball_y; // 小球的坐标
int ball_vx,ball_vy; // 小球的速度
int position_x,position_y;//挡板的中心点
int r;//挡板的半径
int left,right;//挡板的左右点范围
int number;
int block_x,block_y;
int score;
int block_r;
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 = 13;
width = 17;
ball_x = 0;
ball_y = width/2;
ball_vx = 1;
ball_vy = 1;
position_x=high;
position_y=width/2;
r=5;
left=position_y-r;
right=position_y+r;
number=0;
block_x=0;
block_y=width/2 ;
block_r=3;
score=0;
}
void show() // 显示画面
{
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("0"); }
else if(j==width)//输出边界
printf("|");
else if(i==high)
printf("-");
else if((i==high-1)&&(j>=left)&&(j<=right))//输出底板
printf("*");
else if((i==0)&&(j>=block_y-r)&&(j<=block_y+r))
printf("B");
else
printf(" ");//
}
printf("\n");
}
printf("反弹小球数:%d\n",number);//成绩
printf("击中得分: %d\n",score);//得分
}
void updateWithoutInput() // 与用户输入无关的更新
{
if(ball_x==high-1)
{
if((ball_y>=left)&&(ball_y<=right))
{
number++;
printf("\a");
}
else
{
printf("\n游戏失败\n");
system("pause");
exit(0);
}
}
if((ball_x==0)&&(ball_y>=block_y-r)&&(ball_y<=block_y+r))
{
score++;//分数+1
block_y=rand()%width;//产生新的砖块
}
ball_x = ball_x + ball_vx;
ball_y = ball_y + ball_vy;
if ((ball_x==0)||(ball_x==high-1))//碰顶或者碰底
ball_vx = -ball_vx;
if ((ball_y==0)||(ball_y==width-1))//碰左或碰右
ball_vy = -ball_vy;
Sleep(80);
}
void updateWithInput()
{
char input;
if(kbhit())
{
input=getch();
if(input=='a')
{
position_y--;
left=position_y-r;
right=position_y+r;
}
if(input=='d')
{
position_y++;
left=position_y-r;
right=position_y+r;
}
}
}
int main()
{
startup(); // 数据初始化
while (1) // 游戏循环执行
{
show(); // 显示画面
updateWithoutInput(); // 与用户输入无关的更新
updateWithInput(); // 与用户输入有关的更新
}
return 0;
}