【问题标题】:How to send turtle to random position?如何将乌龟发送到随机位置?
【发布时间】:2019-08-21 16:16:00
【问题描述】:

我一直在尝试使用goto() 将海龟发送到随机位置,但运行程序时出现错误。

我不知道如何做到这一点,并且不确定其他方式。 我当前的代码是:

t1.shape('turtle')
t1.penup()
t1.goto((randint(-100,0)),(randint(100,0)))#this is the line with the error

我希望海龟在 -100,100 和 0,100 之间的框中随机坐标,但出现错误:

Traceback (most recent call last):

File "C:\Users\samdu_000\OneDrive\Documents\python\battle turtles.py",    line 18, in <module>

t1.goto((randint(-100,0)),(randint(100,0)))

File "C:\Users\samdu_000\AppData\Local\Programs\Python\Python3732\lib\random.py", line 222, in randint

return self.randrange(a, b+1)

File "C:\Users\samdu_000\AppData\Local\Programs\Python\Python37-
32\lib\random.py", line 200, in randrange

raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, 
istop, width))

 ValueError: empty range for randrange() (100,1, -99)

【问题讨论】:

    标签: python random turtle-graphics


    【解决方案1】:

    您要的是 100 到 0 之间的数字。但请查看 reference 中的 randint()

    random.randint(a, b)

    返回一个随机整数 N,使得 a

    a 应小于或等于 b。因此,将randint(100,0) 替换为randint(0,100)

    import turtle
    from random import randint
    
    t1 = turtle.Turtle()
    
    t1.shape('turtle')
    t1.penup()
    t1.goto(randint(-100,0),randint(0,100))
    
    turtle.done()
    

    演示:https://repl.it/@glhr/55439167

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2019-09-17
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多