Reputation: 25
I made a simple game, where the user needs to get back to the same position in a specified number of moves. However, the code to do with the positioning that recognises whether the user has returned to the initial position does not seem to work.
This is the code that specifies the starting positioning of the turtle just in case:
my_turtle.setposition(0.00, 0.00)
Here is that code (only the part that deals with the positioning):
if my_turtle.position() == (0.00, 0.00) and tries == score:
print("Well done")
break
elif my_turtle.position() == (0.00, 0.00) and (tries > score or score > tries):
print("Return to original position in exactly moves")
Upvotes: 0
Views: 56
Reputation: 41872
Turtles wander a floating point plane. As your turtle moves beyond home (0, 0)
about the screen and eventually returns, it can accumlate some floating point noise, e.g. (0.0001, -0.000)
. So using an integer comparison like ==
won't work. Instead we can use the distance()
method:
if my_turtle.distance(0, 0) < 10:
if tries == score:
print("Well done")
break
print("Return to original position in exactly moves")
The distance()
method is flexible in that along with separate coordinates, it can also accept a tuple coordinate, or even another turtle!
Upvotes: 2
Reputation: 27567
The reason might be because it is very difficult to get the turtle to go to point (0,0) exactly, so it might be better to set boundaries instead:
if 10>my_turtle.xcor()>-10 and 10>my_turtle.ycor()>-10 and tries == score:
print("Well done")
break
elif 10>my_turtle.xcor()>-10 and 10>my_turtle.ycor()>-10 and tries != score:
print("Return to original position in exactly moves")
Upvotes: 2