Menu
CoddyTech

Stay on Screen

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 7 of 32.

Hold Right long enough and the square leaves the window. To keep it in, limit x and y after you move them.

min(a, b) gives the smaller number and max(a, b) the bigger one. Together they hold a number between two limits:

x = max(0, min(x, 480 - 40))

min(x, 440) stops x from going past 440, and max(0, ...) stops it from going below 0. Why 440 and not 480? x is the square's left side, so the right side is at x + 40. At 440 the right side touches the window's edge.

The same goes for y, with the window's height.

challenge icon

Challenge

Easy

After the four arrow checks and before the fill, keep the square inside the 480 by 360 window: limit x to 0 through 440 and y to 0 through 320.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Move the Square")
clock = pygame.time.Clock()

x, y = 220, 160

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    speed = 4
    if keys[pygame.K_SPACE]:
        speed = 8
    if keys[pygame.K_LEFT]:
        x -= speed
    if keys[pygame.K_RIGHT]:
        x += speed
    if keys[pygame.K_UP]:
        y -= speed
    if keys[pygame.K_DOWN]:
        y += speed

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), (x, y, 40, 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground