C++ Flappy Bird 游戏示例:使用 SFML 库
下面是一个使用 C++ 和 SFML 库编写的简单的 Flappy Bird 游戏示例:
#include <SFML/Graphics.hpp>
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int PIPE_WIDTH = 100;
const int PIPE_HEIGHT = 400;
const int PIPE_GAP = 200;
const float GRAVITY = 0.5f;
const float JUMP_FORCE = 10.0f;
class Bird {
public:
Bird(float x, float y) {
shape.setPosition(x, y);
shape.setRadius(20);
shape.setFillColor(sf::Color::Yellow);
}
void update() {
velocity += GRAVITY;
shape.move(0, velocity);
}
void jump() {
velocity = -JUMP_FORCE;
}
sf::CircleShape shape;
float velocity = 0;
};
class Pipe {
public:
Pipe(float x, float y) {
topPipe.setPosition(x, y - PIPE_HEIGHT);
topPipe.setSize(sf::Vector2f(PIPE_WIDTH, PIPE_HEIGHT));
topPipe.setFillColor(sf::Color::Green);
bottomPipe.setPosition(x, y + PIPE_GAP);
bottomPipe.setSize(sf::Vector2f(PIPE_WIDTH, PIPE_HEIGHT));
bottomPipe.setFillColor(sf::Color::Green);
}
void update() {
topPipe.move(-2, 0);
bottomPipe.move(-2, 0);
}
sf::RectangleShape topPipe;
sf::RectangleShape bottomPipe;
};
int main() {
sf::RenderWindow window(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), 'Flappy Bird');
Bird bird(100, SCREEN_HEIGHT / 2);
std::vector<Pipe> pipes;
pipes.push_back(Pipe(SCREEN_WIDTH, SCREEN_HEIGHT / 2));
sf::Clock clock;
float deltaTime = 0.0f;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Space)
bird.jump();
}
}
deltaTime = clock.restart().asSeconds();
bird.update();
for (auto& pipe : pipes) {
pipe.update();
if (pipe.topPipe.getPosition().x < -PIPE_WIDTH) {
pipes.erase(pipes.begin());
pipes.push_back(Pipe(SCREEN_WIDTH, rand() % (SCREEN_HEIGHT - PIPE_HEIGHT - PIPE_GAP)));
}
}
if (bird.shape.getPosition().y + bird.shape.getRadius() > SCREEN_HEIGHT || bird.shape.getPosition().y < 0) {
// 游戏结束
return 0;
}
window.clear();
window.draw(bird.shape);
for (auto& pipe : pipes) {
window.draw(pipe.topPipe);
window.draw(pipe.bottomPipe);
}
window.display();
}
return 0;
}
这只是一个简单的示例,游戏逻辑和图形都很简单。你可以根据自己的需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/pfUe 著作权归作者所有。请勿转载和采集!