Random Numbers
Sometimes we need to perform random actions 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?
Random Number Display
Random numbers are very useful. They are common in games. Why do we still 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 displays a number between 1 and 6. randint() returns an integer, so we need to use str() to convert the integer to a string (e.g., 6 -> “6”).
gui.draw_label() writes the random number to the LCD screen.
If you want to set a 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, end is the ending value, and step is the increment base.
The above example randomly displays even numbers in the range (0, 10).
Sometimes you need numbers with decimal points. You can use the random.random method to generate a random float between 0.0 and 1.0. If you need a larger random float, use 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 deterministic algorithm, not a truly random sequence. The seed is the first value from which the algorithm starts computing. Therefore, as long as the seed is the same, all subsequent “random” results and their order will be exactly the same.
Specify a random seed, usually used in conjunction 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 a dice.