用java制作放烟花的程序
时间: 2023-07-16 15:14:42 浏览: 56
下面是一个简单的 Java 程序,用于绘制放烟花的效果:
```java
import java.awt.*;
import javax.swing.*;
public class Fireworks extends JPanel {
private final int MAX_PARTICLES = 1000; // 最大粒子数
private Particle[] particles; // 粒子数组
private int numParticles; // 当前粒子数
public Fireworks() {
setPreferredSize(new Dimension(500, 500));
setBackground(Color.BLACK);
particles = new Particle[MAX_PARTICLES];
numParticles = 0;
}
public void addParticle(int x, int y, Color color) {
if (numParticles < MAX_PARTICLES) {
particles[numParticles++] = new Particle(x, y, color);
}
}
public void update() {
for (int i = 0; i < numParticles; i++) {
if (!particles[i].update()) {
particles[i] = particles[--numParticles];
particles[numParticles] = null;
}
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < numParticles; i++) {
particles[i].draw(g);
}
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Fireworks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fireworks fireworks = new Fireworks();
frame.add(fireworks);
frame.pack();
frame.setVisible(true);
while (true) {
fireworks.addParticle((int) (Math.random() * fireworks.getWidth()),
(int) (Math.random() * fireworks.getHeight()),
new Color((int) (Math.random() * 256),
(int) (Math.random() * 256),
(int) (Math.random() * 256)));
fireworks.update();
fireworks.repaint();
Thread.sleep(10);
}
}
private static class Particle {
private int x, y; // 粒子位置
private int dx, dy; // 粒子速度
private Color color; // 粒子颜色
private int life; // 粒子寿命
public Particle(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
dx = (int) (Math.random() * 11) - 5;
dy = (int) (Math.random() * 11) - 5;
life = (int) (Math.random() * 51) + 50;
}
public boolean update() {
x += dx;
y += dy;
life--;
return life > 0;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x, y, 5, 5);
}
}
}
```
这个程序使用了 Java 的 Swing 组件来绘制图形,通过重写 `paintComponent` 方法来绘制粒子效果。程序会不断地在窗口中添加粒子,并在每一帧更新所有粒子的位置和寿命,最后再绘制出来。