After I hung up my previous program (a turtle that walked randomly and bounced off the walls until it hit them 4 times), I tried to do the next exercise in the guide, which suggests two turtles with random starting points that walk along the screen and bounce off the walls until they shake each other - there is no counting variable to decide when they should stop. I managed to write the whole thing, except for the part where they collide and stop: I calculated a logical function that returns True if the X and Y coordinates of the turtles are the same, and False if they donβt, but instead they continue to go, and the only The way to terminate the program is to make the translator exit the game. 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: to check if there was an error in the collide(t,u) function or in the while that calls it, I wrote another function that sends both turtles to the same place and prints some text (if someone wonders if this is an internal joke, like every flipping name I came up with), if collide(t,u) returns True . When I ran it, the DID text printed, indicating that collision detection was working correctly ... but the loop somehow did not tell 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 doesn't work?