package sierp;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Sierp extends JFrame{
	
	
	public Sierp(Dimension d) {
		this.setSize(d);
		this.setBackground(Color.white);
		this.add(new MyPane(d));
		this.pack();
		this.setVisible(true);
	}

	class MyPane extends JPanel implements Runnable{
		Thread thread=null;
		
		Point2D.Double a,b,c;
		Line2D.Double line=new Line2D.Double(500,500,500,500);
		
		public MyPane(Dimension d){
			double delta=d.getWidth()/2;
			this.setPreferredSize(d);
			this.setBackground(Color.white);
			
			a=new Point2D.Double(delta+(-1*0.5*delta),delta+(1.0/3*(delta*0.866025)));
			b=new Point2D.Double(delta+(0.5*delta),delta+(1.0/3*(delta*0.866025)));
			c=new Point2D.Double(delta,delta-(2.0/3*(delta*0.866025)));
			
			//line();
			repaint();
			thread = new Thread(this);
			thread.start();
		}
		
		private void line(){
			int rand=(int)(Math.random()*3.0+1);
			Point2D.Double dest=null,orig=null;
			if(rand==1){
				dest=a;
			}else if(rand==2){
				dest=b;
			}else{
				dest=c;
			}
			
			orig=new Point2D.Double(line.getBounds2D().getCenterX(),line.getBounds2D().getCenterY());
			line=new Line2D.Double(orig,dest);
		}
		
		protected void paintComponent(Graphics g){
			Graphics2D g2d = (Graphics2D)g;
			g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
			g2d.setColor(randomCol());
			g2d.fillRect((int)line.getX1(),(int)line.getY1(),1,1);
		}
		
		public void run() {
			while(true){
				try {
					thread.sleep(20);
				} catch (InterruptedException e){
					e.printStackTrace();
				}
				line();
				repaint();
			}
		}
		public Color randomCol(){
			return new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
		}
	}

}



