Brick Game Timer Question

Hi @newprogrammer12,

To understand better how it works, maybe start with a simpler example (without Java classes).

Displaying a timer implies using time. In Processing we can get the current time since the beginning of the program in milliseconds with the millis() function.

Let’s look at the following program:

// Starts at the beginning of the program
int timerStart = 0;
int duration = 1000;

void draw() {
  // Time spent since the beginning of the timer
  int timeSinceStart = millis() - timerStart;

  if (timeSinceStart <= duration) {
    println(timeSinceStart);
  } else {
    println("Timer ends");
    noLoop();
  }
}

It will display the time in milliseconds since the beginning of the program and stops when the duration is over.

Now you need a way to trigger the timer and run it again. Let’s do that by resetting the timerStart to the current time using millis():

int timerStart = 0;
int duration = 1000;

void mousePressed() {
  // Set the start of the timer to the click time
  timerStart = millis();
}

void setup() {
  size(200, 200);
}

void draw() {
  background(255);

  int timeSinceStart = millis() - timerStart;

  textAlign(CENTER, CENTER);
  fill(0);

  if (timeSinceStart <= duration) {
    text(timeSinceStart, width / 2, height / 2);
  } else {
    text("TIMER NOT ACTIVE, CLICK", width / 2, height / 2);
  }
}

Now the issue is that it will start at the beginning because the start time is 0. We can wrap this code into a proper class and control the start (same as the non complete example you sent).

class Timer {
  int duration;
  int savedTime = 0;
  boolean started = false;
  
  Timer(int duration) {
    this.duration = duration;
  }
  
  void start() {
    started = true;
    savedTime = millis();
  }
  
  boolean isFinished() {
    return started && millis() - savedTime > duration;
  }
}

Timer timer;

void setup() {
  size(200, 200);
  timer = new Timer(4000);
  timer.start();
}

void draw() {
  if (timer.isFinished()) {
    println("TIMER OVER");
    noLoop();
  }
}

Now you should be able to use it properly to display your Game over screen. :wink:

1 Like