python - 如何将乌龟发送到随机位置?
问题描述
我一直在尝试使用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 之间的数字。但请查看参考randint()
:
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()
推荐阅读
- mysql - 从mysql中具有不同指针的多表中计数
- python - 访问变量时,python可以“按需”从文件中加载数据吗?
- swift - 向 Base64 字符串添加填充的 Swift 将返回较小的字符串
- wordpress - 如何在使用 WPForms 提交时不清除表单
- css - React Native Image 未以 View 为中心
- javascript - 未定义的 ERROR javascript 值,中间有空格
- reactjs - 我想学习如何使用 populate() 和 aggregate()
- python - 是否有任何代码可用于在 JSON 中查找完整案例?
- flutter - Flutter 动画翻译 2 种不同的动作
- python-3.x - 如何使用 BeautifulSoup 在某个部分进行解析