我一直试图使用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)
答案 0 :(得分:1)
您要输入100到0之间的数字。但是请注意randint()
的{{3}}:
random.randint(a,b)
返回一个随机整数N,使a <= N <= b。
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()
演示:reference