如何将乌龟发送到随机位置? [英] How to send turtle to random position?

查看:134
本文介绍了如何将乌龟发送到随机位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to use goto() to send turtles to a random position but I get an error when running the program.

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

I am lost on how else to do this and not sure of other ways. My current code is:

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

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

I want the turtle to go to random coordinates in a box between -100,100 and 0,100 but I get the error:

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():

You're asking for a number between 100 and 0. But look at the reference for randint():

random.randint(a, b)

random.randint(a, b)

返回一个随机整数 N,使得 a <= N <= b.

Return a random integer N such that a <= N <= b.

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

a should be smaller or equal to b. So, replace randint(100,0) with 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

这篇关于如何将乌龟发送到随机位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆