用java编写一个放烟花
时间: 2023-06-19 22:10:45 浏览: 98
以下是一个简单的Java代码示例,用于放烟花:
```java
import java.awt.Color;
import java.awt.Graphics;
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 int xPos;
private int yPos;
private int[] xPoints = new int[5];
private int[] yPoints = new int[5];
private Color color;
private boolean exploded;
private Random random;
public Fireworks() {
random = new Random();
xPos = random.nextInt(800);
yPos = random.nextInt(600);
color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
exploded = false;
for (int i = 0; i < 5; i++) {
xPoints[i] = xPos;
yPoints[i] = yPos;
}
}
public void run() {
while (!exploded) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
yPos += random.nextInt(5) + 1;
if (yPos > 500) {
explode();
}
repaint();
}
}
private void explode() {
exploded = true;
for (int i = 0; i < 5; i++) {
xPoints[i] = xPos;
yPoints[i] = yPos;
Thread thread = new Thread(new Explosion(xPoints[i], yPoints[i], color));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillOval(xPos, yPos, 10, 10);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Fireworks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
JPanel panel = new JPanel();
panel.setLayout(null);
for (int i = 0; i < 20; i++) {
Fireworks fireworks = new Fireworks();
fireworks.setBounds(0, 0, 800, 600);
panel.add(fireworks);
Thread thread = new Thread(fireworks);
thread.start();
}
frame.add(panel);
frame.setVisible(true);
}
}
class Explosion implements Runnable {
private int xPos;
private int yPos;
private Color color;
private Random random;
public Explosion(int xPos, int yPos, Color color) {
this.xPos = xPos;
this.yPos = yPos;
this.color = color;
random = new Random();
}
public void run() {
Graphics g = Fireworks.getGraphics();
for (int i = 0; i < 50; i++) {
int x = xPos + random.nextInt(101) - 50;
int y = yPos + random.nextInt(101) - 50;
g.setColor(color);
g.fillOval(x, y, 10, 10);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个代码会创建一个显示烟花的窗口。在窗口中,会同时放置多个烟花,并且每个烟花都会按照一定的速度向下移动,直到达到一定高度时就会爆炸成多个小烟花。小烟花会随机生成,并且会以一定的速度向四周扩散。
阅读全文