使用Java写一个小烟花
时间: 2024-05-13 21:17:18 浏览: 105
以下是一个简单的 Java 烟花动画示例代码,使用了 JavaFX 库:
```java
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.effect.BlendMode;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Fireworks extends Application {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int MAX_PARTICLES = 1000;
private static final double GRAVITY = 0.2;
private static final Random random = new Random();
private final List<Particle> particles = new ArrayList<>();
private GraphicsContext gc;
private Canvas canvas;
private AnimationTimer timer;
@Override
public void start(Stage primaryStage) {
canvas = new Canvas(WIDTH, HEIGHT);
gc = canvas.getGraphicsContext2D();
Group root = new Group();
root.getChildren().add(canvas);
Scene scene = new Scene(root, WIDTH, HEIGHT, Color.BLACK);
primaryStage.setTitle("Fireworks");
primaryStage.setScene(scene);
primaryStage.show();
timer = new AnimationTimer() {
@Override
public void handle(long now) {
update();
draw();
}
};
timer.start();
}
private void update() {
if (particles.size() < MAX_PARTICLES) {
particles.add(new Particle(WIDTH / 2, HEIGHT, random.nextDouble() * 2 * Math.PI));
}
for (int i = 0; i < particles.size(); i++) {
Particle particle = particles.get(i);
if (particle.isDead()) {
particles.remove(i--);
} else {
particle.update();
}
}
}
private void draw() {
gc.setGlobalBlendMode(BlendMode.SRC_OVER);
gc.setFill(Color.BLACK);
gc.fillRect(0, 0, WIDTH, HEIGHT);
for (Particle particle : particles) {
particle.draw(gc);
}
}
public static void main(String[] args) {
launch(args);
}
private static class Particle {
private static final int MAX_LIFE = 60;
private double x;
private double y;
private double vx;
private double vy;
private int life;
private final Color color;
public Particle(double x, double y, double angle) {
this.x = x;
this.y = y;
this.vx = Math.cos(angle) * 5;
this.vy = Math.sin(angle) * 5;
this.life = MAX_LIFE;
this.color = Color.hsb(random.nextDouble() * 360, 1, 1);
}
public void update() {
x += vx;
y -= vy;
vy -= GRAVITY;
life--;
}
public boolean isDead() {
return life <= 0;
}
public void draw(GraphicsContext gc) {
gc.setFill(color);
gc.fillOval(x, y, 2, 2);
}
}
}
```
这个示例代码会在窗口中随机生成烟花,每个烟花会发射出若干个颜色随机的小粒子,看起来像是一朵烟花在绽放。
阅读全文