C_ 反弹球小游戏

头文件和全局变量

#include<stdio.h>
#include<conio.h>
#include<Windows.h>

//全局变量
int high, width;//画布
int ball_x, ball_y;//小球
int ballvx, ballvy;//速度
int postion_x, postion_y;//挡板
int radius;//半径
int right, left;//左右边界
int ball_number;

防闪屏和隐藏鼠标

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 };
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

初始化

void Starsup() {//初始化
	HideCursor();
	high = 18;
	width = 25;
	ball_x = 1;
	ball_y = width/2;
	ballvx = 1;
	ballvy = 1;
	postion_x = high-1;
	postion_y = width/2;
	radius = 5;
	left = postion_y - radius;
	right = postion_y + radius;
	ball_number = 0;
}

主界面显示

void Show() {//显示
	gotoxy(0, 0);//防闪屏
	int i, j;
	for (i = 0; i <= high; i++) {//纵坐标
		for (j = 0; j <= width; j++)//横坐标
		{
			if ((i == ball_x) && (j == ball_y))//只有在这个位置才会输出飞机
				printf("*");
			else if (i == high || i == 0)//上下边界
				printf("-");
			else if (j == width || j == 0)//左右边界
				printf("|");
			else if (i == postion_x && j <= right && j >= left)//挡板
				printf("*");
			else printf(" ");
		}
		printf("\n");
	}
	printf("小球击中数:%d\n",ball_number);
}

后台操作

void Back() {//后台


	if (ball_x == postion_x)//小球集中挡板
	{
		if (ball_y <= right && ball_y >= left) {
			ball_number++;
			ballvy = -ballvy;
		}
		else
		{
			printf("Game Over\n");
			exit(0);
		}
	}
	ball_x = ball_x + ballvx;
	ball_y = ball_y + ballvy;
	if (ball_x == 0 || ball_x == high-1)
		ballvx = -ballvx;
	if (ball_y == 0 || ball_y == width-1)
		ballvy = -ballvy;
	Sleep(80);
}

人机交互

void Front() {//用户
	char input;
	if (kbhit()) {//如果有按键输入
		input = getch();//这两个函数都在conion中
		if (input == 'a') {
			postion_y--;
			left = postion_y - radius;
			right = postion_y + radius;
		}
		if (input == 'd') {
			postion_y++;
			left = postion_y - radius;
			right = postion_y + radius;
			}
	}
}

主界面

int main() {
	Starsup();
	while (1) {
		Show();
		Back();
		Front();
	}


}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值