Search code examples
pythonrandombbc-microbit

micro:bit python - random library only generates one number


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?


Solution

  • 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.