CMPC
Would you like to react to this message? Create an account in a few clicks or log in to continue.

A Simple Applet to Render Sierpinski's Triangle

Go down

A Simple Applet to Render Sierpinski's Triangle Empty A Simple Applet to Render Sierpinski's Triangle

Post by Paul Mon Dec 07, 2009 7:38 am

Code:

import java.applet.*;
import java.awt.*;

public class Sierpinski extends Applet
{
    int width, height;
    Point p1,p2,p3;
    public void init()
    {
        width = getSize().width;
        height = getSize().height;
        setBackground( Color.white );
        p1 = new Point( width/2, 0 );
        p2 = new Point( 0, height );
        p3 = new Point( width, height);
    }
    public void paint( Graphics g )
    {
        g.setColor( Color.blue );
        g.drawLine( (p1.x), (p1.y), (p1.x), (p1.y) );
        g.setColor( Color.green );
        g.drawLine( (p2.x), (p2.y), (p2.x), (p2.y) );
        g.setColor( Color.red );
        g.drawLine( (p3.x), (p3.y), (p3.x), (p3.y) );
        Point temp=p1;
        for(int i =0; i <=1000000; i++)
        {
            switch(roll(3))
            {
                case 1:
                {
                    g.setColor( Color.blue );
                    temp=temp.midpoint(p1);
                    g.drawLine( (temp.x), (temp.y), (temp.x), (temp.y) );
                    break;
                }
                case 2:
                {
                    g.setColor( Color.green );
                    temp=temp.midpoint(p2);
                    g.drawLine( (temp.x), (temp.y), (temp.x), (temp.y) );
                    break;
                }
                case 3:
                {
                    g.setColor( Color.red );
                    temp=temp.midpoint(p3);
                    g.drawLine( (temp.x), (temp.y), (temp.x), (temp.y) );
                    break;
                }
            }
        }
    }
    public int roll(int sides)
    {
        return (int) Math.round( (Math.random()*sides)+1 );
    }
}
Paul
Paul
Pickaxe

Posts : 611

Back to top Go down

A Simple Applet to Render Sierpinski's Triangle Empty Re: A Simple Applet to Render Sierpinski's Triangle

Post by Paul Mon Dec 07, 2009 7:39 am

The Point class I wrote for this applet:
Code:

public class Point
{
    public int x,y;
    public Point()
    {
        x = 0;
        y = 0;
    }
    public Point( int xc, int yc )
    {
        x = xc;
        y = yc;
    }
    public Point midpoint(Point between)
    {
        return new Point( (this.x+between.x)/2, (this.y+between.y)/2 );
    }
    public double distance(Point to)
    {
        return Math.sqrt( Math.pow(this.x-to.x,2)+Math.pow(this.y-to.y,2) );
    }
}
Paul
Paul
Pickaxe

Posts : 611

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum