This program checks to see if the number of collisions is an even or odd number and turns the Main LED on or off, respectively, if that is true. There are a couple of different ways to do this, of course, and you can see some of them below. You can generate a collision event by hitting Sphero on your hand or just shaking it vigorously.
Task: Write an algorithm that turns the main LED on when the number of collisions is even and off when the number of collisions is odd.
We need to start by creating and initializing a variable to represent the number of collisions (c) that have occurred. We do this when the program starts and also turn off the main LED.
Anytime there is a collision we need to record that and we do so with the block, set c to c + 1, which increments the number of collisions each time Sphero detects one. Then we need to ask a question, is the number of collisions even or odd? We can do this using the modulo operation, represented here by the % sign in if c % 2 === 0 then. Essentially this works out to if c divided by 2 has a remainder of 0 then it is an even number, else it is an odd number. Here are some examples:
If the result of c % 2 === 0 is TRUE then we set the main LED to a random color, else we turn it off. c % 2 === 0 is a boolean operation that results to either TRUE or FALSE.
Block Types: Events, Variables, Lights, Control, Operator, Comparators
You'll notice that this example uses another variable (c_even) of type boolean, that holds the value of whether the number of collisions is even or odd.
This example has a slightly different outcome. Can you figure out why? Is the different outcome the intended one for the task given? What does the outcome tell us about our algorithm?
Block Types: Events, Variables, Lights, Control, Operator, Comparators
What happens if you shake Sphero vigorously multiple times in a short period? Does Sphero react the way that you expect? Why or why not?
How would you modify this program/algorithm so that you can verify how many collisions have occurred? Hint: You'll need to use a speak block and include the c variable to give audio output. How about having it give audio output only on the 10th collision or every 10th collision?