C语言游戏开发——反弹球

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;
}

代码通过几个函数来实现游戏的主体功能。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值