How do I add borders to my turtle screen?

Question:

So I am creating a code version of the snake game. I want to add in a piece of code where if the snake touches either sides of the borders of the screen, the game is over and the program closes. I already know how to set the size of the screen and all that. I looked at a lot of resources to help me solve this issue but none of them helped. I even looked at the python directory and that didn’t help. If there is any line of code for me to set these borders and cancel the program when the snake touches those borders, I would appreciate that.

Asked By: Abdullah Alejel

||

Answers:

I don’t think you’ve searched hard enough, as something like “python turtle collision detection” returns quite a bit of examples of what you want. Also, the rules state to post a minimal verifiable example of your problem so we know how to help you better – it would be useful to know how the screen is defined, etc…

Aside from that, it should be as simple as:

if turtle.ycor() >= maxY or turtle.ycor() <= minY or turtle.xcor() >= maxX or turtle.xcor <= minX:
     turtle.bye()
     sys.exit(0)

…from looking at the documentation here: turtle.

Answered By: xen20

Although @xen20 explains the gist of a solution, I want to make sure you’re also aware of the window_width() and window_height() methods:

import sys
import turtle

width, height = turtle.window_width(), turtle.window_height()

minX, maxX = -width/2, width/2
minY, maxY = -height/2, height/2

def repeated_code():

    turtle.forward(20)  # keep moving forward until we're out of window

    if not minX <= turtle.xcor() <= maxX or not minY <= turtle.ycor() <= maxY:
        turtle.bye()
        sys.exit("Finished.")  # if we don't exit() a Terminator will be raised

    turtle.ontimer(repeated_code, 100)  # repeat every 1/10th of a second

repeated_code()

turtle.mainloop()  # turn over control to tkinter event loop

Visually, you’ll find your minX, maxX, etc. aren’t perfect due to the chrome (borders, title bar, scroll bars, etc.) on the window. You’ll find it’s worse in the Y dimension due to the size of the title bar. I don’t know of a way within turtle to calculate this difference, other than guess. There may be a solution to be found in the underlying tkinter library.

Answered By: cdlane
import turtle

width, height = turtle.window_width(), turtle.window_height()

minX, maxX = -width/2, width/2
minY, maxY = -height/2, height/2

def repeated_code():

    turtle.forward(20)

    if not minX <= turtle.xcor() <= maxX or not minY <= turtle.ycor() <= maxY:
        turtle.bye()
        SystemExit("Finished.")

    turtle.ontimer(repeated_code, 100)

repeated_code()

turtle.mainloop()
Answered By: AbrorPlayz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.