import pygame # Homework: move a rectangle with WASD keys but stop it at the screen edges. # The rectangle is 50x50. Use pygame.key.get_pressed() to read held keys. # After updating the position, clamp it so it cannot go outside the window. # Hint: use max() and min() to clamp a value. # x = max(0, min(x, screen_width - rect_width)) pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Bounded Move") clock = pygame.time.Clock() BG = (20, 20, 20) GREEN = (60, 180, 80) SIZE = 50 x = 295 y = 215 speed = 4 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False keys = pygame.key.get_pressed() # TODO: move x left/right with A/D keys # TODO: move y up/down with W/S keys # TODO: clamp x so the rect stays inside 0 to 640-SIZE # TODO: clamp y so the rect stays inside 0 to 480-SIZE screen.fill(BG) pygame.draw.rect(screen, GREEN, (x, y, SIZE, SIZE)) pygame.display.flip() clock.tick(60) pygame.quit()