Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Staying on the Screen

In this lesson, you’ll add code to keep the player sprite from moving off the screen. After adding the code from the previous lesson, you may notice two small problems:

  1. The player rectangle can move very fast if a key is held down. You’ll work on that later.
  2. The player rectangle can move off the screen. Let’s solve that one now.

To keep the player on the screen, you need to add some logic to detect if the rect is going to move off screen. To do that, you check whether the rect coordinates have moved beyond the screen’s boundary. If so, then you instruct the program to move it back to the edge:

29 # Move the sprite based on user keypresses
30 def update(self, pressed_keys):
31     if pressed_keys[K_UP]:
32         self.rect.move_ip(0, -5)
33     if pressed_keys[K_DOWN]:
34         self.rect.move_ip(0, 5)
35     if pressed_keys[K_LEFT]:
36         self.rect.move_ip(-5, 0)
37     if pressed_keys[K_RIGHT]:
38         self.rect.move_ip(5, 0)
40     # Keep player on the screen
41     if self.rect.left < 0:
42         self.rect.left = 0
43     if self.rect.right > SCREEN_WIDTH:
44         self.rect.right = SCREEN_WIDTH
45     if <= 0:
46 = 0
47     if self.rect.bottom >= SCREEN_HEIGHT:
48         self.rect.bottom = SCREEN_HEIGHT

KA on May 17, 2020

love these videos.

David Alvarez on July 25, 2020

I kind of compressed the conditionals this way.

        if self.rect.bottom < SCREEN_HEIGHT and keys_pressed[K_DOWN]:
            self.rect.move_ip(0, 4)

        if > 0 and keys_pressed[K_UP]:
            self.rect.move_ip(0, -4)

        if self.rect.left > 0 and keys_pressed[K_LEFT]:
            self.rect.move_ip(-4, 0)

        if self.rect.right < SCREEN_WIDTH and keys_pressed[K_RIGHT]:
            self.rect.move_ip(4, 0)

I don’t know if there is any caveat in this implementation but seems to be working fine. Left side in the if expression it’s evaluated first if I’m not wrong.

Become a Member to join the conversation.