import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;

public class lab20070607 extends JPanel
{
	Cerchio cerchio;
	Cerchio[] millePalline;
	JFrame f;
	double FRAME = 0;
	public lab20070607()
	{
		f = new JFrame();
		f.setSize(400,400);
		f.setTitle("Pallina");
		f.add(this);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
		f.setLocation(500,250);
		
		millePalline = new Cerchio[1000];
		for (int k = 0; k < millePalline.length; k++)
			millePalline[k] = new Cerchio(200,200,8, 0.1+Math.random()*2, new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255)));
			
		cerchio = new Cerchio(200,200,50, 0.7, Color.black);
		addMouseListener(new MouseAdapter() { 
			public void mouseClicked(MouseEvent e){
				if (cerchio.cliccato(e.getX(), e.getY()))
				{
					cerchio.x = (int)(Math.random()*getWidth());
					cerchio.y = (int)(Math.random()*getHeight());
					cerchio.dim = 50;
					repaint();
				}
			}});
	}

	public void paint(Graphics _g)
	{
		super.paintComponent(_g);
		Graphics2D g = (Graphics2D)_g;
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setColor(Color.black);
		FRAME+=0.5;
		cerchio.dim = cerchio.dim + Math.sin(FRAME)*5;
		cerchio.dim+=0.2;
		cerchio.rimbalza(0,0,getWidth(),getHeight());
		cerchio.mostra(g);
		
		
		//f.setLocation(500 - (int)cerchio.x, 250 - (int)cerchio.y);
		
		g.setColor(Color.red);
		for (int k = 0; k < millePalline.length; k++)
		{
			millePalline[k].rimbalza((int)(cerchio.x-cerchio.dim/2), (int)(cerchio.y-cerchio.dim/2), (int)(cerchio.x+cerchio.dim/2), (int)(cerchio.y+cerchio.dim/2));
			millePalline[k].mostra(g);
		}
		repaint();
		try { Thread.sleep(10); } catch(Exception e){}
	}
	
	public static void main(String[] a){ lab20070607 f = new lab20070607();	}
}

class Cerchio
{
	double x, y, dim;
	double step = 1, VX=1, VY=1;
	boolean clicked = false;
	Color sfondo;
	
	public Cerchio(double x, double y, double dim, double step, Color sfondo)
	{
		this.x = x;
		this.y = y;
		this.dim = dim;
		this.step = step;
		VX = (-1 + Math.random()*2);
		VY = (-1 + Math.random()*2);
		this.sfondo = sfondo;
	}
	public boolean cliccato(int cx, int cy)
	{
		if (cx > x - dim/2 && cx < x+dim/2 && cy > y-dim/2 && cy < y+dim/2)
			return true;
		else
			return false;
	}
	
	public void mostra(Graphics g)
	{
		g.setColor(sfondo);
		g.fillOval((int)(x-dim/2),(int)(y-dim/2), (int)dim, (int)dim);
	}
	
	public void rimbalza(int x1, int y1, int x2, int y2)
	{
		x += step*VX;
		y += step*VY;
		if (x < x1+dim/2) VX = Math.random()*2;
		if (x > x2-dim/2) VX = Math.random() - 1;
		if (y < y1+dim/2) VY = Math.random()*2;	
		if (y > y2-dim/2) VY = Math.random() - 1;	
	}
}