c++2025新年烟花代码可复制
时间: 2024-12-31 21:45:16 浏览: 15
### C++代码实现新年2025烟花效果
为了创建一个模拟烟花的效果,可以利用图形库如SFML或OpenGL。下面是一个基于SFML的简单示例程序[^1]:
```cpp
#include <SFML/Graphics.hpp>
#include <vector>
#include <cstdlib>
#include <ctime>
struct Firework {
sf::CircleShape shape;
float lifeTime;
};
int main() {
srand(static_cast<unsigned int>(time(0)));
sf::RenderWindow window(sf::VideoMode(800, 600), "New Year 2025 Fireworks");
std::vector<Firework> fireworks;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
// Add new firework every few frames randomly
if ((rand() % 100) < 3) {
Firework fw;
fw.shape.setRadius(rand() % 10 + 5);
fw.shape.setPosition(rand() % 800, rand() % 600);
fw.shape.setFillColor(sf::Color(rand() % 256, rand() % 256, rand() % 256));
fw.lifeTime = static_cast<float>(rand() % 50) / 10.f + .5f; // Random lifetime between 0.5s and 1s
fireworks.push_back(fw);
}
for (auto& f : fireworks) {
f.lifeTime -= 0.02f;
if (f.lifeTime <= 0) {
f.shape.setScale(f.lifeTime * 2, f.lifeTime * 2); // Shrink as it fades out
}
}
// Remove expired particles
fireworks.erase(std::remove_if(fireworks.begin(), fireworks.end(),
[](const Firework &fw){return fw.lifeTime <= 0;}),
fireworks.end());
window.clear();
for (auto& f : fireworks) {
window.draw(f.shape);
}
window.display();
sf::sleep(sf::milliseconds(20)); // Control frame rate
}
return 0;
}
```
这段代码展示了如何使用SFML绘制圆形代表烟花,并通过随机位置、颜色和大小让它们看起来像真实的烟火爆炸。随着时间推移,这些圆会逐渐缩小并消失。
阅读全文