Why does the turtle not respond to the y border?

Question:

I am making a turtle game with map borders, but my turtle only works with the x borders, just skipping the y ones. Anyone can help?

def gameplay():
    t.forward(10)
    t.heading()
    time.sleep(0.1) 
    sc.onkey(turnleft, "Left")
    sc.onkey(turnright, "Right")
    sc.listen()
    if t.distance(apple) < radius_sum:
        apple.goto(random.randrange(-500, 500), (random.randrange(-500, 500)))
    if t.position() >= (500,500):
        t.penup()
        t.back(1000)
        t.pendown()
    if t.position() <=(-500,-500):
        t.penup()
        t.back(1000)
        t.pendown()
Asked By: Klap

||

Answers:

As you’re aware, .position() returns an (x, y) tuple. You’re comparing that against another (x, y) tuple.

Let’s examine some of these comparisons and see if we get the correct results. We’ll use 5000 as a large value that’s clearly out of bounds on one axis or the other and 10 as a small value that’s clearly in bounds.

The expected outcome is that all return True, because they’re all out of bounds on one axis or the other.

>>> (-5000, 10) <= (-500, -500)
True
>>> (5000, -10) <= (-500, -500)
False
>>> (-5000, -10) <= (-500, -500)
True
>>> (5000, 10) <= (500, 500)
False
>>> (-10, -5000) <= (-500, -500)
False
>>> (-10, 5000) <= (-500, -500)
False
>>> (10, -5000) <= (-500, -500)
False
>>> (10, 5000) <= (500, 500)
True

Clearly, the Y values are being ignored, so comparing tuples like this won’t work for your use case. Try to compare the individual x and y positions separately.

The behavior for comparing tuples works like this: start at the leftmost element pair and compare them. If the values are different, evaluate the comparison. If they’re the same, move on to the next element and repeat the process until two elements are different and a comparison can be made. If one list runs out of elements before that happens, the other is greater. If they both run out at the same time and all elements were equal, the tuples are equal.

Answered By: ggorlen