Menu
CoddyTech

Stay on Screen

Lesson 7 of 40 in Coddy's Make Games with Pygame course.

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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground