在学习数组之前,我们再做一个好玩的游戏:flappy bird。大家可以按照上一个教程中空战游戏的思路,先按照我们的提示,逐步地实现,如果有困难,再参考我们分步骤的代码,这样的锻炼效果最好。
备注:#include <windows.h> 或者 #include <cwindows.h>,大家测试下选适合自己编译器的版本。
第一步,实现一个简单下落的小鸟,实际上和飞机游戏中下落的敌机类似的效果。按空格键后,小鸟上升。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <cwindow.h>
// 全局变量
int high,width; // 游戏画面大小
int bird_x,bird_y; // 小鸟的坐标
int bar1_y,bar1_xDown,bar1_xTop; // 障碍物
void gotoxy(int x,int y)//类似于清屏函数
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle,pos);
}
void startup() // 数据初始化
{
high = 15;
width = 20;
bird_x = 0;
bird_y = width/3;
}
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
printf(" "); // 输出空格
}
printf("\n");
}
}
void updateWithoutInput() // 与用户输入无关的更新
{
bird_x ++;
Sleep(150);
}
void updateWithInput() // 与用户输入有关的更新
{
char input;
if(kbhit()) // 判断是否有输入
{
input = getch(); // 根据用户的不同输入来移动,不必输入回车
if (input == ' ')
{
bird_x = bird_x - 2;
}
}
}
void main()
{
startup(); // 数据初始化
while (1) // 游戏循环执行
{
show(); // 显示画面
updateWithoutInput(); // 与用户输入无关的更新
updateWithInput(); // 与用户输入有关的更新
}
}
第二步,同时实现下落的小鸟和静止障碍物的显示,注意为了刻画障碍物的位置、中间缝隙的大小,需要多个变量。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <cwindow.h>
// 全局变量
int high,width; // 游戏画面大小
int bird_x,bird_y; // 小鸟的坐标
int bar1_y,bar1_xDown,bar1_xTop; // 障碍物的相关坐标
void gotoxy(int x,int y