Search code examples
pythonpython-turtle

How to detect the edge of a window in python


I was trying to make a worm AI thingy that moves around using python turtle and , but I don’t know how to detect the edge of the turtle window for it do evade it. pls help


Solution

  • You can get window's width

    WIDTH = screen.window_width()
    

    and then turtle may have position x in range -WIDTH/2 ... WIDTH/2 and you can do

    x, y = turtle.pos()
    
    if x > WIDTH/2:
        turtle.setx(-WIDTH/2)
    
    if x < -WIDTH/2:
        turtle.setx(WIDTH/2)
    
    

    Similar you can do for position y and window_height().


    Minimal working example:

    import turtle
    
    screen = turtle.Screen()
    WIDTH = screen.window_width()
    
    t = turtle.Turtle()
    t.penup()
    t.speed(0)
    
    while True:
        t.forward(5)
        x, y = t.pos()
        if x > WIDTH/2:
            t.setx(-WIDTH/2)
        screen.update()
    

    EDIT:

    More complex version with 10 turtles which move like in game Asteroid

    import turtle
    
    def check_border(t):
        x, y = t.pos()
    
        if x > WIDTH/2:
            t.setx(-WIDTH/2)
            #x -= WIDTH
            #t.setx(x)
        if x < -WIDTH/2:
            t.setx(WIDTH/2)
            #x += WIDTH
            #t.setx(x)
            
        if y > HEIGHT/2:
            t.sety(-HEIGHT/2)
            #y -= HEIGHT
            #t.sety(y)
        if y < -HEIGHT/2:
            t.sety(HEIGHT/2)
            #y += HEIGHT
            #t.sety(y)
        
    # --- main --
    
    screen = turtle.Screen()
    WIDTH  = screen.window_width()
    HEIGHT = screen.window_height()
    
    all_turtles = []
    for angle in range(0, 360, 36):
        t = turtle.Turtle()
        t.penup()
        t.speed(0)
        t.left(angle)
        all_turtles.append(t)
    
    while True:
    
        for t in all_turtles:    
            t.forward(15)
            check_border(t)
            
        screen.update()