package CHAPTER11;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

public class MouseClickAnimation extends JFrame {
    private AnimationPanel animationPanel;

    public MouseClickAnimation() {
        setTitle("Mouse Click Animation");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        animationPanel = new AnimationPanel();
        add(animationPanel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MouseClickAnimation frame = new MouseClickAnimation();
            frame.setVisible(true);
        });
    }
}

class AnimationPanel extends JPanel {
    private final List<Particle> particles = new ArrayList<>();
    private final Timer timer;

    public AnimationPanel() {
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                createExplosion(e.getX(), e.getY());
            }
        });

        timer = new Timer(30, e -> updateParticles());
        timer.start();
    }

    private void createExplosion(int x, int y) {
        for (int i = 0; i < 50; i++) {
            particles.add(new Particle(x, y));
        }
    }

    private void updateParticles() {
        for (Particle particle : particles) {
            particle.update();
        }
        particles.removeIf(p -> p.getLifetime() <= 0);
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        for (Particle particle : particles) {
            particle.draw(g2d);
        }
    }
}

class Particle {
    private int x, y;
    private int lifetime;
    private double angle;
    private double speed;
    private Color color;

    public Particle(int x, int y) {
        this.x = x;
        this.y = y;
        this.lifetime = 50 + (int) (Math.random() * 50);
        this.angle = Math.random() * 2 * Math.PI;
        this.speed = 2 + Math.random() * 4;
        this.color = new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255));
    }

    public void update() {
        x += (int) (speed * Math.cos(angle));
        y += (int) (speed * Math.sin(angle));
        lifetime--;
    }

    public void draw(Graphics2D g2d) {
        g2d.setColor(color);
        g2d.fillOval(x, y, 10, 10);
    }

    public int getLifetime() {
        return lifetime;
    }
}

