Skip to content Skip to sidebar Skip to footer

Python3.2 How To Keep Turtle From Going Off The Screen And When It Does Reset?

I am writing a simple project with pygame and turtle graphics. They aren't integrated together. I want it so that when my turtle moves off the screen it bounces off. I looked for a

Solution 1:

You can do something like:

screen_rect  = Rect(0, 0, 1600, 900)
player_rect = player.image.get_rect() 

if player.rect.right > screen_rect.right:
    player.xvel *= -1
else if player.rect.left < 0:
    player.xvel *= -1

if player.rect.bottom > screen_rect.bottom:
    player.yvel *= -1
else if player.rect.top < 0:
    player.yvel *= -1

You can check if you are off-screen, by:

if not screen_rect.contains(player_rect):
    print("turtle escaped screen")

http://www.pygame.org/docs/ref/rect.html


Solution 2:

I know this is my own question but I needed an answer that worked well so I added this to the character class:

if self.x < 0:
    self.x = 3
if self.x > 800:
    self.x = 790
if self.y < 0:
    self.y = 3
if self.y > 800:
    self.y = 790

Post a Comment for "Python3.2 How To Keep Turtle From Going Off The Screen And When It Does Reset?"