Python Turtle collision with screen boundaries

Question:

How do I make the collision? so the turtle/snake doesn’t go out of the box. I’m trying to make them stay inside the (-200, -200) and (200, 200).

from turtle import *
from random import *

def bounding_box():
    up()
    right(90)
    forward(200)
    down()
    left(90)
    forward(200)
    left(90)
    forward(400)
    left(90)
    forward(400)
    left(90)
    forward(400)
    left(90)
    forward(200)
    up()
    goto(0,0)
    down()

def drawSnakeRec(segments, length):
    if segments <= 0 or length <= 0:
        return 0
    else:
        color(random(), random(), random())
        forward(length)
        pensize(randint(1,10))
        left(randint(-30, 30))
        return length + drawSnakeRec(segments - 1, randint(1,20))

def drawSnakeIter(segments, length):
    TL = 0
    while segments > 0:
        color(random(), random(), random())
        pensize(randint(1,10))
        forward(length)
        left(randint(-30, 30))
        TL += length
        segments -=1
    return TL


def main():
    segments = int(input("Enter the segments between 0 and 500: "))

    bounding_box()

    hideturtle()
    speed('fast')
    
    if segments < 0 or segments > 500:
        print("Segments is out of range. Segment must be between 0 and 500 inclusive")
        input("Press enter to close")
    else:
        
        x = drawSnakeRec(segments, randint(1, 20))
        print("Recursive Snake's Length is:",x,"Units")
        input("Press Enter to go on Iterative Snake")
        up()
        goto(0,0)
        reset()
        bounding_box()
        y = drawSnakeIter(segments, randint(1,20))
        print("Iterative Snake's Length is:",y," Units")
        input("Press Enter to exit...")
        bye()
main()
Asked By: Singh2013

||

Answers:

In both the recursive version and the iterative version, you’re turning a random direction and moving forward a random length. If you want to avoid the bounding box, these numbers need to know that the bounding box is there.

There are few things you could do, depending on the kind of behavior you want. Probably the easiest would be to put in a check if the new coordinate is outside of the box, and if so, change course appropriately.

If you want it to gradually avoid the box, you could factor in the distance to the nearest edge in either the turning or moving decisions.

In either case, turtle.pos() will be helpful.

Answered By: accidental_PhD

I suggest a large if like:

if turtle.ycor() >= 200 or turtle.ycor() <=-200 or  turtle.xcor() >= 200 or turtle.xcor <= -200

This worked for me!

Answered By: E1247L