
// Barnsley.java
// Robert Sedgewick and Kevin Wayne
// Slightly reformatted by Andrew Davison, Nov. 2022

// https://introcs.cs.princeton.edu/java/22library/Barnsley.java.html

/* Play chaos game to produce Barnsley's fern.

   Usage:
     >  compile Barnsley.java
     > run Barnsley n
   e.g.
     > run Barnsley 10000

   Reference:
      http://physics.wm.edu/~shiwei/courses/Phys690F03/HW/hw1/prob2.pdf
*/

import java.awt.Color;


public class Barnsley
{
  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run Barnsley <no. of points>");
      return;
    }
    int n = Integer.parseInt(args[0]);  

    StdDraw.setPenColor(new Color(0, 114, 0));  // green
    StdDraw.enableDoubleBuffering();

    // apply the update rules
    double x = 0.5;
    double y = 0.0;
    double tempx, tempy;

    for (int i = 0; i < n; i++) {
      double r = Math.random();
      if (r <= 0.02)  {
        tempx = 0.5;
        tempy = 0.27 * y;
      }
      else if (r <= 0.17) {
        tempx = -0.139 * x + 0.263 * y + 0.5700;
        tempy =  0.246 * x + 0.224 * y - 0.0360;
      }
      else if (r <= 0.30) {
        tempx =  0.170 * x - 0.215 * y + 0.4080;
        tempy =  0.222 * x + 0.176 * y + 0.0893;
      }
      else {
        tempx =  0.781 * x + 0.034 * y + 0.1075;
        tempy = -0.032 * x + 0.739 * y + 0.2700;
      }
      x = tempx;
      y = tempy;

      StdDraw.point(x, y);
      StdDraw.show();
      StdDraw.pause(10);
    }
    System.out.println("Finished drawing");
  } /* main */

}  // end of Barnsley class
