如何将海龟发送到随机位置?
How to send turtle to random position?
我一直在尝试使用 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)
您要求的是 100 到 0 之间的数字。但是请查看 reference 的 randint()
:
random.randint(a, b)
Return a random integer N such that 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()
我一直在尝试使用 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)
您要求的是 100 到 0 之间的数字。但是请查看 reference 的 randint()
:
random.randint(a, b)
Return a random integer N such that 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()