java新年快乐烟花
时间: 2024-01-12 14:22:38 浏览: 102
以下是一个使用Java Swing实现的简单祝福烟花效果的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Fireworks extends JFrame {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int NUM_FIREWORKS = 10;
private Firework[] fireworks;
public Fireworks() {
setTitle("New Year Fireworks");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
fireworks = new Firework[NUM_FIREWORKS];
for (int i = 0; i < NUM_FIREWORKS; i++) {
fireworks[i] = new Firework();
}
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
for (Firework firework : fireworks) {
firework.draw(g);
}
}
private class Firework {
private static final int MAX_PARTICLES = 100;
private static final int MAX_VELOCITY = 5;
private static final int MAX_RADIUS = 10;
private int x;
private int y;
private int radius;
private Color color;
private Particle[] particles;
public Firework() {
Random random = new Random();
x = random.nextInt(WIDTH);
y = random.nextInt(HEIGHT);
radius = random.nextInt(MAX_RADIUS) + 1;
color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
particles = new Particle[MAX_PARTICLES];
for (int i = 0; i < MAX_PARTICLES; i++) {
particles[i] = new Particle();
}
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
for (Particle particle : particles) {
particle.update();
particle.draw(g);
}
}
private class Particle {
private int x;
private int y;
private int velocityX;
private int velocityY;
private int radius;
public Particle() {
Random random = new Random();
x = Firework.this.x;
y = Firework.this.y;
velocityX = random.nextInt(2 * MAX_VELOCITY + 1) - MAX_VELOCITY;
velocityY = random.nextInt(2 * MAX_VELOCITY + 1) - MAX_VELOCITY;
radius = random.nextInt(MAX_RADIUS) + 1;
}
public void update() {
x += velocityX;
y += velocityY;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Fireworks::new);
}
}
```
这段代码使用Java Swing库绘制了一个简单的祝福烟花效果。它创建了一个窗口,并在窗口中绘制了多个烟花。每个烟花由一个中心点和多个粒子组成,粒子在窗口中随机移动,形成烟花效果。
阅读全文