The classic fortune telling game! We'll use a function and it will be very similar to Roll the Barnyard, but there are going to be 20 possible options to check for! A function becomes really important here, as all those nested If...Then...Else blocks get a wee bit hard to look at and troubleshoot. For more info about the Magic 8 Ball, check out this link to the Wikipedia article, including the 20 possible answers to a Yes/No question on a standard Magic 8 Ball.
Here we have 2 events to consider, on start program and on freefall. Like many other programs where we don't want Sphero to correct for being upside down, we turn stabilization (off). And I always like to give some visual output that the program has started, so we set the main LED (blue). For the on freefall event, we need to get a random number to test for each of the different possible outcomes and we do that with the pink set (answer) block. Notice we're using a random int from 0 to 19 instead of 1 to 20! In programming, we often start with 0.
To understand the If...Then...Else blocks, it is important to know that our responses for 0 - 9 will all be affirmative, 10 - 14 will be non-committal, and 15 - 19 will be negatives. Using some visual output to go along with the spoken responses adds a bit of fun. The second If...Then...Else statement uses the && block to check that both comparisons are TRUE.
The last block calls our custom function, tellFortune and does the bulk of the work for this program.
Blocks Types: Movements, Lights, Controls, Operators, Comparators, Events, Variables, Functions
Below is the very long function that we wrote. As you look at the function below and the code blocks above, think about other ways that you might be able to write this program. If I wrote it again, I might try changing my set (answer) block above to set (answer) to (random int from (0) to (2)). How do you think I'd have to modify the rest of my program to make that work? Would this new program be easier to understand and troubleshoot for the coder? Would it be faster for the computer to execute this new program?