APP INVENTOR TUTORIAL

EXAMPLE 9: HEADS OR TAILS

This tutorial is a clear example of random functions and booleans. When the user clicks on the button, the coin will randomly show heads or coins.

DESIGNER SECTION

1. Click on Screen1 and change its alignment options to “center” so that all elements added will be displayed at the centre.

2. Add a Button and change its text to “Flip coin”.

3. Add two Images from the User Interface section. Then upload the two sides of a coin, one for each image. If you don’t want to have a background for your image, choose .png files.

4. Once you added the two images, tick the option “visible” for just one of them. In our example,  heads is visible now.

5. Let’s add also a flipping coin sound when the users clicks on the button. Add Sound from the Media Section (non-visible component). Now, click on it and upload an audio file.

BLOCKS SECTION

1.When the user clicks the button, our audio file will be played and a random side of the coin will be displayed. First of all, we have to include the code for the button:

when Button1.Click
do

2. Click on Sound and add:

call Sound1.Play

3. Now, how do we code that a random side of the coin has to be displayed every time the user clicks? First, we need to insert an if statement to include our conditions. So, drag the “if then” block from the Control section and add “else”.

Then, we will use a random function so that the app will choose randomly between two numbers, one of each will make an image visible. For example, if the random number between 1 and 2 is 1, we want the app to display Image1. Go to Math and drag the block “….=….”. Then, drag the following block inside the first empty space:

random integer from 1 to 100

Then change “100” to “2”. Change the value of the second empty space to 1.

4. Now we have to set what happens when the random number is 1. Go to Image1 and drag:

set Image1.Visible to 

From Logic, drag and attach the block “true”.

5. If image 1 is visible, the other one must be invisible. So, just copy and paste the “set visible” block and change Image1 to Image2 and true to false.

6. What if the random number is 2 instead? In this case, it’s Image2 that will be displayed on the Screen. Copy and paste the two “set Visible” blocks you have just added and attach them to the “else”. Now change their values: if the random number is 2, “Image1.visible” will be false and “Image2.visible” will become true.



Now, let’s run the app with Emulator and flip the coin! What did you get?




You can download the project here.