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 and state
score = 0
line_offset = 0  # Offset for moving dashed lines
game_stage = "menu"  # States: 'menu', 'playing', 'drift', 'game_over'

# 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 score, high_score, obstacles, third_obstacle_added, fourth_obstacle_added, game_stage

    # 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
                    reset_game_variables()
                    score = 0
                    game_stage = "playing"
                    return  # Exit the end game screen loop
                elif quit_button.collidepoint(event.pos):  # Quit game
                    pygame.quit()
                    exit()

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

    while game_stage == "menu":
        clock.tick(60)

        # Update the background gameplay of obstacles moving
        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
                    reset_game_variables()
                    score = 0
                    game_stage = "playing"
                    return

# Reset game variables helper
def reset_game_variables():
    global obstacles, third_obstacle_added, fourth_obstacle_added, obstacle_speed
    global car_lane, car_x, car_target_x, score

    obstacles.clear()
    obstacles.extend([
        {"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
    obstacle_speed = 5
    score = 0
    # Reset car position
    global car_lane, car_x, car_target_x
    car_lane = 2
    car_x = lanes[car_lane] - car_width // 2
    car_target_x = car_x

# --- Drifting Stage Variables ---
drift_position = pygame.Vector2(width // 2, height - 150)
drift_velocity = pygame.Vector2(0, 0)
drift_angle = 0  # degrees
drift_speed = 0
DRIFT_MAX_SPEED = 10
DRIFT_ACCELERATION = 0.2
DRIFT_FRICTION = 0.05
DRIFT_TURN_SPEED = 3  # degrees per frame
drift_timer = 0
DRIFT_TIME_LIMIT = 30 * 60  # 30 seconds * 60 FPS

drift_car_img = player_car_img  # Reuse player car image

def drift_stage():
    global drift_position, drift_velocity, drift_angle, drift_speed, drift_timer, game_stage, score

    clock.tick(60)
    drift_timer += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    keys = pygame.key.get_pressed()

    # Controls - simulate drift / slip
    if keys[pygame.K_LEFT]:
        drift_angle += DRIFT_TURN_SPEED  # Turning left increases angle
    if keys[pygame.K_RIGHT]:
        drift_angle -= DRIFT_TURN_SPEED  # Turning right decreases angle

    # Accelerate with Up arrow
    if keys[pygame.K_UP]:
        drift_speed += DRIFT_ACCELERATION
    else:
        drift_speed -= DRIFT_FRICTION

    # Clamp speed between 0 and max
    drift_speed = max(0, min(DRIFT_MAX_SPEED, drift_speed))

    # Calculate velocity vector based on drift angle
    rad_angle = -drift_angle * (3.14159265 / 180)  # convert degrees to radians, negative for screen coord
    drift_velocity.x = drift_speed * pygame.math.Vector2(1, 0).rotate(rad_angle).x
    drift_velocity.y = drift_speed * pygame.math.Vector2(1, 0).rotate(rad_angle).y

    # Update position
    drift_position += drift_velocity

    # Keep car inside boundaries (simple bounding box)
    drift_position.x = max(visual_car_width // 2, min(width - visual_car_width // 2, drift_position.x))
    drift_position.y = max(car_height // 2, min(height - car_height // 2, drift_position.y))

    # Draw icy road background
    win.fill((180, 220, 255))  # Light blue for icy road

    # Draw drifting car rotated by drift_angle
    rotated_car = pygame.transform.rotate(drift_car_img, drift_angle)
    rect = rotated_car.get_rect(center=drift_position)
    win.blit(rotated_car, rect.topleft)

    # Draw timer/countdown
    time_left = max(0, (DRIFT_TIME_LIMIT - drift_timer) // 60)
    timer_text = font.render(f"Time Left: {time_left}s", True, BLACK)
    win.blit(timer_text, (10, 10))

    # Display current drift speed
    speed_text = font.render(f"Speed: {int(drift_speed*10)}", True, BLACK)
    win.blit(speed_text, (10, 50))

    pygame.display.update()

    # When time runs out, return to menu
    if drift_timer >= DRIFT_TIME_LIMIT:
        drift_timer = 0
        reset_game_variables()
        game_stage = "menu"

# --- Main Playing Loop ---
def play_stage():
    global score, obstacle_speed, third_obstacle_added, fourth_obstacle_added
    global car_x, car_target_x, car_lane, game_stage

    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:
            pygame.quit()
            exit()
        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):
            game_stage = "game_over"
            return

    # If score reaches 100, switch to drifting stage
    if score >= 100:
        # Reset drift variables
        global drift_timer, drift_position, drift_angle, drift_speed, drift_velocity
        drift_timer = 0
        drift_position.update(width // 2, height - 150)
        drift_angle = 0
        drift_speed = 0
        drift_velocity.update(0, 0)
        game_stage = "drift"

def main():
    global game_stage
    reset_game_variables()
    while True:
        if game_stage == "menu":
            main_menu()
        elif game_stage == "playing":
            play_stage()
        elif game_stage == "drift":
            drift_stage()
        elif game_stage == "game_over":
            end_game_screen()

if __name__ == "__main__":
    main() make it so once you hit a 100 score give them a choice to continue playing the first stage