import pygame from pygame.locals import * import os pygame.init() # Constants SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 FPS = 60 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Initialize screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Platformer Game') # Clock clock = pygame.time.Clock() # Load images bg_img = pygame.image.load('img/sky.png') sun_img = pygame.image.load('img/sun.png') player_img = pygame.image.load('img/player.png') door_img = pygame.image.load('img/door.png') # Scale images bg_img = pygame.transform.scale(bg_img, (SCREEN_WIDTH, SCREEN_HEIGHT)) sun_img = pygame.transform.scale(sun_img, (100, 100)) player_img = pygame.transform.scale(player_img, (50, 50)) door_img = pygame.transform.scale(door_img, (70, 70)) class Player(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.image = player_img self.rect = self.image.get_rect() self.rect.topleft = (x, y) self.vel_y = 0 self.jumping = False self.gravity = 1 def update(self, keys, platforms): # Horizontal movement if keys[K_LEFT]: self.rect.x -= 5 if keys[K_RIGHT]: self.rect.x += 5 # Vertical movement if keys[K_SPACE] and not self.jumping: self.vel_y = -15 self.jumping = True self.vel_y += self.gravity self.rect.y += self.vel_y # Simple ground collision if self.rect.bottom >= SCREEN_HEIGHT: self.rect.bottom = SCREEN_HEIGHT self.jumping = False self.vel_y = 0 # Platform collision if self.vel_y > 0: # only check for collision if falling hits = pygame.sprite.spritecollide(self, platforms, False) if hits: self.rect.bottom = hits[0].rect.top self.jumping = False self.vel_y = 0 class Platform(pygame.sprite.Sprite): def __init__(self, x, y, width, height): super().__init__() self.image = pygame.Surface((width, height)) self.image.fill(BLACK) self.rect = self.image.get_rect() self.rect.topleft = (x, y) # Create player instance player = Player(100, SCREEN_HEIGHT - 60) player_group = pygame.sprite.Group() player_group.add(player) # Create platforms platforms = pygame.sprite.Group() platform1 = Platform(200, SCREEN_HEIGHT - 150, 200, 10) platform2 = Platform(450, SCREEN_HEIGHT - 300, 200, 10) platform3 = Platform(300, SCREEN_HEIGHT - 450, 200, 10) platform4 = Platform(150, SCREEN_HEIGHT - 600, 200, 10) platforms.add(platform1) platforms.add(platform2) platforms.add(platform3) platforms.add(platform4) # Create door at the top door = pygame.sprite.Sprite() door.image = door_img door.rect = door.image.get_rect() door.rect.topleft = (350, 10) # Adjust the position as needed # Main game loop running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False keys = pygame.key.get_pressed() player_group.update(keys, platforms) screen.blit(bg_img, (0, 0)) screen.blit(sun_img, (700, 50)) platforms.draw(screen) player_group.draw(screen) screen.blit(door.image, door.rect.topleft) pygame.display.update() clock.tick(FPS) pygame.quit()