import pygame import sys import random # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 CUBE_SIZE = 30 FPS = 60 SPEED = 15 # Colors WHITE = (255, 255, 255) RED = (255, 0, 0) # Create the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Bouncing and Adding Cube Example") # Clock to control the frame rate clock = pygame.time.Clock() # Class to represent a cube class Cube: def __init__(self, x, y, direction=None): self.rect = pygame.Rect(x, y, CUBE_SIZE, CUBE_SIZE) if direction is None: direction = random.choice([(1, 0), (-1, 0), (0, 1), (0, -1)]) self.direction = direction def move(self): self.rect.x += SPEED * self.direction[0] self.rect.y += SPEED * self.direction[1] def bounce(self): # Reverse the direction when bouncing off the wall self.direction = (-self.direction[0], -self.direction[1]) def draw(self): pygame.draw.rect(screen, RED, self.rect) # Create the initial cube current_cube = Cube(WIDTH // 2 - CUBE_SIZE // 2, HEIGHT // 2 - CUBE_SIZE // 2) cubes = [current_cube] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Move all the cubes for cube in cubes: cube.move() # Check if the cube hits the wall if cube.rect.left < 0 or cube.rect.right > WIDTH or \ cube.rect.top < 0 or cube.rect.bottom > HEIGHT: # Bounce off the wall cube.bounce() # Create a new cube at a random position new_cube = Cube(random.randint(0, WIDTH - CUBE_SIZE), random.randint(0, HEIGHT - CUBE_SIZE)) cubes.append(new_cube) # Draw the cubes screen.fill(WHITE) for cube in cubes: cube.draw() pygame.display.flip() clock.tick(FPS)