Search code examples
pythonpython-3.xturtle-graphicspython-turtle

How to make boundaries work in turtle - python


So, I was making a game in which I need to move a player which is just a square as of now but it can go out of the screen if I keep pressing the key. I want to stop the player at the end of the screen. Here is my code this is not the complete game:

import turtle
sc=turtle.Screen()
sc.title("Math fighter")
sc.bgcolor("black")
sc.setup(width=1000, height=600)
player=turtle.Turtle()
player.speed(0)
player.shape("square")
player.color("white")
player.shapesize(stretch_wid=2, stretch_len=3)
player.penup()
player.goto(0, -250)
def playerleft():
    x = player.xcor()
    x -= 20
    player.setx(x)


def playerright():
    y = player.xcor()
    y += 20
    player.setx(y)
sc.listen()
sc.onkeypress(playerright, "Right")
sc.onkeypress(playerleft, "Left")

Solution

  • You need only use if to check position before setx() and skip it. That's all.

    def playerleft():
        x = player.xcor()
        x -= 20
    
        if x > -500:
            player.setx(x)
    
    
    def playerright():
        x = player.xcor()
        x += 20
    
        if x < 500:
           player.setx(x)