
// KochRainbow.java
// Robert Sedgewick and Kevin Wayne
// Slightly reformatted by Andrew Davison, Nov. 2022

// https://introcs.cs.princeton.edu/java/32class/KochRainbow.java.html

/* Plot an order n Koch snowflake, using the spectrum of colors.

   Uses Turtle.java

   Usage:
     > compile KochRainbow.java
     > run KochRainbow n
   e.g.
     > run KochRainbow 5
*/


import java.awt.Color;


public class KochRainbow 
{
  private static Turtle turtle; 
  private static double color;       // current color
  private static double increment;   // change in color


  public static void main(String[] args) 
  {
    if (args.length != 1) {
      System.out.println("Usage: run KochRainbow <depth>");
      return;
    }
    int n = Integer.parseInt(args[0]);

    int width = 512;
    int height = (int) (2 * width / Math.sqrt(3));


    turtle = new Turtle(0, width * Math.sqrt(3)/2, 0.0);
    turtle.setCanvasSize(width, height);
    turtle.setXscale(0, width);
    turtle.setYscale(0, height);

    double step = width / Math.pow(3.0, n);
    turtle.setStep(step);

    // rainbow of colors
    color = 0.0;
    increment = Math.pow(4.0, -n) / 3.0;

    // three Koch curves in the shape of an equilateral triangle
    koch(n);
    turtle.left(-120);
    koch(n);
    turtle.left(-120);
    koch(n);
  } // end of main()



  private static void koch(int n) 
  {
    if (n == 0) {
      turtle.setPenColor(Color.getHSBColor(
                      (float) color, 1.0f, 1.0f));
      color += increment;
      turtle.forward();
    }
    else {
      koch(n-1);
      turtle.left(60);
      koch(n-1);
      turtle.left(-120);
      koch(n-1);
      turtle.left(60);
      koch(n-1);
    }
  } // end of koch()


}  // end of KochRainbow class
