java烟花代码
时间: 2023-07-02 19:21:02 浏览: 538
以下是一个简单的 Java 烟花代码示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Firework extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Timer timer;
private ArrayList<Particle> particles;
private Random random;
public Firework() {
setPreferredSize(new java.awt.Dimension(600, 400));
setBackground(Color.BLACK);
timer = new Timer(20, this);
timer.start();
particles = new ArrayList<>();
random = new Random();
}
@Override
public void actionPerformed(ActionEvent e) {
particles.add(new Particle(getWidth() / 2, getHeight() - 10, random.nextFloat() * 10 - 5, random.nextFloat() * -10 - 5, random.nextFloat() * 0.2f + 0.1f, random.nextInt(255), random.nextInt(255), random.nextInt(255)));
for (int i = 0; i < particles.size(); i++) {
Particle p = particles.get(i);
p.update();
if (p.isDead()) {
particles.remove(i);
i--;
}
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Particle p : particles) {
g.setColor(new Color(p.getRed(), p.getGreen(), p.getBlue()));
g.fillOval((int) p.getX(), (int) p.getY(), 10, 10);
}
}
private static class Particle {
private float x, y, vx, vy, life, r, g, b;
public Particle(float x, float y, float vx, float vy, float life, int r, int g, int b) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.life = life;
this.r = r;
this.g = g;
this.b = b;
}
public void update() {
x += vx;
y += vy;
vy += 0.1f;
life -= 0.01f;
}
public boolean isDead() {
return life <= 0;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public int getRed() {
return (int) r;
}
public int getGreen() {
return (int) g;
}
public int getBlue() {
return (int) b;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Firework");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Firework());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这个程序创建了一个窗口,在其中绘制烟花效果。每个烟花被表示为一个由颜色、位置、速度和寿命组成的粒子。程序每隔一定时间添加一个新的烟花,然后更新和绘制所有粒子。
阅读全文