飞翔的小鸟游戏设计
首先需要包含以下库:
#include<stdio.h>
#include<windows.h>
#include<stdlib.h> //包含system
#include<conio.h>
设置窗口大小:
#define WIDTH 50
#define HEIGHT 16
设置鸟的结构:
struct bird
{
bool live;
int x,y;
int speed;
int score;
int step;
}bird;
设置洞/墙的结构:
struct hole
{
int size;
int yBegin;
}hole;
定义全局变量:
char map[HEIGHT - 1][WIDTH];
int scoreMax = 0;
游戏初始化设置:
void GameInit()
{
srand(GetTickCount());
//窗口
char cmd[128];
sprintf(cmd, "mode con cols=%d lines=%d", WIDTH, HEIGHT);
system(cmd); //将cmd窗口设定为指定大小,其中cols指定为列数,lines指定为行数。
system("title flappy bird"); //标题
//地图清零
for (int i = 0; i < HEIGHT - 1; i++)
{
for (int j = 0; j < WIDTH; j++)
{
map[i][j] = ' ';
}
}
//鸟初始化
bird.live = true;
bird.score = 0;
bird.step = 0;
bird.x = 7, bird.y = 7;
bird.speed = 1;
map[bird.y][bird.x] = '*';
//洞
hole.size = 7;
//开始画面
for (int i = 0; i < HEIGHT - 1; i++)
{
for (int j = 0; j < WIDTH; j++)
{
putchar(map[i][j]);
}
putchar(10);//换行
}
printf("\t你的分数:%d\t最高分:%d 按N键起飞", bird.score, scoreMax);
while (!GetAsyncKeyState('N'));
}
创建墙的机制:
void CreateWall()
{
if (bird.step % 20 == 0)//过一段距离创建墙
{
hole.yBegin = rand() % 8 + 3;
for (int i = 0; i < HEIGHT - 1; i++)
{
if (i < hole.yBegin || i >= hole.yBegin + hole.size)map[i][49] = '#';
else map[i][49] = ' ';
}
}
}
墙向左移动的机制:
void WallMove()
{
for (int j = 0; j < WIDTH; j++)
{
if (map[0][j] == '#')//有墙
{
if (j == 0)//墙到头
for (int k = 0; k < HEIGHT - 1; k++)
map[k][j] = ' ';
else//墙没到头
{
for (int k = 0; k < HEIGHT - 1; k++)
{
if (map[k][j] == '#')
{
map[k][j - 1] = '#';
map[k][j] = ' ';
}
}
//鸟穿过墙
if (j == bird.x)bird.score++;
}
}
}
//更新最高分数
scoreMax = bird.score > scoreMax ? bird.score : scoreMax;
//增大难度
if (bird.step % 100 == 0)
{
hole.size--;
if (hole.size == 0)hole.size = 1;
}
bird.step++;//墙左移,鸟级数+1
}
鸟上下移动的机制:
void BirdMove()
{
if (GetAsyncKeyState(VK_SPACE))//上升
{
bird.y -= bird.speed;
if (map[bird.y][bird.x] == '#'){bird.live = false; return;}//撞墙判断
map[bird.y][bird.x] = '*';
map[bird.y+ bird.speed][bird.x] = ' ';
}
else//下降
{
bird.y += bird.speed;
if (map[bird.y][bird.x] == '#'){bird.live = false; return;}//撞墙判断
map[bird.y][bird.x] = '*';
map[bird.y - bird.speed][bird.x] = ' ';
}
//越界判断
if(bird.y>=HEIGHT|| bird.y <= 0)bird.live = false;
}
窗口需要实时更新,实现画面的连续性:
void DrawGame()
{
system("cls");//画面是一块一块输出的
//输出字符
for (int i = 0; i < HEIGHT - 1; i++)
{
for (int j = 0; j < WIDTH; j++)
{
putchar(map[i][j]);
}
putchar(10);//换行
}
printf("\t你的分数:%d\t最高分:%d 芜湖~~~", bird.score, scoreMax);
}
执行主函数:
int main()
{
while (1)
{
GameInit();
while (bird.live)
{
DrawGame();
BirdMove();
CreateWall();
WallMove();
Sleep(100);
}
system("cls");
printf("\n\n\t你鸟没了!\n\n\t你的分数:%d\t最高分:%d\n\n", bird.score, scoreMax);
printf("\t\t按B键重新开始");
while (!GetAsyncKeyState('B'));
}
system("pause");
return 0;
}
结果: