import pygame import sys # Initialize Pygame pygame.init() # Screen dimensions SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 FPS = 60 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) # Player properties PLAYER_WIDTH = 50 PLAYER_HEIGHT = 50 PLAYER_COLOR = RED PLAYER_GRAVITY = 0.5 PLAYER_JUMP_STRENGTH = -10 # Platform properties PLATFORM_WIDTH = 100 PLATFORM_HEIGHT = 20 PLATFORM_COLOR = BLACK # Create the screen screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Platformer with Floor") # Clock object to control the frame rate clock = pygame.time.Clock() # Define the player object player = pygame.Rect(SCREEN_WIDTH // 2 - PLAYER_WIDTH // 2, SCREEN_HEIGHT // 2 - PLAYER_HEIGHT // 2, PLAYER_WIDTH, PLAYER_HEIGHT) player_velocity_x = 0 player_velocity_y = 0 player_jump = False # Define multiple platforms platforms = [ pygame.Rect(100, SCREEN_HEIGHT - 100, PLATFORM_WIDTH, PLATFORM_HEIGHT), pygame.Rect(300, SCREEN_HEIGHT - 200, PLATFORM_WIDTH, PLATFORM_HEIGHT), pygame.Rect(500, SCREEN_HEIGHT - 300, PLATFORM_WIDTH, PLATFORM_HEIGHT), pygame.Rect(200, SCREEN_HEIGHT - 400, PLATFORM_WIDTH, PLATFORM_HEIGHT) ] # Define the floor (ground platform) floor = pygame.Rect(0, SCREEN_HEIGHT - PLATFORM_HEIGHT, SCREEN_WIDTH, PLATFORM_HEIGHT) def handle_movement(): global player_velocity_x, player_velocity_y, player_jump keys = pygame.key.get_pressed() # Horizontal movement if keys[pygame.K_LEFT]: player_velocity_x = -5 elif keys[pygame.K_RIGHT]: player_velocity_x = 5 else: player_velocity_x = 0 # Jump if keys[pygame.K_SPACE] and not player_jump: player_velocity_y = PLAYER_JUMP_STRENGTH player_jump = True def update_player(): global player_velocity_y, player_jump # Apply gravity player_velocity_y += PLAYER_GRAVITY # Update player position player.x += player_velocity_x player.y += player_velocity_y # Check collision with platforms on_platform = False for plat in platforms: if player.colliderect(plat): if player_velocity_y > 0: # Falling down player.y = plat.top - PLAYER_HEIGHT player_velocity_y = 0 player_jump = False on_platform = True elif player_velocity_y < 0: # Moving up player.y = plat.bottom player_velocity_y = 0 # Check collision with the floor if player.colliderect(floor): if player_velocity_y > 0: # Falling down player.y = floor.top - PLAYER_HEIGHT player_velocity_y = 0 player_jump = False if not on_platform and player.y + PLAYER_HEIGHT < SCREEN_HEIGHT: player_jump = True # Allow jumping if not on a platform def draw(): screen.fill(WHITE) pygame.draw.rect(screen, PLAYER_COLOR, player) for plat in platforms: pygame.draw.rect(screen, PLATFORM_COLOR, plat) pygame.draw.rect(screen, PLATFORM_COLOR, floor) # Draw the floor pygame.display.flip() # Main game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() handle_movement() update_player() draw() clock.tick(FPS)