c語言碰撞小球
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define High 15? // 游戲畫面尺寸
#define Width 20
// 全局變量
int ball_x,ball_y; // 小球的坐標
int ball_vx,ball_vy; // 小球的速度
int position_x,position_y; // 擋板中心坐標
int ridus;? // 擋板半徑大小
int left,right; // 擋板左右位置
int canvas[High][Width] = {0}; // 二維數(shù)組存儲游戲畫布中對應的元素
// 0為空格,1為小球O,2為擋板*,3為方塊#
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()? // 數(shù)據(jù)初始化
{
HideCursor();
ridus = 5;
position_x = High-1;
position_y = Width/2;
left = position_y - ridus;
right = position_y + ridus;
ball_x = position_x-1;
ball_y = position_y;
ball_vx = -1;
ball_vy = 1;
canvas[ball_x][ball_y] = 1;
int k,i;
for (k=left;k<=right;k++)? // 擋板
canvas[position_x][k] = 2;
for (k=0;k<Width;k++)? // 加幾排磚塊
for (i=0;i<High/4;i++)??
canvas[i][k] = 3;
}
void show()? // 顯示畫面
{
gotoxy(0,0);? ? // 光標移動到原點位置,以下重畫清屏
int i,j;
for (i=0;i<High;i++)
{
for (j=0;j<Width;j++)
{
if (canvas[i][j]==0)
printf(" ");? ?//? ?輸出空格
else if (canvas[i][j]==1)
printf("0");? ?//? ?輸出小球0
else if (canvas[i][j]==2)
printf("*");? ?//? ?輸出擋板*
else if (canvas[i][j]==3)
printf("#");? ?//? ?輸出磚塊#
}
printf("|\n"); // 顯示右邊界
}
for (j=0;j<Width;j++)
printf("-"); // 顯示下邊界
printf("\n");
}
void updateWithoutInput()? // 與用戶輸入無關的更新
{
if (ball_x==High-2)
{
if ( (ball_y>=left) && (ball_y<=right) )? ?// 被擋板擋住
{
}
else? ? // 沒有被擋板擋住
{
printf("游戲失敗\n");
system("pause");
exit(0);
}
}
static int speed = 0;??
if (speed<7)
speed++;
if (speed == 7)
{
speed = 0;
canvas[ball_x][ball_y] = 0;
// 更新小球坐標
ball_x = ball_x + ball_vx;
ball_y = ball_y + ball_vy;
canvas[ball_x][ball_y] = 1;
// 碰到邊界后反彈
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 (canvas[ball_x-1][ball_y]==3)
{
ball_vx = -ball_vx;
canvas[ball_x-1][ball_y] = 0;
printf("\a");
}
}
}
void updateWithInput()? // 與用戶輸入有關的更新
{
char input;
if(kbhit())? // 判斷是否有輸入
{
input = getch();? // 根據(jù)用戶的不同輸入來移動,不必輸入回車
if (input == 'a' && left>0)? ?
{
canvas[position_x][right] = 0;
position_y--;? // 位置左移
left = position_y - ridus;
right = position_y + ridus;
canvas[position_x][left] = 2;
}
if (input == 'd' && right<Width-1)
{
canvas[position_x][left] = 0;
position_y++;? // 位置右移
left = position_y - ridus;
right = position_y + ridus;
canvas[position_x][right] = 2;
}
}
}
int main()
{
startup();? // 數(shù)據(jù)初始化
while (1)? //? 游戲循環(huán)執(zhí)行
{
show();? // 顯示畫面
updateWithoutInput();? // 與用戶輸入無關的更新
updateWithInput();? ? ?// 與用戶輸入有關的更新
}
return 0;
}