A Program that Makes Programs

Writing programs with lots of circles, lines, and rectangles can be tedious work. So in this brief note we provide a interesting program that lets you create a program by drawing.

Here is the code:

void setup() {
  size(500, 500);

  println("void setup() {");
  println("  size(500, 500);");
  println("}");
  println();
  println("void draw() {");
  // body of the draw() function added in mousePressed
}

void draw() {
  // draw function does nothing --- everything happens in mousePressed
}

void mousePressed() {
  noStroke();
  fill(255, 0, 0);
  ellipse(mouseX, mouseY, 5, 5);

  println("ellipse(" + mouseX + ", " + mouseY + ", 5, 5);");
}

void keyPressed() {
  if (key == 'q' || key == 'Q') {
    println("}");
  }
}

When you run it, click on some points around the screen. Then press ‘q’ when you are done. The print-out in the black console window at the bottom of the screen will be a program that draws the very same points.

It’s not hard to make changes to this program to make it produce different effects. For example you could replace the line that draws the ellipse to one that draws a rectangle, e.g.:

println("rect(" + mouseX + ", " + mouseY + ", 5, 5);")

Or in setup you could print a statement that changes the background color, e.g.:

void setup() {
  size(500, 500);

  println("void setup() {");
  println("  size(500, 500);");
  println("}");
  println();
  println("void draw() {");
  pritnln("  background(255);");
  // body of the draw() function added in mousePressed
}

Programming Questions

  1. Modify the program in these notes so that when the user presses ‘r’, the fill-color of the circles in the output program is set to red. Do the same thing with ‘g’ for green and ‘b’ for blue.
  2. Modify the program in these notes so that when the user presses one of the number keys, 1’, ‘2’, ... or ‘9’, then the width and height of the rectangle in the output program is set to be that number.