MicroPython Tutorial III
Ok, lets try and build a simple game with the code we learnt over the last two lessons in the next two. Here is our code template.
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.parameters import Button, Color
from pybricks.tools import wait
import time
import randomcolorList = [Color.RED, Color.YELLOW, Color.ORANGE, Color.GREEN, Color.BLACK]def randomColor():
seedling = int(round(time.time()))
random.seed(seedling)
colorNo = random.randint(0,4)
return(colorNo)while True:
if Button.DOWN in brick.buttons():
colorNo = randomColor()
brick.light(colorList[colorNo])
wait(500)
if Button.UP in brick.buttons():
colorNo = randomColor()
brick.light(colorList[colorNo])
wait(500)
It is basically the same code you did in tutorial II, with a few minor changes that will come into play as we move forward.
We’re going to build a “simple Simon says” type game. We start by adding two subroutines. Code that you can place above the randomColor routine.
def blink():
brick.light(Color.BLACK)
wait(500)def randomSet():
global randomList
# RED = LEFT button
# YELLOW = RIGHT button
# ORANGE = DOWN button
# GREEN = UP button
# BLACK = starting mode
for loop in range(4):
randomList.append(randomColor())
wait(1000)
In the first we define a method for turning the brick light off. In the second we document the colors against the buttons in comments (starting with a hash). We then use a simple loop to call our random number generator 4 times, waiting one second between each call for a new seed.
We then call our new subroutines in main program before the while True: loop.
randomSet()
print(“randomList”,randomList)
blink()
for colorNo in randomList:
brick.light(colorList[colorNo])
wait(1000)
blink()
Run the program, it will display the list as it generates it and then use that to show a sequence of colors.