相信大家都玩过弹球砖块,话不多说,直接上代码。
代码很简单,试着运行了一下,玩着没有问题。
大家可以试玩,也可以试着优化,欢迎在评论区交流,谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
int high,width;
int ball_x,ball_y;
int ball_vx,ball_vy;
int position_x,position_y;
int ridus;
int left,right;
int ball_number;
int block_x,block_y;
int score;
void gotoxy (int x,int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition (handle,pos);
}
void startup ()
{
high = 20;
width = 30;
ball_x = 0;
ball_y = width/2;
ball_vx = 1;
ball_vy = 1;
position_x = high;
position_y = width/2;
ridus = 6;
left = position_y-ridus;
right = position_y+ridus;
ball_number = 0;
block_x = 0;
block_y = width/2-2;
score = 0;
}
void show ()
{
int i,j;
gotoxy (0,0);
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+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_number);
printf ("消掉砖块数:%d\n",score);
}
void updateWithoutInput ()
{
if (ball_x == high-1)
{
if ((ball_y >= left) && (ball_y <=right))
{
ball_number++;
printf ("\a");
//ball_y = ball_y + rand()%4-2;
}
else
{
printf ("游戏失败\n");
system ("pause");
exit (0);
}
}
if ((ball_x == block_x) && (ball_y == block_y))
{
score++;
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 - ridus;
right = position_y + ridus;
}
if (input == 'd')
{
position_y ++;
left = position_y - ridus;
right = position_y + ridus;
}
}
}
int main ()
{
startup ();
while (1)
{
show ();
updateWithoutInput ();
updateWithInput ();
}
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/1b06f65d234a2c99b6419eac2cb8e8ef.png)