SIMON 4

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.

INFO BOX ON RANDRANGE()

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:


INSERT CODE BOX

play_order = []

Finally, we'll have to create our random sequence of LEDs.  We can add a random LED to play_order[] with the following line of code:


INSERT CODE BOX

play_order += [randrange(4)]


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:

INSERT CODE BLOCK

# Initialize the LEDs and sequence list
from rstem.gpio import Output
import time
lights = [Output(4), Output(18), Output(14), Output(15)]
play_order = [0, 1, 2, 3, 2, 1, 0, 3]

# Play sequence
for light in lights: light.off()

for i in play_order:
    lights[i].on()
    time.sleep(0.4)
    lights[i].off()
    time.sleep(0.2)

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:


INSERT CODE BLOCK

# Initialize the LEDs and sequence list
from rstem.gpio import Output
import time
lights = [Output(4), Output(18), Output(14), Output(15)]
play_order = [0, 1, 2, 3, 2, 1, 0, 3]

# Play sequence
for light in lights: light.off()

while True:
    for i in play_order:
        lights[i].on()
        time.sleep(0.4)
        lights[i].off()
        time.sleep(0.2)


Here is what the code for this project should look like at this point:



prev| next