Search code examples
pythonturtle-graphicspython-turtle

Is there a way to check if a turtle is touching a color?


I am tryng to make a game with edge walls and inner walls but I don't know how to sense if the turtle is touching the inner wall(the outer wall checks turtles position and moves him back). My outer wall code is this:

import turtle
t = turtle.Turtle()
if t.xcor() >= 425:
        t.setx(424)
    if t.xcor() <= -425:
        t.setx(-424)
    if t.ycor() >= 375:
        t.sety(374)
    if t.ycor() <= -350:
        t.sety(-349)

and my walls should look like this: in the middle of the turtle screen

in the center of turtle screen


Solution

  • Assuming your graph is something like this: enter image description here

    Here is how:

    if -350 < turtle.xcor() < 350 and -325 < turtle.ycor() < 325: # For A
        if turtle.xcor() >= 350:
            turtle.setx(349)
        if turtle.xcor() <= -350 and (25 < turtle.ycor() < 325 or -25 > turtle.ycor() > -325):
            turtle.setx(-349)
        if turtle.ycor() >= 325:
            turtle.sety(324)
        if turtle.ycor() <= -325:
            turtle.sety(-324)
    
    if -25 < turtle.ycor() < 25 and -425 < turtle.xcor() < -350: # For B
        if turtle.ycor() > 25:
            turtle.sety(24)
        if turtle.ycor() < -25:
            turtle.sety(-24)