import pygame, sys def bouncing_rect(): global x_speed, y_speed, other_speed move_rect.x += x_speed move_rect.y += y_speed #Collisions if move_rect.right >= screen_w or move_rect.left <= 0: x_speed *= -1 if move_rect.bottom >= screen_h or move_rect.top <= 0: y_speed *= -1 #Move other rect other_rect.y += other_speed if other_rect.top <= 0 or other_rect.bottom >= screen_h: other_speed *= -1 #Collision with rect collision_tol = 33 if move_rect.colliderect(other_rect): if abs(other_rect.top - move_rect.bottom) < collision_tol and y_speed > 0: y_speed *= -1 if abs(other_rect.bottom - move_rect.top) < collision_tol and y_speed < 0: y_speed *= -1 if abs(other_rect.right - move_rect.left) < collision_tol and x_speed < 0: x_speed *= -1 if abs(other_rect.left - move_rect.right) < collision_tol and x_speed > 0: x_speed *= -1 pygame.draw.rect(screen, (255,255,255), move_rect) pygame.draw.rect(screen, (255,0,0), other_rect) pygame.init() clock = pygame.time.Clock() screen_w, screen_h = 800, 800 screen = pygame.display.set_mode((screen_w, screen_h)) move_rect = pygame.Rect(350,350,50,50) x_speed, y_speed = 5,4 other_rect = pygame.Rect(300,600,200,100) other_speed = 4 while True : for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: print("key_board input -> Exit") pygame.quit() sys.exit() screen.fill((30,30,30)) bouncing_rect() pygame.display.flip() clock.tick(60)