Decision-Making and the If-Else

An app is a set of event handlers. When an event occurs, perform some instructions (blocks). However, within those event-handlers, the app can ask if questions and perform different instructions based on the answers. Such conditional blocks form the basis for the intelligence of an app.

Sample: Toggling between presidential candidates

President Obama appears when the apps begins, but each time you click the picture it switches back and forth between Obama and Mitt Romney

  • The picture appears on a Button component. The Button.Image property specifies the image file that appears on the button.
  • The event is the button click.
  • When the button is clicked, ask which picture appears. If it is Obama, show Romney, else if it was Romney, show Obama.

A reference block (the light blue 'Button1.Image') is used to see what the existing image is, while a set block (the darker blue 'set Button1.Image' block) is used to change the image the appears. In general, if tests will use reference blocks to check the current state of the app.

Sample: Randomly choosing a picture

As a second if-example, let's change the app so that it randomly chooses one of the two pictures (each time the user clicks, it might show Obama, might show Romney). Such random behavior is the part of many games.

  • In the Math folder, there is a random integer block. You can set a range for the value that it generates.
  • We'll grab a random number with a range from 1 to 2. If 1 is generated (50% chance), we'll show Obama, else we'll show Romney.