import pygame import sys # Constants SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 FPS = 60 GRAVITY = 0.8 WHITE = (255, 255, 255) BLUE = (50, 50, 255) GREEN = (0, 200, 0) BLACK = (0, 0, 0) pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) clock = pygame.time.Clock() pygame.display.set_caption("Multi-Level Platformer") class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((40, 60)) self.image.fill(BLUE) self.rect = self.image.get_rect() self.rect.x = 100 self.rect.y = 500 self.vel_y = 0 self.jump_power = -15 self.on_ground = False def update(self, platforms): keys = pygame.key.get_pressed() dx = 0 if keys[pygame.K_LEFT]: dx = -5 if keys[pygame.K_RIGHT]: dx = 5 self.vel_y += GRAVITY dy = self.vel_y # Move horizontally self.rect.x += dx # Collision in x for platform in platforms: if self.rect.colliderect(platform.rect): if dx > 0: self.rect.right = platform.rect.left if dx < 0: self.rect.left = platform.rect.right # Move vertically self.rect.y += dy # Collision in y self.on_ground = False for platform in platforms: if self.rect.colliderect(platform.rect): if dy > 0: self.rect.bottom = platform.rect.top self.vel_y = 0 self.on_ground = True if dy < 0: self.rect.top = platform.rect.bottom self.vel_y = 0 # Jump if keys[pygame.K_SPACE] and self.on_ground: self.vel_y = self.jump_power # Keep on screen if self.rect.left < 0: self.rect.left = 0 if self.rect.right > SCREEN_WIDTH: self.rect.right = SCREEN_WIDTH class Platform(pygame.sprite.Sprite): def __init__(self, x, y, w, h): super().__init__() self.image = pygame.Surface((w, h)) self.image.fill(GREEN) self.rect = self.image.get_rect(topleft=(x, y)) # Define levels levels = [ [ Platform(0, 550, 800, 100), Platform(120, 400, 70, 13), Platform(4,500, 70, 14), ], Platform(0, 550, 800, 100), Platform(120, 400, 70, 13), Platform(14,500, 70, 14), [ Platform(0, 550, 800, 100), Platform(200, 395, 70, 13), Platform(40,500, 70, 14), ], ], def load_level(level_num): return pygame.sprite.Group(*levels[level_num]) def main(): level_num = 0 platforms = load_level(level_num) player = Player() all_sprites = pygame.sprite.Group(player, *platforms) while True: screen.fill(WHITE) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() player.update(platforms) # Level transition if player.rect.right >= SCREEN_WIDTH and level_num < len(levels) - 1: level_num += 1 player.rect.left = 0 platforms = load_level(level_num) all_sprites = pygame.sprite.Group(player, *platforms) all_sprites.draw(screen) pygame.display.flip() clock.tick(FPS) if __name__ == "__main__": main()