Stay on Screen
Lesson 7 of 41 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
EasyKeep the square inside the 480 by 360 window.
- After the four arrow tests, before the fill, limit
xto 0 through 440. - Limit
yto 0 through 320.
Press Play and hold an arrow: the square stops at the edge. Then Check.
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 Make Games with Pygame
1The Game Loop
Open a WindowFill the BackgroundPractice on your own: Pygame playground