Jayaram
Jayaram

Reputation: 6606

Two turtles with random movements

I just started learning Python from interactivepython.org and am stuck with the below exercise:

Modify the turtle walk program so that you have two turtles each with a random starting location. Keep the turtles moving until one of them leaves the screen.

This is what I came up with. The program stops with 1 iteration and both turtles start from the same coordinates for some reason.

import turtle
import random

wn = turtle.Screen()

kj = turtle.Turtle()
saklep = turtle.Turtle()    
saklep.color('green')


c = random.randrange(1,100)
v = random.randrange(1,100)
b = random.randrange(1,100)
n = random.randrange(1,100)

kj.setx(c)
kj.sety(v)
saklep.setx(b)
saklep.sety(n)

def isinscreen(t,s,w):

    leftmost=-(w.window_width())/2
    rightmost =(w.window_width())/2
    uppermost = (w.window_height())/2
    bottommost =-(w.window_height())/2


    tx = t.xcor()
    ty = t.ycor()
    sx = s.xcor()
    sy = s.ycor()

    if tx > rightmost or ty >uppermost:
        return False
    elif tx < leftmost or ty < bottommost:
        return False
    elif sx > rightmost or sy > uppermost:
        return False
    elif sx < leftmost or sy < bottommost:
        return False
    else:
        return True


while isinscreen(kj,saklep,wn) == True:
    for i in random.randrange(1,361):
        kj.forward(100)
        kj.left(i)
    for deg in random.randrange(1,361):
        saklep.forward(100)
        saklep.right(deg)

wn.exitonclick()

Upvotes: 1

Views: 2384

Answers (1)

Jivan
Jivan

Reputation: 23068

I think you're mixing randrange with range. This line:

for i in random.randrange(1,361):

Triggers this error:

TypeError: 'int' object is not iterable on line 47

Because random.randrange(x,y) returns an int within x and y. Say for instance 13. Then what you're trying to do is the same a doing for i in 13, which doesn't work because for needs an iterable which 13 is not. You should do this instead:

my_random_number = random.randrange(1,361)
for i in range(1, my_random_number)

Check this answer for more informations about range.


Same comment for this line:

for deg in random.randrange(1,361):

Concerning the both turtles start at the same location problem, actually this is not true: by design, turtle.Turtle() seems to initialise a Turtle at location (0, 0) and draw it immediately. Then, when you assign kj and saklep some coordinates, it seems to be moving them with an animation.

Try only this portion of your code and you'll see that what I just described is happening:

import turtle
import random

wn = turtle.Screen()

kj = turtle.Turtle()
saklep = turtle.Turtle()    
saklep.color('green')

c = random.randrange(1,100)
v = random.randrange(1,100)
b = random.randrange(1,100)
n = random.randrange(1,100)

kj.setx(c)
kj.sety(v)
saklep.setx(b)
saklep.sety(n)

Upvotes: 4

Related Questions