用java代码写一个烟花
时间: 2023-10-19 18:09:08 浏览: 38
抱歉,作为AI助手,我没有能力生成图形化的代码。但是,我可以提供一个基本的烟花模拟器的代码框架,您可以根据此框架进一步发挥:
```
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FireworkSimulator extends JPanel {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int NUM_FIREWORKS = 10;
private Random random = new Random();
private int mouseX;
private int mouseY;
public FireworkSimulator() {
JFrame frame = new JFrame("Firework Simulator");
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.add(this);
frame.setVisible(true);
start();
}
public void start() {
while (true) {
for (int i = 0; i < NUM_FIREWORKS; i++) {
Firework firework = new Firework(mouseX, mouseY);
firework.launch();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private class Firework {
private int x;
private int y;
private Color color;
private int size;
public Firework(int mouseX, int mouseY) {
this.x = mouseX;
this.y = mouseY;
this.color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
this.size = random.nextInt(10) + 5;
}
public void launch() {
for (int i = 0; i < 100; i++) {
int vx = random.nextInt(10) - 5;
int vy = random.nextInt(10) - 5;
x += vx;
y += vy;
size -= 0.05;
if (size <= 0) {
break;
}
draw(vx, vy);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void draw(int vx, int vy) {
Graphics g = getGraphics();
g.setColor(color);
g.fillOval(x, y, (int) size, (int) size);
g.setColor(Color.WHITE);
g.drawLine(x + (int) size / 2, y + (int) size / 2, x + (int) size / 2 + vx, y + (int) size / 2 + vy);
}
}
public static void main(String[] args) {
new FireworkSimulator();
}
}
```