Code

//globals
int x =50;
int y = 50;
int w = 200;
int h = 10;
int time= 120;
int frame= 0;

boolean bstartOver = false;
boolean bcolor = false;

float percent = 0;

void setup (){
  size (300,100);
  background (255, 0,0);
  noStroke();
  smooth();
}

void draw(){
percent=(((float)frameCount-(float)frame)/time);
  rect (x,y,w,h);
  fill (0);
  
  if (percent < 1 && bstartOver == true){
    rect (x,y,percent*w, h);
    fill (200,60,180);
  }
  
  if (frameCount== frame + time && bstartOver ==true){
    change();
  }
}

void mousePressed(){
  bstartOver= true;
  frame = frameCount;
}

void change(){
  bcolor=!bcolor;
  if (bcolor){
    background (255);
  }
  
  else if (!bcolor){
    background (0);
  }
}

0304 - Maintaining state (progress bar): Timers and booleans

Statement:Give yourself ample time to create this program. The solution code is short, but you may need to think carefully.

Create a "progress bar" program in which a progress bar is set into action by the user's click, and when the timer has elapsed, the background color flips from black to white. Here are some hints:

  • Store the frameCount when the user clicks the mouse;
  • On each frame, compute how many frames have elapsed since the click;
  • Suppose that your "progress bar" takes 120 frames to complete its task (the "task completion time"). It would be nice if this were a global variable...
  • Compute a percentage which represents the fraction of the "task completion time" which has elapsed;
  • Render a progress bar which illustrates this percentage;
  • When the progress bar is complete, flip the color of the screen from white to black (or vice-versa);
  • The program should wait for user input when it launches.
Your colleague Placebo has created a solution to this problem which illustrates the correct behavior.

hide statement