C语言游戏开发——反弹球
1.划定一块区域,小球在其中运动,碰到边框会反弹,通过判断是否触底来决定是否结束游戏,玩家通过w,a,s,d来控制反弹板的运动,来反弹小球避免游戏失败。
2.在startup()函数中来改变游戏区域的大小以及反弹板的大小等参数
3.在Sleep(50);这个语句中更改游戏速度
4.以下为游戏主体代码。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
int high, width;
int ball_x, ball_y;
int vx, vy;
int px, py;
int r;
int left, right;
int number;
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 startup()
{
high = 15;
width = 20;
ball_x = 0;
ball_y = width / 2;
vx = 1;
vy = 1;
r = 4;
px = high;
py = width / 2;
left = py - r;
right = py + r;
number = 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("o");
else if (j == width)
printf("|");
else if (i == high+1)
printf("-");
else if ((i == high ) && (j>=left)&&(j <=right))
printf("*");
else printf(" ");
}
printf("\n");
}
printf("反弹小球数:%d", number);
}
void inputwithout()
{
if (ball_x==high-1)
{
if ((ball_y >= left) && (ball_y <= right))
{
number++;
}
else
{
printf("游戏失败");
system("pause");
exit(0);
}
}
ball_x = ball_x + vx;
ball_y = ball_y + vy;
if ((ball_x == 0) || (ball_x == high - 1))
{
vx = -vx;
}
if ((ball_y == 0) || (ball_y == width - 1))
{
vy = -vy;
}
Sleep(50);
}
void inputwith()
{
char input;
if (_kbhit())
{
input = _getch();
if (input=='a')
{
py--;
left = py - r;
right = py + r;
}
if (input=='d')
{
py++;
left = py - r;
right = py + r;
}
}
}
int main()
{
startup();
while (1)
{
show();
inputwithout();
inputwith();
}
return 0;
}
代码通过几个函数来实现游戏的主体功能。