Skip to content

Instantly share code, notes, and snippets.

@gsasikiran
Last active December 9, 2020 13:27
Show Gist options
  • Save gsasikiran/f90a18cc68989611230220fdee77cd3e to your computer and use it in GitHub Desktop.
Save gsasikiran/f90a18cc68989611230220fdee77cd3e to your computer and use it in GitHub Desktop.
Chaos Game inspired from https://www.youtube.com/watch?v=kbKtFN71Lfs&t=1s. It generates Sierpiński triangle, when points = 3 and moving by half the length to each point with same probability. Try to tune different number of points and change the amount of length you can move from 1/2 to 1/3 (in lines 57 and 58) for different patterns.
/**
* Generates various fractals of geometries using chaos game as
* mentioned in https://www.youtube.com/watch?v=kbKtFN71Lfs&t=1s
*/
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.lang.Math;
/**
* @author Sasi Kiran Gaddipati
*
*/
public class chaosGame extends JPanel{
private int iterations = 150000;
private int upperbound = 500;
private int radius = 200;
private static int points = 3;
public void randomPoint(Graphics g, int iter, int num_points) {
Graphics2D g2d = (Graphics2D) g;
Random rand = new Random();
// To save the points
HashMap<Integer, Point> points = new HashMap<Integer, Point>();
// Generating the points on the window
for (int i = 0; i < num_points; i++) {
int x = (int) (radius * Math.cos((2*Math.PI*i)/num_points) + 250);
int y = (int) (radius * Math.sin((2*Math.PI*i)/num_points) + 250);
points.put(i+1, new Point(x, y));
g2d.fillOval(x, y, 5, 5);
}
// starting random position
int cur_x = 5 * rand.nextInt(upperbound);
int cur_y = 5 * rand.nextInt(upperbound);
g2d.drawOval(cur_x, cur_y, 5, 5);
Point point = new Point();
// Iterating to reach each point
for (int i=0; i< iter; i++) {
int num = rand.nextInt(num_points) + 1;
point = points.get(num);
cur_x = (cur_x + point.x)/2;
cur_y = (cur_y + point.y)/2;
g2d.fillOval(cur_x, cur_y, 5, 5);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
randomPoint(g, iterations, points);
}
public static void main(String[] args) {
chaosGame cg = new chaosGame();
JFrame window = new JFrame("Pyramid");
window.setSize(500,500);
window.add(cg);
window.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment