How to make keyPressed work inside a while loop

This is the key thing to understand. Processing is already designed to make things like this easy if you treat draw like your while loop. After the end of every draw (every frame), all the interaction functions – mouseDragged(), keyPressed(), keyReleased(), etc. – are checked. So I recommend following @jb4x’s advice and do your checking there.

If you have a lot of different states, then write a simple state machine by turning most of your draw loop into a switch statement.

This also makes it simple to prototype your state machine before writing any of the code. For example, here is a simple state machine that asks questions and displays answers until a score is reached, then it displays the end screen.

char state = 'q';
int score = 0;
int max = 3;

void draw() {
  switch(state) {
  case 'q':
    question();
    break;
  case 'a':
    answer();
    break;
  case 'e':
    end();
    break;
  default:
    question();
  }
}

void question() {
  background(255, 0, 0);
}

void answer() {
  background(0, 255, 0);
}

void end() {
  background(0, 0, 255);
}

void score() {
  score += 1;
}

void keyReleased() {
  switch(state) {
  case 'q':
    state = 'a';
    break;
  case 'a':
    score();
    if (score < max) {
      state = 'q';
    } else {
      state = 'e';
    }
    break;
  case 'e':
    end();
    break;
  default:
    question();
  }
}

This simple sketch outline only asks three “questions”, and the “answer” is always correct – so I just press the space bar a few times and the “game” is over. But it shows me that draw is acting as a while loop, displaying my question state (red), answer state (green), or end state (blue) at the correct times. Having designed that, I can now get into the code for asking and scoring questions separately, each in its own function, without worrying about the state logic.

2 Likes