import pygame
import sys
import random

# Initialize pygame
pygame.init()

# Set up the screen
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Endless Runner")

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

# Set up the clock
clock = pygame.time.Clock()

# Load the player image
player_color = RED
player_size = 50
player_rect = pygame.Rect(WIDTH // 2 - player_size // 2, HEIGHT - 70 - player_size, player_size, player_size)
player_speed = 5
jump_height = -10
gravity = 0.5
is_jumping = False

# Set up game variables
platform_width = 100
platform_gap = 200
platform_speed = 5
platforms = []
score = 0
high_score = 0

# Load font for displaying text
font = pygame.font.Font(None, 36)

# Function to generate new platforms
def generate_platform():
    platform_y = random.randint(HEIGHT // 2, HEIGHT - 100)
    platform = pygame.Rect(WIDTH, platform_y, platform_width, 20)
    return platform

# Main game loop
running = True
while running:
    screen.fill(WHITE)

    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Check for jump input
    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] and not is_jumping:
        is_jumping = True
        jump_height = -10

    # Move player
    if is_jumping:
        player_rect.y += jump_height
        jump_height += gravity
        if player_rect.bottom >= HEIGHT:
            player_rect.bottom = HEIGHT
            is_jumping = False

    # Generate platforms
    if len(platforms) == 0 or platforms[-1].x < WIDTH - WIDTH // 3:
        platforms.append(generate_platform())

    # Move platforms
    for i, platform in enumerate(platforms):
        platform.x -= platform_speed
        if platform.x + platform_width < 0:
            platforms.pop(i)
            score += 1
            if score > high_score:
                high_score = score
                
# Check for collision with platforms
on_platform = False
for platform in platforms:
    if player_rect.colliderect(platform) and jump_height >= 0:
        on_platform = True
        player_rect.bottom = platform.top
        jump_height = -10
        is_jumping = False  # Set is_jumping to False only when on a platform
    elif player_rect.bottom >= HEIGHT:
        running = False


    # Draw player and platforms
    pygame.draw.rect(screen, player_color, player_rect)
    for platform in platforms:
        pygame.draw.rect(screen, BLACK, platform)

    # Display score
    score_text = font.render("Score: " + str(score), True, BLACK)
    high_score_text = font.render("High Score: " + str(high_score), True, BLACK)
    screen.blit(score_text, (20, 20))
    screen.blit(high_score_text, (20, 60))

    # Update the display
    pygame.display.flip()

    # Cap the frame rate
    clock.tick(60)

# Quit pygame
pygame.quit()
sys.exit()