import pygame import sys # Initialize Pygame pygame.init() # Screen dimensions WIDTH, HEIGHT = 800, 600 SCREEN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Platformer Game") # Colors WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) # Clock clock = pygame.time.Clock() FPS = 60 # Gravity GRAVITY = 0.8 # Player class 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 = HEIGHT - 150 self.vel_y = 0 self.jumping = 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 # Jumping if keys[pygame.K_SPACE] and not self.jumping: self.vel_y = -15 self.jumping = True # Apply gravity self.vel_y += GRAVITY dy = self.vel_y # Collision with platforms for platform in platforms: if platform.rect.colliderect(self.rect.x, self.rect.y + dy, self.rect.width, self.rect.height): if self.vel_y > 0: dy = platform.rect.top - self.rect.bottom self.vel_y = 0 self.jumping = False # Update position self.rect.x += dx self.rect.y += dy # Keep within screen if self.rect.left < 0: self.rect.left = 0 if self.rect.right > WIDTH: self.rect.right = WIDTH if self.rect.bottom > HEIGHT: self.rect.bottom = HEIGHT self.jumping = False # Platform class class Platform(pygame.sprite.Sprite): def __init__(self, x, y, width, height): super().__init__() self.image = pygame.Surface((width, height)) self.image.fill(GREEN) self.rect = self.image.get_rect(topleft=(x, y)) # Create player and platforms player = Player() platforms = pygame.sprite.Group() platforms.add(Platform(0, HEIGHT - 40, WIDTH, 40)) # Ground platforms.add(Platform(200, 450, 120, 20)) platforms.add(Platform(400, 350, 120, 20)) platforms.add(Platform(600, 250, 120, 20)) all_sprites = pygame.sprite.Group() all_sprites.add(player) all_sprites.add(*platforms) # Game loop running = True while running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Update player.update(platforms) # Draw SCREEN.fill(WHITE) all_sprites.draw(SCREEN) pygame.display.flip() pygame.quit() sys.exit()