# Homework 34 solution, problem 3: follow the mouse. # Run with: python exercises/34/homework/solutions/03-follow-mouse.py import pygame pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Follow Mouse") clock = pygame.time.Clock() rect = pygame.Rect(370, 270, 50, 50) speed = 5 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False mx, my = pygame.mouse.get_pos() dx = mx - rect.centerx dy = my - rect.centery if abs(dx) > speed: rect.x += speed if dx > 0 else -speed else: rect.centerx = mx if abs(dy) > speed: rect.y += speed if dy > 0 else -speed else: rect.centery = my screen.fill((20, 20, 20)) pygame.draw.rect(screen, (255, 200, 50), rect) pygame.display.flip() clock.tick(60) pygame.quit()