C语言小游戏--飞翔的小鸟(详解)

引言

本文基于C语言代码,编写的一个小游戏,代码运行后,小鸟将会自动坠落,只有摁下空格的时候小鸟才会上升。在飞行过程中小鸟也会遇到各种障碍。度过障碍则会加分。

代码分析

代码主函数

1初始化数据
2死循环
3绘制图画
4用户无关的数据更新
5用户有关得数据更新
重新进入步骤3

编译环境

本文引用头文件

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>

相关头文件函数分析请查阅作者相关博客.

全局变量

封装函数故,在设置全局变量,以便在相应得函数能够更改变量值

//全局变量
int high, width;					//游戏的画面大小
int bird_x, bird_y;					//小鸟的坐标
int barl_y, barl_xDown, barl_xTop;	//障碍物
int score;							//得分

优化图像

system(“cls”)由于会导致图像闪烁所以我们使用了重绘画这一方法

// 光标移到(X, Y)位置
void gotoxy(int x, int 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()
{
	high = 15;
	width = 20;
	bird_x = 0;
	bird_y = width / 3;
	barl_y = width ;
	barl_xDown = high / 3;
	barl_xTop = width / 3;
	score = 0;
}

绘画图像


//显示画面
void show()
{
	gotoxy(0, 0);
	int i, j;

	for (i = 0; i <= high; i++)
	{
		for (j = 0; j <= width; j++)
		{
			if (i == bird_x && j == bird_y)
				printf("@");	//输出小鸟
			else if (i == high)
				printf("-");
			else if (j == width)
				printf("|");
			else if (j == barl_y && (i<barl_xDown || i>barl_xTop))
				printf("*");	//输出障碍物
			else
				printf(" ");	//输出空格
		}
		printf("\n");
	}
	printf("得分:%d\n", score);
}

用户无关的更新

比如图象中的障碍左移动,小鸟下坠,分数判断以及游戏是否能够继续


//与用户无关的输出
void updateWithoutInput()
{
	bird_x++;
	barl_y--;
	if (bird_y == barl_y)
	{
		if (bird_x >= barl_xDown && bird_x <= barl_xTop)
			score++;
		else
		{
			printf("游戏失败\n");
			system("pause");
			exit(0);
		}
	}
	if (bird_x == high)
	{
		printf("游戏失败\n");
		system("pause");
		exit(0);
	}
	if (barl_y <= 0)
	{
		barl_y = width;
		int temp = rand() % (int)(high * 0.8);
		barl_xDown = temp - high / 10;
		barl_xTop = temp + high / 10;
	}
	Sleep(150);
}

与用户有关得更新

很明显在游戏中与用户有关的则是用户按下空格键,小鸟上升

///与用户输入有关的更行
void updateWithInput()
{
	char input;
	if (_kbhit())
	{
		input = _getch();
		if (bird_x > 1 && input == ' ')
			bird_x = bird_x - 2;
	}
}

主函数

int main()
{
	HideCursor();//隐藏光标
	startup();
	while (1)
	{
		show();
		updateWithoutInput();
		updateWithInput();
	}
	return 0;
}

完整代码:https://blog.csdn.net/Liu1_1_/article/details/133988177

后续

若对代码含有疑问,可以查阅作者相关的详解代码,或是私聊作者,感谢点赞

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值