import pygame import sys # Initialize Pygame pygame.init() # Screen dimensions SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("2D Platformer") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) BLUE = (0, 0, 255) GREEN = (0, 255, 0) # Player settings player_size = 50 player_color = BLUE player_x = SCREEN_WIDTH // 2 player_y = SCREEN_HEIGHT - player_size player_speed = 5 player_jump = 10 player_velocity_y = 0 gravity = 0.5 # Platform settings platforms = [ pygame.Rect(100, 500, 200, 10), pygame.Rect(400, 400, 200, 10), pygame.Rect(200, 300, 200, 10) ] # Game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Get keys pressed keys = pygame.key.get_pressed() # Player movement if keys[pygame.K_LEFT]: player_x -= player_speed if keys[pygame.K_RIGHT]: player_x += player_speed # Player jump if keys[pygame.K_SPACE] and player_y == SCREEN_HEIGHT - player_size: player_velocity_y = -player_jump # Apply gravity player_velocity_y += gravity player_y += player_velocity_y # Check for collision with the ground if player_y >= SCREEN_HEIGHT - player_size: player_y = SCREEN_HEIGHT - player_size player_velocity_y = 0 # Check for collision with platforms for platform in platforms: if platform.colliderect(player_x, player_y, player_size, player_size): player_y = platform.top - player_size player_velocity_y = 0 # Clear screen screen.fill(WHITE) # Draw player pygame.draw.rect(screen, player_color, (player_x, player_y, player_size, player_size)) # Draw platforms for platform in platforms: pygame.draw.rect(screen, BLACK, platform) # Update display pygame.display.flip() # Cap the frame rate pygame.time.Clock().tick(60)