import pygame import os # Initialize Pygame pygame.init() # Screen settings screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("2D Platformer") # Load player animations def load_images(folder, prefix, count): return [pygame.image.load(os.path.join(folder, f"{prefix} ({i}).png")) for i in range(1, count + 1)] idle_images = load_images('Images/Player', 'idle', 16) run_images = load_images('Images/Player', 'run', 20) jump_images = load_images('Images/Player', 'jump', 30) # Player settings class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.images = { 'idle': idle_images, 'run': run_images, 'jump': jump_images } self.image = self.images['idle'][0] self.rect = self.image.get_rect() self.rect.center = (400, 300) self.vel = pygame.math.Vector2(0, 0) self.speed = 5 self.gravity = 0.5 self.jump_power = -12 self.on_ground = True self.jumping = False self.facing_right = True self.frame = 0 self.animation_speed = 0.1 def update(self): keys = pygame.key.get_pressed() # Horizontal movement if keys[pygame.K_LEFT]: self.vel.x = -self.speed self.facing_right = False elif keys[pygame.K_RIGHT]: self.vel.x = self.speed self.facing_right = True else: self.vel.x = 0 # Jumping if (keys[pygame.K_UP] or keys[pygame.K_SPACE]) and self.on_ground: self.vel.y = self.jump_power self.on_ground = False self.jumping = True # Apply gravity self.vel.y += self.gravity # Update player position self.rect.x += self.vel.x self.rect.y += self.vel.y # Screen collision if self.rect.left < 0: self.rect.left = 0 if self.rect.right > 800: self.rect.right = 800 if self.rect.bottom > 600: self.rect.bottom = 600 self.on_ground = True self.jumping = False self.vel.y = 0 # Animation handling if self.jumping: self.frame = (self.frame + self.animation_speed) % len(self.images['jump']) self.image = self.images['jump'][int(self.frame)] elif self.vel.x != 0: self.frame = (self.frame + self.animation_speed) % len(self.images['run']) self.image = self.images['run'][int(self.frame)] else: self.frame = (self.frame + self.animation_speed) % len(self.images['idle']) self.image = self.images['idle'][int(self.frame)] # Flip sprite if not self.facing_right: self.image = pygame.transform.flip(self.image, True, False) # Sprite group all_sprites = pygame.sprite.Group() player = Player() all_sprites.add(player) # Game loop running = True clock = pygame.time.Clock() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Update all_sprites.update() # Draw screen.fill((135, 206, 235)) # Sky blue background all_sprites.draw(screen) # Display update pygame.display.flip() clock.tick(120) pygame.quit()