windows GDI 控制台小游戏flappy bird

曾经很火的小游戏flappy bird, 玩的都有点上瘾,如今在火车上无聊,也自己写一个简化版的。

游戏的实现方法是在创建鸟和柱子的类,鸟始终在一个x坐标点上,高度y的变化符合自由落体,而柱子以恒定速度向-x方向移动,使得看起来鸟是以抛物线移动,每当按下空格,鸟就获得一个向上的速度,当纵向速度为0后开始加速下落。

先看柱子的类

 
 
class Column
{
public:
	Column(void);
	virtual ~Column(void);
public:
	double vx;//speed on x axis
	double x; //horizontal position
	double height; //height of the lower column
	double gapheight; //gap between upper and lower column
	double width; //width of the column
public:
	void move(); //flash the column position on x-axis
	void draw(); //draw the column
};

其中两个方法都很简单,move就是根据vx更新x坐标。draw画出上下两个柱子。

看小鸟类:

 
 
class Bird
{
public:
	int birddot[2][5][5]; //the shape of the bird
	double vx,vy; //speed on two axis
	double x,y;   //x,y location
	double g;     //gravity, indicate the acceleration of the falling speed 
	double upa;   //the speed when press the space key
	int birdstate;
public:
	void jump();  //when pressing the space key, it will change y-axis speed "vy" to "upa"
	void move();  //flash the bird's position
	void drawBD(); //draw the bird
	void changeBdSt(); //change the bird's posture
public:
	Bird(void);
	virtual ~Bird(void);
};

由于是控制台绘图,所以小鸟的形状是用像素块画出来的,为了让小鸟生动一点,用了两个形态表示翅膀的扇动,如图:

所以小鸟的姿态用了2*5*5的三维数组。

游戏逻辑在game.cpp中实现:

 
 
//judge whether the bird has hit the pillar
bool ifGameover();
//change the columns's positions
void movecolumn();
//draw background, paint it to black and draw the frame
void drawBG();
//put out text in console window
void PutOutText(char* lpsz, int X, int Y, unsigned long fontcolor);
//print the current game result and status
void printResult();

由于按键少(就一个空格键),所以消息处理回调函数里的分支相对其他小游戏少很多。

重绘消息

 
 
case WM_PAINT:
	hdc = BeginPaint(hWnd, &ps);
	// TODO: 在此添加任意绘图代码...
	EndPaint(hWnd, &ps);
	break;

定时消息

 
 
case WM_TIMER:
	if (wParam == ID_TIMER)
	{
		KillTimer(hWnd, ID_TIMER);
		bdstctn++;
		bdstctn %=4;
		if(bdstctn ==3 ) pbird->changeBdSt();

		drawBG();
		pbird->move();
		movecolumn();
		if(ifGameover()){
			MessageBoxA(hwndtxt, "Game Over", "Ah..ou", MB_OK);
			ifStart = 0;
			delete pbird;
			int i;
			for(i=0;i<colctn;i++){
				delete pcol[i];
			}
		}
		else{
			pbird->drawBD();
			SetTimer(hWnd, ID_TIMER, INTERVAL, NULL);
		}
		printResult();
	}
	break;

按键消息

 
 
case WM_CHAR:
	switch (wParam)
	{
	case 'f':
	case 'F':
		if (!ifStart){
			ifStart = 1;
			pbird = new Bird; 
			drawBG();
			pbird->drawBD();
			pcol[0] = new Column;
			colctn = 1;
			bdstctn = 0;
			score = 0;
			SetTimer(hWnd, ID_TIMER,INTERVAL, NULL);
			printResult();
		}
		break;
	case 'p':
	case 'P':
		if (!ifStart)break;
		ifPause = ifPause == 0 ? 1 : 0;
		if (ifPause){
			KillTimer(hWnd, ID_TIMER);
		}
		else{
			SetTimer(hWnd, ID_TIMER, INTERVAL, NULL);
		}
		printResult();
		break;
	case ' ':
	case 'j':
	case 'J':
		if(ifStart&&!ifPause)
			pbird->jump();
	}
	break;

游戏效果图:

源码地址:

PixelBird

原博客:

http://www.straka.cn/blog/console-flappy-bird/

猜你喜欢

转载自blog.csdn.net/atp1992/article/details/80960256