Monday 9 May 2011

If/Else Examples 1

The first example I have of if/else statements in code is the sketch called A Zombie in Wonderland: A Text Adventure. The code works as such:

void draw() {
  if (page == 1) {
    pageOne();
  }else if (page == 2) {
    pageTwo();
  }else if (page == 3) {
    pageThree();
  }else if (page == 4) {
    pageFour();
  }else if (page == 5) {
    pageFive();

 etc...and then later continues:

void mousePressed() {
  if (page == 1) {
    if (overButton(b1x, b1y, b1w, b1h) == true) {
      page = 2;}
    else if (overButton(b2x, b2y, b2w, b2h) == true) {
      page = 3;}
  } else if (page == 2) {
    if (overButton(b1x, b1y, b1w, b1h) == true) {
      page = 4;}
    else if (overButton(b2x, b2y, b2w, b2h) == true) {
      page = 5;}

This sketch, although simple, is a great example of the "else if" function. It starts with the if statement which says if this specific page is loaded, then go to this page. Then, it later continues to make the buttons at the bottom of the page work by saying if this button is pressed go to this page ELSE if this button is pressed go to this page. The program then continues to run and eventually loops back to the begining depending on which buttons you press. Again, this is a very simple sketch, but a very good example of how the if/else function works, and how it can be used in a more complex way than just the original if/else statement.


No comments:

Post a Comment