flappy bird的c++代码
时间: 2023-09-10 12:13:32 浏览: 79
以下是一个简单的 Flappy Bird 游戏的 C++ 代码示例:
```c++
#include<iostream>
#include<conio.h>
#include<cstdlib>
#include<ctime>
#include<windows.h>
using namespace std;
bool gameOver; // 游戏结束标志
const int width = 20; // 游戏宽度
const int height = 20; // 游戏高度
int x, y; // 玩家坐标
int fruitX, fruitY; // 水果坐标
int score; // 分数
int tailX[100], tailY[100]; // 尾巴坐标
int nTail; // 尾巴长度
enum eDirection {STOP = 0, LEFT, RIGHT, UP, DOWN}; // 方向枚举
eDirection dir;
void Setup() // 初始设置
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw() // 绘制游戏画面
{
system("cls"); // 清空屏幕
// 绘制上边框
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
// 绘制游戏区域
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (j == 0)
cout << "#";
if (i == y && j == x) // 绘制玩家
cout << "O";
else if (i == fruitY && j == fruitX) // 绘制水果
cout << "F";
else
{
bool print = false;
for (int k = 0; k < nTail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "o"; // 绘制尾巴
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "#";
}
cout << endl;
}
// 绘制下边框
for (int i = 0; i < width + 2; i++)
cout << "#";
cout << endl;
// 显示分数
cout << "Score:" << score << endl;
}
void Input() // 处理输入
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() // 逻辑处理
{
// 处理尾巴
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
// 处理方向
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
// 处理撞墙
if (x >= width || x < 0 || y >= height || y < 0)
gameOver = true;
// 处理撞尾巴
for (int i = 0; i < nTail; i++)
{
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
}
// 处理吃水果
if (x == fruitX && y == fruitY)
{
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
int main()
{
srand(time(0)); // 随机数种子
Setup(); // 初始设置
while (!gameOver)
{
Draw(); // 绘制游戏画面
Input(); // 处理输入
Logic(); // 处理逻辑
Sleep(100); // 暂停100毫秒
}
return 0;
}
```
注意:该代码仅供学习和参考,不保证完全正确和可运行。