Search code examples
pythonbbc-microbit

Digits not showing on Microbit


I have this code:

for i in range(len(str(score))):
        basic.show_string((str(score)).substr(i, i))
        basic.pause(500)

Score is an int that is your score No errors in the Python Microbit editor

So this code is supposed to go through every digit of the score and display each one for a brief moment and then go to the next one, except that it shows a blank screen. Why and how do i fix this?


Solution

  • The help for the substr parameters is:

    Parameters

    • start: a number which is the position to start copying from in this string.
    • length: a number which is the amount of characters to copy from this string.

    So I think the issues is that you have start and length incrementing in the loop.

    You could hard code the length value as 1 as you only want to display one digit at a time. e.g.

    for i in range(len(str(score))):
            basic.show_string((str(score)).substr(i, 1))
            basic.pause(500)
    

    substr on a Python string is very specific to the Makecode implementation of Python on the micro-bit.

    A more generic way of doing this in Python (and works in Makecode) is:

    def test_loop():
        # Random score
        score = randint(0, 999)
        # Display one digit at a time rather than scroll
        str_score = str(score)
        for index in range(len(str_score)):
            basic.show_string(str_score[index])
        basic.show_icon(IconNames.HEART)
        # Pause before picking new number
        basic.pause(5000)
    
    basic.forever(test_loop)