2025跨年烟花代码java
时间: 2025-01-01 11:28:53 浏览: 7
### Java 2025新年烟花动画代码实例
为了实现Java环境下的2025新年烟花效果,通常会采用图形界面库如Swing或JavaFX。下面提供了一个基于Java Swing的简单烟花爆炸模拟程序:
```java
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class FireworksAnimation extends JPanel {
private List<Firework> fireworks = new ArrayList<>();
public FireworksAnimation() {
setPreferredSize(new Dimension(800, 600));
setBackground(Color.BLACK);
Timer timer = new Timer(30, e -> repaint());
timer.start();
// 模拟每隔一段时间发射新的烟花
Thread thread = new Thread(() -> {
while (true) {
try {
Thread.sleep((long)(Math.random() * 1000 + 500)); // 随机间隔时间
addNewFirework();
} catch (InterruptedException ex) {}
}
});
thread.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
for(Firework f : fireworks){
f.draw(g2d);
}
updateFireworks();
g2d.dispose();
}
private synchronized void addNewFirework(){
int x = (int)(Math.random()*getWidth());
fireworks.add(new Firework(x, getHeight()));
}
private synchronized void updateFireworks(){
List<Firework> toRemove = new ArrayList<>();
for(int i=0; i<fireworks.size(); ++i){
if(fireworks.get(i).update()){
toRemove.add(fireworks.get(i));
}
}
fireworks.removeAll(toRemove);
}
static class Firework{
private final Color color;
private double x,y,vx,vy,radius,alpha;
public Firework(double startX,double startY){
this.color = new Color(
(float)Math.random(),
(float)Math.random(),
(float)Math.random()
);
this.x=startX;
this.y=startY-(startY* Math.random())/2;
this.vx=(Math.random()-0.5)*7;
this.vy=-Math.sqrt(Math.abs(startY-x))*0.9-Math.random()*4-2;
this.radius=Math.random()*3+1;
this.alpha=1f;
}
boolean update(){
vy+=0.1;
y+=vy;
x+=vx;
alpha-=0.01;
return alpha<=0 || y>=getHeight();
}
void draw(Graphics2D g2d){
Composite originalComposite=g2d.getComposite();
AlphaComposite ac=AlphaComposite.getInstance(
AlphaComposite.SRC_OVER,
(float)alpha
);
g2d.setComposite(ac);
g2d.setColor(color);
g2d.fillOval((int)x-radius,(int)y-radius,2*(int)radius,2*(int)radius);
g2d.setComposite(originalComposite);
}
}
public static void main(String[] args) {
JFrame frame=new JFrame("Happy New Year 2025!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FireworksAnimation());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这段代码创建了一个窗口,在其中随机位置不断生成并渲染烟花粒子的效果[^1]。
阅读全文