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

# Staying on the Screen

Copied!
Happy Pythoning!

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:

Python
``````29# Move the sprite based on user keypresses
30def 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)
39
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 self.rect.top <= 0:
46        self.rect.top = 0
47    if self.rect.bottom >= SCREEN_HEIGHT:
48        self.rect.bottom = SCREEN_HEIGHT
``````
Copied!

KA

love these videos.

David Alvarez

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 self.rect.top > 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.

to join the conversation.