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 random
colorList = [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.

Coding for 35+ years, enjoying using and learning Swift/iOS development. Writer @ Better Programming, @The StartUp, @Mac O’Clock, Level Up Coding & More

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store