SIMON 4
In this project, we continue the development of our Simon-like pattern matching game by adding randomized LED blinking.
Speaker & Audio Cable
I/O (Input/Output) RaspberrySTEM Cell
Having issues? Check out the Troubleshooting Guide.

In our last project, we wrote some code to flash LEDs in a pre-planned sequence. While that's a good start, in our Simon-like game, we're going to need to flash LEDs in a random sequence.

In this project, we're going to make some modifications to the code from the last project which will give us a random sequence of LED flashes. In the next project, we'll add in the buttons.


randrange() Function

The randrange() function simply returns a random number with the range provided when the function is called. If one parameter is supplied, the random number generated will fall between 1 and that parameter. If two parameters are supplied, the random number will fall between the first and second parameter, both included.

We use the randrange() function in our Simon-like game to generate a random sequence of LED flashes for our game.


Programming Implementation

Starting with the code we left off with in the previous project, the first thing we'll need to do is import the function randrange() to create our random generation of LED flashes:



Next, instead of filling the list play_order with a pre-defined sequence, we're going to make that an empty list that we can use to hold our random sequence. To do that, we'll replace the list we created previously with a new (empty) list:



Finally, we'll have to create our random sequence of LEDs. We'll add a random LED to the end of the play_order list. The following line of code is a shorthand to append an item to a list (in this case, the item is a random number from 0 to 3):



If we add this code to our previous code that includes the play sequence, we'll see that we're adding a single random LED flash to our sequence list and then flashing it:



If we add a while loop, we can continue to generate a random LED and add it to the list each time through the loop. This will play the entire sequence of random LED flashes, add a new LED to the sequence, play the list again with the new LED added, and then repeat:



Here is what the code for this project should look like at this point -- when you run it, you will see a random LED flash, then that light will repeat with a second random light added, then that 2-light sequence will repeat with a third added and so on (the sequence will continue until you stop the program):



home | prev | next