How can I restart the program with keypress

One simple way of approaching restart-timing is to rerun your setup each time you restart, and maintain a global variable with the last time you restarted. This lets you compute either the total run time (millis) or the current runtime (restart-millis).

Processing always runs setup on frame 0 – so one way to rerun it (and reset frameCount at the same time) is to set the frameCount to -1.

/**
 * Restart Frame 0
 * 2019-11 Processing 3.4 
 * Press key to restart -- setup() runs again on the following frame.
 * Sketch demonstrates computing a custom millis based on last restart.
 */

int start;
color bgcolor;
int level = 0;

void setup() {
  start = millis();
  bgcolor = color(random(255), random(255), random(255));
  level = level + 1;
}

int reMillis() {
  return millis()-start;
}

void draw() {
  background(bgcolor);
  text(level, 20, 20);
  text(frameCount, 20, 40);
  text(reMillis(), 20, 60);
  text(millis(), 20, 85);
}

void keyReleased() {
  frameCount = -1;
}

Note that this behavior isn’t officially documented in the reference – but it has been a part of Processing for a very long time.

1 Like