C语言实现飞翔的小鸟游戏
操纵小鸟使其不要掉下来或着撞上烟囱
windows平台实现
代码如下:
game.h:
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
void HideCursor();
void gotoxy(int x, int y);
void DataInit();
void Show();
void UpdateWithoutInput();
void UpdateWithInput();
test.cpp:
#include "game.h"
int high;
int width;
int bird_x_v;
int bird_x;
int bird_y;
int board_x_top;
int board_x_bot;
int board_y;
int score;
int main()
{
DataInit(); //数据初始化
while (1)
{
Show(); //显示画面
UpdateWithoutInput(); //与用户无关的数据更新
UpdateWithInput(); //与用户有关的数据更新
}
return 0;
}
game.cpp:
#include "game.h"
extern int high;
extern int width;
extern int bird_x_v;
extern int bird_x;
extern int bird_y;
extern int board_x_top;
extern int board_x_bot;
extern int board_y;
extern int score;
void DataInit()
{
high = 20;
width = 20;
bird_y = 2;
bird_x = high / 2;
bird_x_v = 1;
board_y = width;
board_x_top = high / 3;
board_x_bot = board_x_top + 5;
score = 0;
HideCursor();
}
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(j == board_y && (i <= board_x_top || i >= board_x_bot))
printf("#");
else
printf(" ");
}
printf("\n");
}
printf("SCORE: %d\n", score);
}
void UpdateWithoutInput()
{
bird_x += bird_x_v;
board_y--;
if (bird_y == board_y )
{
if (bird_x >= board_x_top && bird_x <= board_x_bot)
{
score++;
}
else
{
printf("WASTED!!!\n");
system("pause");
exit(-1);
}
}
if (board_y == 0)
{
board_y = width;
int tmp = rand() % (high - 5);
board_x_top = tmp;
board_x_bot = tmp + high / 4;
}
Sleep(150);
}
void UpdateWithInput()
{
char input;
if (_kbhit())
{
input = _getch();
if (input == ' ')
bird_x -= 2;
}
}
fix.cpp:
主要用来修复cls所带来的闪屏问题
#include "game.h"
void HideCursor()
{
CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void gotoxy(int x, int y)
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}