import pygame pygame.init() screen_size = (600, 600) screen = pygame.display.set_mode(screen_size) square_size = 50 num_squares = screen_size[0] // square_size squares = [] for i in range(num_squares): row = [] for j in range(num_squares): square_rect = pygame.Rect(j * square_size, i * square_size, square_size, square_size) row.append(square_rect) squares.append(row) object_rect = pygame.Rect(0, 0, square_size, square_size) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: if object_rect.top > 0: object_rect.top -= square_size elif event.key == pygame.K_DOWN: if object_rect.bottom < screen_size[1]: object_rect.top += square_size elif event.key == pygame.K_LEFT: if object_rect.left > 0: object_rect.left -= square_size elif event.key == pygame.K_RIGHT: if object_rect.right < screen_size[0]: object_rect.left += square_size screen.fill((255, 255, 255)) for row in squares: for square_rect in row: pygame.draw.rect(screen, (0, 0, 0), square_rect, 1) pygame.draw.rect(screen, (255, 0, 0), object_rect) pygame.display.flip()