How to send turtle to random position?

2019-09-19 09:36发布

问题:

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

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)

回答1:

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

random.randint(a, b)

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

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

Demo: https://repl.it/@glhr/55439167