写一段Java烟花代码
时间: 2023-05-20 11:03:11 浏览: 304
以下是一段简单的Java烟花代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Fireworks extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private ArrayList<Particle> particles;
private Random rand;
private int width, height;
public Fireworks(int width, int height) {
this.width = width;
this.height = height;
particles = new ArrayList<Particle>();
rand = new Random();
}
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (rand.nextInt(100) < 10) {
particles.add(new Particle(rand.nextInt(width), height));
}
for (int i = 0; i < particles.size(); i++) {
Particle p = particles.get(i);
if (p.isDead()) {
particles.remove(i);
} else {
p.update();
}
}
repaint();
}
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
for (Particle p : particles) {
p.draw(g);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fireworks");
Fireworks fireworks = new Fireworks(800, 600);
frame.add(fireworks);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
new Thread(fireworks).start();
}
}
class Particle {
private int x, y, vx, vy, age, maxAge;
private Color color;
public Particle(int x, int y) {
this.x = x;
this.y = y;
vx = (int) (Math.random() * 10) - 5;
vy = (int) (Math.random() * -20) - 10;
age = 0;
maxAge = (int) (Math.random() * 100) + 100;
color = new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255));
}
public void update() {
x += vx;
y += vy;
vy += 1;
age++;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x, y, 5, 5);
}
public boolean isDead() {
return age >= maxAge;
}
}
```
这段代码实现了一个简单的烟花效果,每隔一段时间会产生一个新的烟花,烟花会向上运动并产生许多彩色的粒子。