import pygame import sys # Initialize Pygame pygame.init() # Set up the display WIDTH, HEIGHT = 800, 600 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Mini Platformer") # Define colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Define constants PLAYER_SIZE = 40 PLAYER_COLOR = GREEN PLATFORM_WIDTH = 80 PLATFORM_HEIGHT = 20 PLATFORM_COLOR = RED PLAYER_SPEED = 5 JUMP_HEIGHT = -15 GRAVITY = 1 # Define game variables player_x = WIDTH // 2 player_y = HEIGHT // 2 player_vel_y = 0 platforms = [ pygame.Rect(200, 500, PLATFORM_WIDTH, PLATFORM_HEIGHT), pygame.Rect(400, 400, PLATFORM_WIDTH, PLATFORM_HEIGHT), pygame.Rect(600, 300, PLATFORM_WIDTH, PLATFORM_HEIGHT), ] clock = pygame.time.Clock() # Main game loop running = True while running: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Handle user input keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: player_x -= PLAYER_SPEED elif keys[pygame.K_RIGHT]: player_x += PLAYER_SPEED elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: # Check if player is on a platform before allowing jump player_rect = pygame.Rect(player_x, player_y, PLAYER_SIZE, PLAYER_SIZE) for platform in platforms: if player_rect.colliderect(platform): player_vel_y = JUMP_HEIGHT # Apply gravity player_vel_y += GRAVITY player_y += player_vel_y # Check for collisions with platforms player_rect = pygame.Rect(player_x, player_y, PLAYER_SIZE, PLAYER_SIZE) on_ground = False for platform in platforms: if player_rect.colliderect(platform) and player_vel_y >= 0: on_ground = True player_y = platform.top - PLAYER_SIZE player_vel_y = 0 # Update game objects # Render WIN.fill(BLACK) pygame.draw.rect(WIN, PLAYER_COLOR, (player_x, player_y, PLAYER_SIZE, PLAYER_SIZE)) for platform in platforms: pygame.draw.rect(WIN, PLATFORM_COLOR, platform) pygame.display.update() # Cap the frame rate clock.tick(60) # Quit Pygame pygame.quit() sys.exit()