Microbit 上没有显示数字。

huangapple go评论70阅读模式
英文:

Digits not showing on Microbit

问题

我有这段代码:

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

"Score" 是一个整数,表示你的得分
Python 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?

答案1

得分: 0

以下是翻译好的部分:

"substr"参数的帮助信息如下:

> 参数
> - start:一个数字,表示要从该字符串中复制的起始位置。
> - length:一个数字,表示要从该字符串中复制的字符数量。

所以我认为问题在于您在循环中递增了 startlength

您可以将长度值硬编码为 1,因为您只想一次显示一个数字,例如:

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

在Python字符串上的 "substr" 在微:bit上的 Makecode Python 实现中非常特定。

在Python中更通用的方法(并且在Makecode中也有效)是:

def test_loop():
    # 随机得分
    score = randint(0, 999)
    # 逐个显示一个数字,而不是滚动
    str_score = str(score)
    for index in range(len(str_score)):
        basic.show_string(str_score[index])
    basic.show_icon(IconNames.HEART)
    # 在选择新数字之前暂停
    basic.pause(5000)

basic.forever(test_loop)

希望对您有所帮助。

英文:

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)

huangapple
  • 本文由 发表于 2023年6月11日 20:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定