import pygame
import random
import os  # For file handling

pygame.init()

# Window settings
width = 700
height = 600
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Car Game")  # Updated title

# Colors
ASPHALT = (50, 50, 50)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
ROAD_EDGE = (180, 180, 180)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)

# Road and lanes
road_left = 100
road_right = 600
lane_count = 5
lane_width = (road_right - road_left) // lane_count
lanes = [road_left + i * lane_width + lane_width // 2 for i in range(lane_count)]  # center x of each lane

# Car settings (hitbox dimensions)
car_width = 70  # Player car hitbox width
car_height = 140  # Player car hitbox height
car_lane = 2  # Start in the middle lane
car_x = lanes[car_lane] - car_width // 2  # Current x position
car_target_x = car_x  # Target x position for smooth movement
car_y = height - car_height - 10
car_speed = 10  # Speed of smooth movement (pixels per frame)

# Obstacle settings (hitbox dimensions)
obstacle_width = 70  # Obstacle car hitbox width
obstacle_height = 120  # Obstacle car hitbox height
obstacles = [
    {"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": None},
    {"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": None},  # Second car starts farther away
]
obstacle_speed = 5  # Initial speed
third_obstacle_added = False  # Flag for adding a third obstacle
fourth_obstacle_added = False  # Flag for adding a fourth obstacle

# Visual dimensions (for rendering only)
visual_car_width = 120  # Player car appears thicker
visual_obstacle_width = 70  # Obstacle car appears thinner

# Load car images with updated visual dimensions
player_car_img = pygame.image.load("car_player.png")  # Replace with the path to your player's car image
player_car_img = pygame.transform.scale(player_car_img, (visual_car_width, car_height))

# Load multiple obstacle images
obstacle_skins = [
    pygame.transform.scale(pygame.image.load("car_obstacle1.png"), (visual_obstacle_width, obstacle_height)),
    pygame.transform.scale(pygame.image.load("car_obstacle2.png"), (visual_obstacle_width, obstacle_height)),
    pygame.transform.scale(pygame.image.load("car_obstacle3.png"), (visual_obstacle_width, obstacle_height)),
    pygame.transform.scale(pygame.image.load("car_obstacle4.png"), (visual_obstacle_width, obstacle_height)),
]

# Assign random skins to initial obstacles
for obstacle in obstacles:
    obstacle["skin"] = random.choice(obstacle_skins)

clock = pygame.time.Clock()
font = pygame.font.Font(pygame.font.match_font('arial'), 36)  # Stylish font
title_font = pygame.font.Font(pygame.font.match_font('arial'), 72)

# Load a monospace font for odometer style speed display
odometer_font = pygame.font.SysFont('consolas', 40, bold=True)

# Game variables
run = True
menu_active = True
score = 0
line_offset = 0  # Offset for moving dashed lines

# High score handling
high_score_file = "highscore.txt"

def load_high_score():
    """Load the high score from a file."""
    if os.path.exists(high_score_file):
        with open(high_score_file, "r") as file:
            try:
                return int(file.read().strip())
            except ValueError:
                return 0
    return 0

def save_high_score(high_score):
    """Save the high score to a file."""
    with open(high_score_file, "w") as file:
        file.write(str(high_score))

# Initialize high score
high_score = load_high_score()

def draw_speedometer(speed):
    # Format speed as 3-digit zero-padded string
    speed_str = f"{speed:03d} km/h"

    # Render the text
    speed_text = odometer_font.render(speed_str, True, WHITE)

    padding_x = 15
    padding_y = 10

    box_width = speed_text.get_width() + 2 * padding_x
    box_height = speed_text.get_height() + 2 * padding_y

    x = width - box_width - 20
    y = height - box_height - 20

    # Draw background rectangle (black) with rounded corners
    pygame.draw.rect(win, BLACK, (x, y, box_width, box_height), border_radius=10)
    # Draw white border rectangle
    pygame.draw.rect(win, WHITE, (x, y, box_width, box_height), 3, border_radius=10)

    # Blit speed text inside the box
    win.blit(speed_text, (x + padding_x, y + padding_y))

def draw_highway():
    # Draw the asphalt background
    win.fill(ASPHALT)

    # Draw road edges (shoulders)
    pygame.draw.rect(win, ROAD_EDGE, (road_left - 20, 0, 20, height))  # Left shoulder
    pygame.draw.rect(win, ROAD_EDGE, (road_right, 0, 20, height))  # Right shoulder

    # Draw the road itself
    pygame.draw.rect(win, ASPHALT, (road_left, 0, road_right - road_left, height))  # Road area

    # Draw solid white lines for highway boundaries
    pygame.draw.line(win, WHITE, (road_left, 0), (road_left, height), 4)  # Left boundary
    pygame.draw.line(win, WHITE, (road_right, 0), (road_right, height), 4)  # Right boundary

    # Draw moving dashed yellow lane dividers
    global line_offset
    line_offset = (line_offset + 5) % 40  # Speed of lane line movement
    for i in range(1, lane_count):
        lane_x = road_left + i * lane_width
        for y in range(-line_offset, height, 40):
            pygame.draw.rect(win, YELLOW, (lane_x - 2, y, 4, 20))

def draw_game():
    draw_highway()
    visual_car_x = car_x - (visual_car_width - car_width) // 2  # Adjust visual car to match hitbox

    win.blit(player_car_img, (visual_car_x, car_y))  # Draw player's car

    # Draw obstacles
    for obstacle in obstacles:
        obstacle_x = lanes[obstacle["lane"]] - visual_obstacle_width // 2
        win.blit(obstacle["skin"], (obstacle_x, obstacle["y"]))

    # Display the score
    score_text = font.render(f"Score: {score}", True, WHITE)
    win.blit(score_text, (10, 10))

    # Draw odometer-style speedometer in bottom-right corner
    draw_speedometer(obstacle_speed)

def end_game_screen():
    global run, menu_active, score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added

    # Update high score if current score is higher
    if score > high_score:
        high_score = score
        save_high_score(high_score)  # Save the new high score

    while True:
        win.fill(ASPHALT)
        end_text = title_font.render("Game Over", True, RED)
        score_text = font.render(f"Your Score: {score}", True, WHITE)
        high_score_text = font.render(f"High Score: {high_score}", True, WHITE)
        play_again_text = font.render("Play Again", True, WHITE)
        quit_text = font.render("Quit", True, WHITE)

        play_again_button = pygame.Rect(width // 2 - 100, 300, 200, 50)  # Play Again button
        quit_button = pygame.Rect(width // 2 - 100, 400, 200, 50)  # Quit button

        # Draw Game Over screen
        win.blit(end_text, (width // 2 - end_text.get_width() // 2, 100))
        win.blit(score_text, (width // 2 - score_text.get_width() // 2, 200))
        win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 250))
        pygame.draw.rect(win, BLUE, play_again_button)
        pygame.draw.rect(win, BLUE, quit_button)
        win.blit(play_again_text, (play_again_button.x + play_again_button.width // 2 - play_again_text.get_width() // 2,
                                   play_again_button.y + play_again_button.height // 2 - play_again_text.get_height() // 2))
        win.blit(quit_text, (quit_button.x + quit_button.width // 2 - quit_text.get_width() // 2,
                             quit_button.y + quit_button.height // 2 - quit_text.get_height() // 2))
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if play_again_button.collidepoint(event.pos):  # Restart game
                    score = 0
                    obstacles = [
                        {"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
                        {"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
                    ]
                    third_obstacle_added = False
                    fourth_obstacle_added = False
                    return  # Exit the end game screen loop
                elif quit_button.collidepoint(event.pos):  # Quit game
                    pygame.quit()
                    exit()

def main_menu():
    global menu_active, obstacles, score, high_score, third_obstacle_added, fourth_obstacle_added

    while menu_active:
        clock.tick(60)

        # Update the background gameplay
        for obstacle in obstacles:
            obstacle["y"] += obstacle_speed
            if obstacle["y"] > height:
                obstacle["y"] = -obstacle_height
                obstacle["lane"] = random.randint(0, lane_count - 1)
                obstacle["skin"] = random.choice(obstacle_skins)  # Assign a new random skin

        # Draw the game in the background
        draw_game()

        # Draw menu overlay
        title_text = title_font.render("Car Game", True, WHITE)
        play_text = font.render("Play", True, WHITE)
        high_score_text = font.render(f"High Score: {high_score}", True, WHITE)

        play_button_rect = pygame.Rect(width // 2 - 100, 300, 200, 50)  # Play button dimensions

        # Draw title, high score, and button
        win.blit(title_text, (width // 2 - title_text.get_width() // 2, 100))
        win.blit(high_score_text, (width // 2 - high_score_text.get_width() // 2, 200))
        pygame.draw.rect(win, BLUE, play_button_rect)
        win.blit(play_text, (play_button_rect.x + play_button_rect.width // 2 - play_text.get_width() // 2,
                             play_button_rect.y + play_button_rect.height // 2 - play_text.get_height() // 2))
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if play_button_rect.collidepoint(event.pos):  # Start game
                    score = 0
                    obstacles = [
                        {"lane": random.randint(0, lane_count - 1), "y": -obstacle_height, "skin": random.choice(obstacle_skins)},
                        {"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 200, "skin": random.choice(obstacle_skins)},
                    ]
                    third_obstacle_added = False
                    fourth_obstacle_added = False
                    menu_active = False  # Exit the menu

# Main loop
main_menu()  # Display the main menu
while run:
    clock.tick(60)

    # Increase obstacle speed as score increases
    obstacle_speed = 5 + (score // 10)

    # Add a third obstacle when the score reaches 10
    if score >= 10 and not third_obstacle_added:
        obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 400, "skin": random.choice(obstacle_skins)})
        third_obstacle_added = True

    # Add a fourth obstacle when the score reaches 20
    if score >= 20 and not fourth_obstacle_added:
        obstacles.append({"lane": random.randint(0, lane_count - 1), "y": -obstacle_height - 600, "skin": random.choice(obstacle_skins)})
        fourth_obstacle_added = True

    draw_game()
    pygame.display.update()

    # Update obstacles
    for obstacle in obstacles:
        obstacle["y"] += obstacle_speed
        if obstacle["y"] > height:
            obstacle["y"] = -obstacle_height
            obstacle["lane"] = random.randint(0, lane_count - 1)
            obstacle["skin"] = random.choice(obstacle_skins)
            score += 1  # Increase score when an obstacle resets

    # Smoothly move the car towards the target x position
    if car_x < car_target_x:
        car_x += min(car_speed, car_target_x - car_x)
    elif car_x > car_target_x:
        car_x -= min(car_speed, car_x - car_target_x)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:  # Detect key press
            if event.key == pygame.K_LEFT and car_lane > 0:
                car_lane -= 1
                car_target_x = lanes[car_lane] - car_width // 2
            elif event.key == pygame.K_RIGHT and car_lane < lane_count - 1:
                car_lane += 1
                car_target_x = lanes[car_lane] - car_width // 2

    # Check for collisions
    car_rect = pygame.Rect(car_x, car_y, car_width, car_height)
    for obstacle in obstacles:
        obstacle_x = lanes[obstacle["lane"]] - obstacle_width // 2

        # Adjust obstacle hitbox to be smaller (10% of original size)
        obstacle_hitbox_width = obstacle_width * 0.1
        obstacle_hitbox_height = obstacle_height * 0.1
        obstacle_hitbox_x = obstacle_x + (obstacle_width - obstacle_hitbox_width) // 2
        obstacle_hitbox_y = obstacle["y"] + (obstacle_height - obstacle_hitbox_height) // 2

        obstacle_rect = pygame.Rect(
            obstacle_hitbox_x, obstacle_hitbox_y, obstacle_hitbox_width, obstacle_hitbox_height
        )

        if car_rect.colliderect(obstacle_rect):
            end_game_screen()  # Display end game screen once you hit 100 on the car game take them to a new stage where you have to drift the car