After I got the hang of my previous programme (the turtle that walked randomly and bounced off the walls until it hit them 4 times), I tried doing the following exercise in the guide, which asks for two turtles with random starting locations that walk around the screen and bounce off the walls until they bump into each other – no counter variable to decide when they should stop. I managed to write the entire thing except for the part where they collide and stop: I figured a boolean function that returns True
if the turtles' X and Y coordinates are the same and False
if they aren't would do the job, but instead they keep walking and the only way to terminate the programme is to force the interpreter to quit. What am I doing wrong?
import turtle
import random
def setStart(t):
tx = random.randrange(-300,300,100)
ty = random.randrange(-300,300,100)
t.penup()
t.goto(tx,ty)
t.pendown()
def throwCoin(t):
coin = random.randrange(0,2)
if coin == 0:
t.left(90)
else:
t.right(90)
def isInScreen(w,t):
leftBound = w.window_width() / -2
rightBound = w.window_width() / 2
bottomBound = w.window_height() / -2
topBound = w.window_height() / 2
turtlex = t.xcor()
turtley = t.ycor()
stillIn = True
if turtlex < leftBound or turtlex > rightBound or turtley < bottomBound or turtley > topBound:
stillIn = False
return stillIn
def collide(t,u):
if t.xcor() == u.xcor() and t.ycor() == u.ycor():
return True
return False
def randomWalk(t,w):
if not isInScreen(w,t):
t.left(180)
else:
throwCoin(t)
t.forward(100)
def doubleRandom(t,u,w):
while not collide(t,u):
randomWalk(t,w)
if collide(t,u):
break
randomWalk(u,w)
wn = turtle.Screen()
wn.bgcolor('lightcyan')
steklovata = turtle.Turtle()
steklovata.color('darkslategray')
steklovata.shape('turtle')
setStart(steklovata)
catshower = turtle.Turtle()
catshower.color('orangered')
catshower.shape('turtle')
setStart(catshower)
doubleRandom(steklovata,catshower,wn)
wn.exitonclick()
EDIT: in order to test whether the bug was in the collide(t,u)
function or in the while
loop that calls it, I wrote another function that sends both turtles to the same spot and prints out some text (if anyone's wondering, it's an inside joke, like every flipping name I come up with) if collide(t,u)
returns True
. When I ran it the text DID print out, which tells me that the collision detection is working properly... but the loop somehow isn't telling Python that the turtles should stop when they collide. This is the function:
def raul(t,u,w):
t.goto(1,1)
u.goto(1,1)
if collide(t,u):
t.write('RAUL SUNTASIG')
Does this give you guys any ideas as to why it's not working?