Random Numbers
Sometimes we need to do something random or generate random numbers. In this case you can use the random module.
For example, here is how to randomly display a name on the OLED screen:
from lv_gui import *
from mpython import *
import random
gui = GUI()
names = ["Mary", "Yolanda", "Damien", "Alia", "Kushal", "Mei Xiu", "Zoltan" ]
gui.fill(type=0)
gui.draw_label(text=str(random.choice(names)), row=1, color=0xffffff, wrap=False)
gui.update()
The list (names) contains seven names defined as strings. The random.choice method takes the names list as a parameter and returns a randomly selected item.
Can you modify the list to include your own name?
Randomly Displaying Numbers
Random numbers are very useful. They are common in games. Why else would we have dice?
MicroPython comes with several useful random number methods. Here is how to make a simple dice:
from lv_gui import *
from mpython import *
import random
gui = GUI()
gui.fill(type=0)
gui.draw_label(text=str(random.randint(1,6)), row=1, color=0xffffff, wrap=False)
gui.update()
Note
Each time the mPython Board restarts, it will display a number between 1 and 6. randint() returns an integer, so we need to use str() to convert the integer to a string (for example, 6 -> “6”).
gui.draw_label() writes the random number to the LCD screen.
If you want to set the random range or increment base, you can use random.randrange():
from lv_gui import *
from mpython import *
import random
gui = GUI()
gui.fill(type=0)
gui.draw_label(text=str(random.randrange(0,10,2)), row=1, color=0xffffff, wrap=False)
gui.update()
Note
random.randrange(start, end, step). start is the starting value of the random number, end is the ending value of the random number, and step is the increment base.
The above example randomly displays an even number in the range (0,10).
Sometimes you need numbers with a decimal point. You can use the random.random method to generate a random floating-point number from 0.0 to 1.0. If you need a larger random floating-point number, add random.uniform:
from lv_gui import *
from mpython import *
import random
gui = GUI()
gui.fill(type=0)
gui.draw_label(text=str(random.random()), row=1, color=0xffffff, wrap=False)
gui.draw_label(text=str(random.uniform(1,20)), row=2, color=0xffffff, wrap=False)
gui.update()
Random Seed
Random numbers in MicroPython are actually a stable sequence of results produced by a stable algorithm, rather than a random sequence. The seed is the first value from which this algorithm starts computing. So it happens that as long as the seed is the same, all subsequent “random” results and their order will be exactly the same.
Specify the random number seed, usually used together with other random number generation functions.
Sometimes you want repeatable random behavior: a reproducible random source. This is like saying you need the same five random values each time you roll the dice.