I am making a hangman game on my microbit and am having trouble with the random library. I need to choose a random number between 1 and 7, and every single time I run the program it always yields the number ‘5’.The strangest part is when I copy the exact same code into a IDE like visual code studio and run in via the terminal instead of through the micro:bit emulator it creates, like I would expect, random numbers between 1 and 7
What I have tried
Attempt 1
from microbit import * #omitted when ran in terminal
import random
num = random.randint(1, 7)
display.show(str(num)) #changed to print(num) when ran in terminal
Attempt 2
from microbit import * #omitted when ran in terminal
import random
numbers = [1, 2, 3, 4, 5, 6, 7]
num = random.choice(numbers)
display.show(str(num)) #changed to print(num) when ran in terminal
Attempt 3
from microbit import * #omitted when ran in terminal
import random
random.seed(4443)
while True:
if button_a.was_pressed:
num = random.randint(1, 7)
print(num)
Solution
This solution only works for the physical microbit and doesn’t work in the emulator.
while True:
num = random.randint(1, 7)
display.show(num)
sleep(2000)
machine.reset()
I have been following the documentation on the random library on micropython’s offical docs.
Is there something I am doing wrong?
3
Answers
Try this way:
Edit 1st November 2022: The bug in the simulator is now fixed. The code runs as expected on the simulator, displaying a series of random numbers.
Original reply dated 15th October 2022:
The bug appears to be in the simulator only. When I ran your code on the simulator I got the same – always the same number.
I tried using the random.seed() function, which in theory adjusts how the random numbers are generated. This has no effect in the simulator.
Downloading the code onto a micro:bit v2 produces a random number each time the reset button is pushed on the back of the micro:bit.
Interestingly, the solution proposed by Bibhav generates the same string of numbers on the simulator display. The string appears to be random, but is always be the same string of values in the same order.
Downloading Bibhav’s solution to the micro:bit hardware results in what appears to be a random series of numbers that varies each time the board is reset.
As @Oppy correctly diagnosed, this should work correctly in the micro:bit device, and the problem only affected the Python Editor simulator. In this case the issue was that the simulator random number generator was not seeded correctly.
The micro:bit Python Editor issue has been fixed and deployed today:
https://github.com/microbit-foundation/micropython-microbit-v2-simulator/issues/85
If you go to https://python.microbit.org and do a hard-refresh (to ensure the latest version is loaded), it should now work in the simulator as well as the device.