Skip to content

Instantly share code, notes, and snippets.

@Arinerron
Last active March 19, 2017 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arinerron/63f0b6c94509bb26026158fb30c66a96 to your computer and use it in GitHub Desktop.
Save Arinerron/63f0b6c94509bb26026158fb30c66a96 to your computer and use it in GitHub Desktop.
A Sierpinski Triange program I made cause I was bored...
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class Triangle extends JPanel {
public final JFrame frame = new JFrame("Sierpinski Triangle");
public final int width = 500;
public final int height = 500;
public boolean running = false;
public BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
public Random random = new Random();
public long iteration = 0;
public Point v1 = new Point(width / 2, 0);
public Point v2 = new Point(0, height);
public Point v3 = new Point(width, height);
public Point p = random(v1, v2, v3);
public static void main(String[] args) {
new Triangle();
}
public Triangle() {
image.getGraphics().setColor(Color.WHITE);
frame.setBackground(Color.BLACK);
frame.setSize(width, height);
frame.setResizable(false);
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
new java.util.Timer().schedule(new java.util.TimerTask() {
public void run() {
if(!running) {
running = true;
updateImage();
running = false;
}
}
}, 2, 2);
new java.util.Timer().schedule(new java.util.TimerTask() {
public void run() {
Triangle.this.repaint();
}
}, 10, 10);
}
public void updateImage() {
Point current = p;
Point vertice = random(v1, v2, v3);
final int halfx = (int)((current.x + vertice.x) / 2);
final int halfy = (int)((current.y + vertice.y) / 2);
Graphics g = image.getGraphics();
g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g.drawLine(halfx, halfy, halfx, halfy);
p = new Point(halfx, halfy);
iteration++;
}
public Point random(Point... points) {
return points[random.nextInt(points.length)];
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, 100);
if(this.image != null) {
g.drawImage(image, 0, 0, width, height, null);
}
g.setColor(Color.GREEN);
g.drawString("Iteration: " + iteration, 10, 10);
}
}
class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment