0

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")
furas
  • 134,197
  • 12
  • 106
  • 148
  • 1
    you don't use PyGame so I removed tag `pygame` – furas Feb 27 '22 at 12:16
  • you have to use `if/else` to check position before `player.setx(...)` and skip it. That's all. – furas Feb 27 '22 at 12:17
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 28 '22 at 00:25

1 Answers1

0

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)
furas
  • 134,197
  • 12
  • 106
  • 148