0. Overview¶

  1. Introduction
  2. Helper Functions & Custom Training Environment
  3. PPO Networks & Agent
  4. Reward Structure
  5. Training Loop & Curiculum Learning
  6. Possible Improvements & Future Work
  • Word of Advise: If you want to use the code you are better of using the files in training under this space since the setup doesent work in the notebook.
  • The notebook is just to give an overview of the code - it will only partly runn everything.

1. Introduction¶

  • Since the release of the "Absolute Zero" Paper earlier in 2025 and the realease of "Deepseek" in 2023 reinforcement learning became more inportant than ever.
  • This project serves as my first introducction to reinforcment learing with realtime environment feedback.
  • So the question was which project to choose:
    • It shouldent be to difficult but also not to easy (flappy-bird)
    • I deceided to work on a steering project for cars.
  • Goal: Create a project that trains an AI agent on many different randomly generated tracks how to do acceleration, deceleration and steering.
  • Hopefully the large amount of procedural roads forces the agent to generalize and is able to fully replace a dataset like mentioned in the "Absolute Zero" Paper.
    • Link to the paper mentioned: https://arxiv.org/abs/2505.03335
  • The original code is split into the following files:
    • train_reward_steering.py - contains the training loop and the environment
    • ppo_agent.py - contains the ppo networks, and the agent class
    • car_game_classes.py - contains many helper functions used by the environment in train_reward_steering.py
    • These files can be downloaded in this space under files/training/

2.1 Helper Functions¶

MapGenerator¶
  • The MapGenerator is the part of the code that generates the steets. And also places the car on the street.
  • How does it work?
    1. First it creates creates control points.
    2. Then it interpolates these control points using Catmull–Rom splines for smoothness.
    3. Generates goal lines at intervals, these goals will give the agent a reward for passing it.
    4. For performance the map is cashed. Since there is no need to regenerate it every step of the simulation. It should only regenerate when certain conditions are met. Later more on that.
  • I want to train the agent using the corriculum learning.
  • I will do this by
MapGenerator.update()¶
  1. Clears the canvas to white.
  2. Chooses a difficulty level based on the user input.
  3. Level 1:
    • The roads generated have soft wide curves or are straight.
    • This level is primary used to teach the car acceleration and deceleration and slight steering.
    • Accelerationg and deceleration must be trained first since the car must have velocity befor it can learn poper steering.
  4. Level 2:
    • This level generates circular roads that are displaced using a noise.
    • Its main use is to teach the car consistent/prolonged steering since its driving in a circle.
    • Prolonged steering is neccesary to be able to steer very tight corners that will come up in level 3
  5. Level 3:
    • The generated roads are alternating high/low to create sharper corners/ turns.
    • This generates a wavy looking curve.
  • Overview alt text
  1. Computes detailed curve points via Catmull–Rom.
  2. Builds & draws goals as blue line segments perpendicular to the track.
  3. Draws road segments and endpoint caps on the surface.
  4. Positions and rotates the car to match the generated road.
In [ ]:
import pygame
import math
import numpy as np

class MapGenerator:
    def __init__(self, width, height, difficulty, goals):
        self.surface = pygame.Surface((width, height))
        self.width = width
        self.height = height
        self.difficulty = difficulty
        self.goals = []
        self.num_goals = goals if isinstance(goals, int) else len(goals) if goals else 12
        self.curve_pts = []  # Added to store curve points

    def update(self):
        self.surface.fill((255, 255, 255))

        if self.difficulty == 1:
            border = 50
            num_ctrl = 4
            x_coords = [i * (self.width/(num_ctrl-1)) for i in range(num_ctrl)]
            x_coords[0], x_coords[-1] = border*2, self.width-border*2
            y_coords = np.random.randint(border*4, self.height-border*4, num_ctrl)
            ctrl_pts = list(zip(x_coords, y_coords))
            curve_pts = self.compute_catmull_rom(ctrl_pts, 800)
            road_width = 100
        
        if self.difficulty == 2:
            # Define constants
            border = 150
            cx = self.width / 2
            cy = self.height / 2

            r = min(self.width / 2 - border, self.height / 2 - border)
            a = r
            b = r

            # Generate control points for open loop (exclude last few points to create gap)
            N = 25
            gap_points = 3  # Remove last 3 control points to create visible gap
            angles = [2 * np.pi * i / N for i in range(N - gap_points)]
            control_pts = []

            # Perlin-like noise parameters for soft, organic wobble
            octaves = 1
            frequencies = [2.5] # Multiple octaves for perlin-like effect
            amplitudes = [16]  # Decreasing amplitudes for each octave
            
            # Random phases for each octave
            phi_x = [[np.random.uniform(0, 2 * np.pi) for _ in range(octaves)]]
            phi_y = [[np.random.uniform(0, 2 * np.pi) for _ in range(octaves)]]

            # Generate noisy control points with perlin-like noise
            for i, angle in enumerate(angles):
                x = cx + a * np.cos(angle)
                y = cy + b * np.sin(angle)
                
                # Apply multi-octave noise (perlin-like)
                dx = 0
                dy = 0
                for j in range(octaves):
                    # Use both angle and position index for variation
                    noise_input = frequencies[j] * angle + phi_x[0][j]
                    dx += amplitudes[j] * np.sin(noise_input)
                    
                    noise_input_y = frequencies[j] * angle + phi_y[0][j]
                    dy += amplitudes[j] * np.cos(noise_input_y)  # Use cos for y to decorrelate
                
                x += dx
                y += dy
                control_pts.append((x, y))

            # Randomly invert the list of control points
            if np.random.rand() < 0.5:
                control_pts = control_pts[::-1]

            # Compute the curve points with an open loop
            curve_pts = self.compute_catmull_rom(control_pts, 800)
            
            # Remove additional points at the end to ensure visible gap
            if len(curve_pts) > 100:
                curve_pts = curve_pts[:-50]  # Remove last 50 curve points for clear gap
            road_width = 100
            
        if self.difficulty == 3:
            border = 50
            num_ctrl = 5
            x_coords = [i * (self.width/(num_ctrl-1)) for i in range(num_ctrl)]
            x_coords[0], x_coords[-1] = border*2, self.width-border*2
            
            # Generate y coordinates with alternating high/low pattern
            y_coords = []
            
            # Define high and low ranges
            high_range = (self.height//2 + 2*border, self.height - int(border*5.5))
            low_range = (int(border*5.5), self.height//2 - 2*border)
            
            # Generate first point randomly
            first_y = np.random.randint(int(border*5.5), self.height-int(border*5.5))
            y_coords.append(first_y)
            
            # Determine if first point is high or low
            is_first_high = first_y > self.height // 2
            
            # Generate remaining points alternating between high and low
            for i in range(1, num_ctrl):
                if is_first_high:
                    # If previous point was high, make this one low
                    if (i - 1) % 2 == 0:  # Previous was high (first point)
                        y = np.random.randint(low_range[0], low_range[1])
                    else:  # Previous was low
                        y = np.random.randint(high_range[0], high_range[1])
                else:
                    # If previous point was low, make this one high
                    if (i - 1) % 2 == 0:  # Previous was low (first point)
                        y = np.random.randint(high_range[0], high_range[1])
                    else:  # Previous was high
                        y = np.random.randint(low_range[0], low_range[1])
                
                y_coords.append(y)
                
            ctrl_pts = list(zip(x_coords, y_coords))
            
            # 50% chance to flip the control points order
            if np.random.rand() < 0.5:
                ctrl_pts = ctrl_pts[::-1]
            
            curve_pts = self.compute_catmull_rom(ctrl_pts, 800)
            road_width = 100

        self.curve_pts = curve_pts  # Store curve points

        # Create goals     
        goals_pts = self.create_goals(curve_pts)
        self.goals = goals_pts  

        # Draw roads as connected segments
        self.draw_road_segments(curve_pts, road_width)

        # Draw goals
        for goal_index in goals_pts: 
            pygame.draw.line(self.surface, (0,0,255), goal_index[0], goal_index[1], width=2)   

        # Get car start
        if len(curve_pts) >= 2:
            start_pos = curve_pts[0]
            xs, ys = start_pos
            xe, ye = curve_pts[1]
            x = xe - xs
            y = ye - ys
            start_dir = (x, y)
        else:
            start_pos = (100, self.height//2)
            start_dir = (1, 0)
            
        return pygame.math.Vector2(start_pos), pygame.math.Vector2(start_dir)

    def draw_road_segments(self, points, road_width):
        if len(points) < 2:
            return
        for i in range(len(points) - 1):
            start_pos = (int(points[i][0]), int(points[i][1]))
            end_pos = (int(points[i+1][0]), int(points[i+1][1]))
            pygame.draw.line(self.surface, (0, 0, 0), start_pos, end_pos, width=road_width)
        cap_radius = road_width // 2
        for point in points:
            pygame.draw.circle(self.surface, (0, 0, 0), (int(point[0]), int(point[1])), cap_radius)

    def compute_catmull_rom(self, control_points, steps_per_segment=20):
        try:
            is_loop = control_points[0] == control_points[-1]
            if hasattr(is_loop, '__len__') and len(is_loop) > 1:
                is_loop = np.allclose(control_points[0], control_points[-1])
        except:
            first = np.array(control_points[0])
            last = np.array(control_points[-1])
            is_loop = np.allclose(first, last)
        
        pts = control_points[:-1] if is_loop else control_points
        n = len(pts)
        points = []

        def get(idx):
            if is_loop:
                return pts[idx % n]
            else:
                return pts[min(max(idx, 0), n - 1)]

        for i in range(n if is_loop else n - 1):
            p0 = get(i - 1)
            p1 = get(i)
            p2 = get(i + 1)
            p3 = get(i + 2)
            for j in range(steps_per_segment):
                t = j / steps_per_segment
                t2 = t * t
                t3 = t2 * t
                f1 = -0.5 * t3 + t2 - 0.5 * t
                f2 = 1.5 * t3 - 2.5 * t2 + 1.0
                f3 = -1.5 * t3 + 2.0 * t2 + 0.5 * t
                f4 = 0.5 * t3 - 0.5 * t2
                x = f1 * p0[0] + f2 * p1[0] + f3 * p2[0] + f4 * p3[0]
                y = f1 * p0[1] + f2 * p1[1] + f3 * p2[1] + f4 * p3[1]
                points.append((x, y))
        if not is_loop:
            points.append(tuple(pts[-1]))
        return points
    
    def resample_by_distance(self, points, desired_spacing):
        if len(points) < 2:
            return points
        dists = [0.0]
        for i in range(1, len(points)):
            prev, curr = np.array(points[i-1]), np.array(points[i])
            dist = float(np.linalg.norm(curr - prev))
            dists.append(dists[-1] + dist)
        total_len = dists[-1]
        if total_len == 0:
            return points
        n_points = int(total_len // desired_spacing)
        new_pts = []
        for k in range(n_points+1):
            target = k * desired_spacing
            for j in range(1, len(dists)):
                if dists[j] >= target:
                    ratio = (target - dists[j-1])/(dists[j] - dists[j-1])
                    A, B = np.array(points[j-1]), np.array(points[j])
                    P = A + ratio*(B - A)
                    new_pts.append(tuple(P))
                    break
        return new_pts if new_pts else points

    def create_goals(self, pts, goal_number=None):
        n_pts = len(pts)
        if goal_number is not None:
            num_goals = goal_number
        else:
            num_goals = self.num_goals
        if n_pts == 0 or num_goals == 0:
            return []
        actual_goals = min(num_goals, n_pts // 10)
        if actual_goals == 0:
            actual_goals = 1
        lines = []
        last_dir = None
        for k in range(actual_goals):
            if actual_goals == 1:
                idx = n_pts // 2
            else:
                idx = int((k * (n_pts - 1)) / (actual_goals - 1))
            idx = max(0, min(idx, n_pts - 1))
            idx2 = idx
            look_ahead = 5
            if idx + look_ahead < n_pts:
                idx2 = idx + look_ahead
            elif idx >= look_ahead:
                idx2 = idx - look_ahead
            elif idx + 1 < n_pts:
                idx2 = idx + 1
            elif idx > 0:
                idx2 = idx - 1
            x, y = pts[idx]
            if idx2 != idx:
                x1, y1 = pts[idx2]
                dir_vec = pygame.math.Vector2(x1 - x, y1 - y)
                if idx2 < idx:
                    dir_vec *= -1
            else:
                dir_vec = last_dir if last_dir else pygame.math.Vector2(0, -1)
            if dir_vec.length_squared() < 1e-8:
                dir_vec = pygame.math.Vector2(0, -1)
            else:
                dir_vec = dir_vec.normalize()
                if last_dir and dir_vec.dot(last_dir) < -0.5:
                    dir_vec *= -1
            last_dir = dir_vec
            normal = dir_vec.rotate(90)
            p0 = pygame.math.Vector2(x, y) + normal * 50
            p1 = pygame.math.Vector2(x, y) - normal * 50
            lines.append((p0, p1))
        return lines

    def draw(self, surface):
        surface.blit(self.surface, (0,0))
Car Class¶
  • Tracks position, velocity, angle.
  • Applies acceleration, steering and brake.
  • Uses simple physics for speed updates.
  • Rotates the car sprite to match heading of the direction vector.
In [ ]:
class Car:
    def __init__(self, image, pos, max_velocity=275, turn_speed=77.5):
        self.original_image = image.convert_alpha()
        self.image = self.original_image
        self.pos = pygame.math.Vector2(pos)
        self.velocity = 0.0
        self.max_velocity = max_velocity
        self.direction = pygame.math.Vector2(1, 0)
        self.turn_speed = turn_speed
        self.angle = 0.0
        self.is_braking = False
        self.acceleration = 55.0
        self.deceleration = 16.0
        self.brake_deceleration = 55.0
        self.min_velocity_threshold = 5.0

    def update(self, dt, keys=None, steer_factor=1.0):
        if keys is None:
            pressed = pygame.key.get_pressed()
            keys = {
                'w': pressed[pygame.K_w],
                'a': pressed[pygame.K_a],
                's': pressed[pygame.K_s],
                'd': pressed[pygame.K_d]
            }
        self.is_braking = False
        if keys.get('w', False):
            acceleration_multiplier = 1.0
            if self.velocity > 50:
                acceleration_multiplier = 1.2
            elif self.velocity < 20:
                acceleration_multiplier = 1.5
            if self.velocity < self.max_velocity:
                self.velocity += self.acceleration * acceleration_multiplier * dt
                if self.velocity > self.max_velocity:
                    self.velocity = self.max_velocity
        if keys.get('s', False):
            self.is_braking = True
            if self.velocity > 0:
                brake_multiplier = 1.0 + (self.velocity / self.max_velocity) * 0.5
                self.velocity -= self.brake_deceleration * brake_multiplier * dt
                if self.velocity < 0:
                    self.velocity = 0
        else:
            if not keys.get('w', False) and self.velocity > 0:
                decel_rate = self.deceleration
                if self.velocity > 100:
                    decel_rate *= 0.7
                self.velocity -= decel_rate * dt
                if self.velocity < self.min_velocity_threshold:
                    self.velocity = max(0, self.velocity - 2.0 * dt)
        if self.velocity > 0:
            self.pos += self.direction.normalize() * self.velocity * dt
        if self.velocity > 10:
            angular_velocity = 0
            speed_factor = min(1.0, self.velocity / 200.0)
            effective_turn_speed = self.turn_speed * (0.5 + 0.5 * speed_factor)
            if keys.get('a', False):
                angular_velocity = -effective_turn_speed * steer_factor
            elif keys.get('d', False):
                angular_velocity = effective_turn_speed * steer_factor
            if angular_velocity != 0:
                angle_change = angular_velocity * dt
                target_direction = self.direction.rotate(angle_change)
                base_drift = 0.15
                velocity_factor = min(1.0, self.velocity / self.max_velocity)
                drift_factor = base_drift * (0.5 + 0.5 * velocity_factor)
                self.direction = (self.direction * drift_factor + 
                                target_direction * (1 - drift_factor)).normalize()
                self.angle = -math.degrees(math.atan2(self.direction.y, self.direction.x))
        self.image = pygame.transform.rotate(self.original_image, self.angle)

    def draw(self, surface):
        rect = self.image.get_rect(center=self.pos)
        surface.blit(self.image, rect.topleft)
    
    def reset(self, pos, direction):
        self.pos = pygame.math.Vector2(pos)
        self.direction = pygame.math.Vector2(direction).normalize()
        self.velocity = 0.0
        self.angle = -math.degrees(math.atan2(self.direction.y, self.direction.x))
RayCasting¶
  • Casts N rays from car front.
  • Detects distance to track edges.
  • 2-phase raycasting for performance: coarse & fine steps.
    • first the ray goes N steps using the coarse step distance until a collision is found
    • Then it goes pixel by pixel (fine step) from the previous coarse step to find the actual distance.
    • The class provides distances and hit points.
  • Visualisation alt text
In [ ]:
class RayCasting:
    def __init__(self, car_pos, car_dir, track_surf,
                 ray_angles, ray_offsets, max_distance=1600, step_pixels=1, draw_rays=True):
        self.car_pos = pygame.math.Vector2(car_pos)
        self.car_dir = pygame.math.Vector2(car_dir).normalize()
        self.track_surf = track_surf
        self.ray_angles = list(ray_angles)
        self.ray_offsets = list(ray_offsets)
        self.max_distance = max_distance
        self.step_pixels = step_pixels
        self.last_collisions = [self.car_pos.copy()] * len(self.ray_angles)
        self.ray_distances = [0.0] * len(self.ray_angles)
        self.draw_rays = draw_rays
        
        # NEW: Performance optimization variables
        self.coarse_step = 15  # Check every x pixels first
        self.fine_step = 1    # Then refine with 1 pixel precision

    def cast_ray(self, start_pos, direction):
        """Optimized ray casting with coarse-to-fine approach"""
        pos = pygame.math.Vector2(start_pos)
        dir_norm = pygame.math.Vector2(direction).normalize()
        
        # Calculate step size based on direction
        inv = max(abs(dir_norm.x), abs(dir_norm.y))
        base_step_size = (1.0 / inv) if inv != 0 else 1.0
        
        # Phase 1: Coarse search with 5x step size
        coarse_step_size = base_step_size * self.coarse_step
        traveled = 0.0
        w, h = self.track_surf.get_size()
        last_safe_pos = pos.copy()
        last_safe_distance = 0.0
        
        while traveled < self.max_distance:
            ix, iy = int(pos.x), int(pos.y)
            if 0 <= ix < w and 0 <= iy < h:
                color = self.track_surf.get_at((ix, iy))
                if color[:3] == (255, 255, 255):
                    # Collision found, break for fine search
                    break
            # Store last safe position
            last_safe_pos = pos.copy()
            last_safe_distance = traveled
            
            pos += dir_norm * coarse_step_size
            traveled += coarse_step_size
        
        # Phase 2: Fine search from last safe position
        if traveled < self.max_distance:
            # Reset to last safe position and do fine search
            pos = last_safe_pos.copy()
            traveled = last_safe_distance
            fine_step_size = base_step_size * self.fine_step
            
            while traveled < self.max_distance:
                ix, iy = int(pos.x), int(pos.y)
                if 0 <= ix < w and 0 <= iy < h:
                    color = self.track_surf.get_at((ix, iy))
                    if color[:3] == (255, 255, 255):
                        return pos, traveled
                pos += dir_norm * fine_step_size
                traveled += fine_step_size
        
        return pos, traveled
    
    def draw_ray(self, start, end, color=(255, 255, 0)):
        pygame.draw.line(self.track_surf, color,
                         (int(start.x), int(start.y)),
                         (int(end.x), int(end.y)),
                         width=2)

    def update(self, car_pos, car_dir):
        """Updated to use optimized ray casting"""
        self.car_pos = pygame.math.Vector2(car_pos)
        self.car_dir = pygame.math.Vector2(car_dir).normalize()
        self.last_collisions = []
        self.ray_distances = []
        any_origin_in_white = False
        
        for angle, offset in zip(self.ray_angles, self.ray_offsets):
            ray_dir = self.car_dir.rotate(angle).normalize()
            origin = self.car_pos + ray_dir * offset
            ix, iy = int(origin.x), int(origin.y)
            w, h = self.track_surf.get_size()
            
            if 0 <= ix < w and 0 <= iy < h:
                if self.track_surf.get_at((ix, iy))[:3] == (255, 255, 255):
                    any_origin_in_white = True
                    self.last_collisions.append(origin)
                    self.ray_distances.append(0.0)
                    continue
            
            # Use optimized ray casting
            hit_pt, distance = self.cast_ray(origin, ray_dir)
            self.last_collisions.append(hit_pt)
            self.ray_distances.append(distance)
            
            if self.draw_rays:
                self.draw_ray(origin, hit_pt)
        
        return not any_origin_in_white

    def get_ray_distances(self):
        return self.ray_distances.copy()
    
    def has_zero_length_ray(self):
        return any(distance <= 0.0 for distance in self.ray_distances)

2.2 Training Environment¶

Global Constants & Setup¶
  • Imports core libraries: numpy, torch, pygame.
  • Since the agent is given the ray distances and the position in the map its important to set these values as constants
    • MAX_STEPS - this regulates how long the agent is driving on the same map befor another one is generated
    • DIFF_LVL - which difficulty the generated map should have
    • BATCH_SIZE - how much experience the agent needs to accumulate befor the ppo networks are update
    • SIMULATION_FPS - how many actions the agent performs per second
    • RENDER_FPS - how many frames are rendered per second (is lower to save performance)
    • ACTION_SPACE - the amount of actions (like breaking, accelerating, steering left or right) the agent can perform
    • LOADED_MODEL - this loads a model for corriculum learning, when no model is present it will default to learning from scratch
In [ ]:
import numpy as np
import torch
import math
from collections import deque
import time
import pygame
import asyncio
from ppo_agent import PPOAgent
from car_game_classes import Car, RayCasting, MapGenerator

pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 1600, 900
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()

MAX_STEPS = 4096 * 2
DIFF_LVL = 3
BATCH_SIZE = 1024 *2
SIMULATION_FPS = 120
RENDER_FPS = 30
ACTION_SPACE = 8
LOADED_MODEL = "modelBackups/18.6_car_model_epoch_270_lvl3_final.pth" #lvl 1 550 epochs -> #lvl 2 circle 350 epochs -> lvl3 epoch 300 -> lvl3 270
TrainingEnvironment¶
  • Initializes MapGenerator with difficulty level and goal count.
  • Loads and scales car sprite.
  • Prepares deques for speed and steering histories.
  • Calls reset() to start fresh.
  • generate_new_map()
    • Calls map_generator.update().
    • Stores returned start_pos and start_dir.
  • reset_car()
    • Requires map to be generated.
    • Creates Car instance at start_pos and sets direction.
    • Initializes RayCasting with ray angles and lengths.
    • Resets goal index, histories, and last action.
  • reset()
    • Wrapper that regenerates map and car state.
  • detect_steering_need(ray_distances)
    • Normalizes distances by max range.
    • Averages left, center, and right rays.
    • Checks three conditions in order:
      • Too close to side walls.
      • Significant imbalance between left/right.
      • Front obstacle proximity.
      • Sets: needed (bool), direction (-1 left, +1 right), urgency (0–1), space_diff, left_space, right_space, center_distance.
  • get_state()
    • Updates rays and gets raw distances.
    • Builds state vector:
    • Car features: normalized speed, direction vector, braking flag.
    • Ray distances (normalized).
    • Steering info from detect_steering_need().
    • Goal progress ratio.
    • Previous action (to see if car is continiusly steering in the right direction).
    • Speed change and its moving average.
  • execute_action_dispatch(action, dt)
    • Maps discrete action to key presses (w, a, d, s) since the pygame class is expecting strings as key inputs.
    • Defines eight possible maneuvers: Accelerate, steer, brake, combinations.
    • Adjusts steer_factor for combined controls.
    • Temporarily modifies brake deceleration for light braking.
    • Calls car.update(dt, keys, steer_factor).a
  • calculate_reward()
    • i will talk in more detail about this later
In [ ]:
def point_to_line_distance(point, line_p0, line_p1):
    p = pygame.math.Vector2(point)
    a = pygame.math.Vector2(line_p0)
    b = pygame.math.Vector2(line_p1)
    ap = p - a
    ab = b - a
    magnitude_ab = ab.length_squared()
    if magnitude_ab == 0:
        return ap.length()
    projection = ap.dot(ab) / magnitude_ab
    projection = max(0, min(1, projection))
    closest = a + projection * ab
    return p.distance_to(closest)

class TrainingEnvironment:
    def __init__(self):
        self.action_space = ACTION_SPACE
        self.map_generator = MapGenerator(SCREEN_WIDTH, SCREEN_HEIGHT, DIFF_LVL, 18)
        car_surf = pygame.image.load("assets/car_transparent.png").convert_alpha()
        w, h = car_surf.get_size()
        self.car_image = pygame.transform.scale(car_surf, (w//18, h//18))
        self.start_pos = None
        self.start_dir = None
        self.previous_speed = 0.0
        self.speed_history = deque(maxlen=5)
        # Add steering tracking
        self.steering_history = deque(maxlen=10)
        self.last_steering_reward = 0.0
        self.reset()

    def generate_new_map(self):
        start_pos, start_dir = self.map_generator.update()
        self.start_pos = pygame.math.Vector2(start_pos)
        self.start_dir = pygame.math.Vector2(start_dir).normalize()

    def reset_car(self):
        if self.start_pos is None or self.start_dir is None:
            raise ValueError("Map not generated yet")
        self.car = Car(self.car_image, self.start_pos)
        self.car.direction = self.start_dir
        self.rays = RayCasting(
            self.car.pos, self.car.direction, self.map_generator.surface,
            [-60, -30, -15, 0, 15, 30, 60],
            [14, 22, 27, 26, 27, 22, 14],
            draw_rays=False)
        self.current_goal_index = 0
        self.passed_goals = []
        self.prev_pos = self.car.pos.copy()
        self.last_action = 0
        self.previous_speed = 0.0
        self.speed_history.clear()
        self.steering_history.clear()
        self.last_steering_reward = 0.0

    def reset(self):
        self.generate_new_map()
        self.reset_car()

    def detect_steering_need(self, ray_distances):
        """Detect when steering is actually needed"""
        norm_distances = [min(d / self.rays.max_distance, 1.0) for d in ray_distances]
        
        # Check road boundaries
        left_rays = norm_distances[0:3]   # -60, -30, -15
        center_ray = norm_distances[3]    # 0
        right_rays = norm_distances[4:7]  # 15, 30, 60
        
        left_avg = sum(left_rays) / len(left_rays)
        right_avg = sum(right_rays) / len(right_rays)
        
        # Determine if steering is needed and in which direction
        space_difference = right_avg - left_avg
        
        steering_needed = False
        preferred_direction = 0
        urgency = 0.0
        
        # Check if we're getting close to walls
        min_side_distance = min(min(left_rays), min(right_rays))
        if min_side_distance < 0.3:
            steering_needed = True
            urgency = 1.0 - min_side_distance
            preferred_direction = 1 if left_avg < right_avg else -1
        
        # Check for curves ahead
        elif abs(space_difference) > 0.15:
            steering_needed = True
            urgency = min(abs(space_difference), 1.0)
            preferred_direction = 1 if space_difference > 0 else -1
            
        # Check front distance
        elif center_ray < 0.4:
            steering_needed = True
            urgency = 1.0 - center_ray
            # Steer towards the side with more space
            preferred_direction = 1 if left_avg < right_avg else -1
        
        return {
            'needed': steering_needed,
            'direction': preferred_direction,  # -1 = left, 1 = right
            'urgency': urgency,
            'space_diff': space_difference,
            'left_space': left_avg,
            'right_space': right_avg,
            'center_distance': center_ray
        }

    def get_state(self):
        self.rays.update(self.car.pos, self.car.direction)
        ray_distances = self.rays.get_ray_distances()
        normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
        
        # Detect steering need
        steering_info = self.detect_steering_need(ray_distances)
        
        state = [
            # Car state
            self.car.velocity / self.car.max_velocity,
            self.car.direction.x,
            self.car.direction.y,
            int(self.car.is_braking),
        ]
        
        # Ray distances
        state.extend(normalized_ray_distances)
        
        # Steering information - this is key for learning
        state.extend([
            float(steering_info['needed']),
            steering_info['direction'],
            steering_info['urgency'],
            steering_info['space_diff'],
            steering_info['left_space'],
            steering_info['right_space'],
            steering_info['center_distance']
        ])
        
        # Goal progress
        total_goals = len(self.map_generator.goals)
        progress = self.current_goal_index / max(total_goals, 1)
        state.append(progress)
        
        # Previous action
        state.append(self.last_action / 4.0)
        
        # Speed change
        speed_change = self.car.velocity - self.previous_speed
        self.speed_history.append(speed_change)
        avg_speed_change = sum(self.speed_history) / max(len(self.speed_history), 1)
        state.extend([speed_change / 100.0, avg_speed_change / 100.0])
        
        self.previous_speed = self.car.velocity
        
        return np.array(state, dtype=np.float32)

    def execute_action_dispatch(self, action, dt):
        """Extended action space with better braking and steering control"""
        action_int = int(action) if hasattr(action, '__int__') else action
        self.last_action = action_int
        
        keys = {'w': False, 'a': False, 'd': False, 's': False}
        steer_factor = 1.0
        
        if action_int == 0:  # Accelerate only
            keys['w'] = True
            
        elif action_int == 1:  # Steer left (no acceleration)
            keys['a'] = True
            steer_factor = 1.0
            
        elif action_int == 2:  # Steer right (no acceleration)
            keys['d'] = True
            steer_factor = 1.0
            
        elif action_int == 3:  # Accelerate + steer left
            keys['w'] = True
            keys['a'] = True
            steer_factor = 0.8  # Increased from 0.7 for better control
            
        elif action_int == 4:  # Accelerate + steer right
            keys['w'] = True
            keys['d'] = True
            steer_factor = 0.8  # Increased from 0.7
            
        elif action_int == 5:  # Light brake
            keys['s'] = True
            # Simulate light braking by reducing brake effectiveness
            original_brake = self.car.brake_deceleration
            self.car.brake_deceleration *= 0.6
            self.car.update(dt, keys, steer_factor)
            self.car.brake_deceleration = original_brake
            return  # Skip normal update
            
        elif action_int == 6:  # Heavy brake + steer left
            keys['s'] = True
            keys['a'] = True
            steer_factor = 1.2  # Enhanced steering while braking
            
        elif action_int == 7:  # Heavy brake + steer right
            keys['s'] = True
            keys['d'] = True
            steer_factor = 1.2  # Enhanced steering while braking
        
        self.car.update(dt, keys, steer_factor)

    def calculate_reward(self):
        self.rays.update(self.car.pos, self.car.direction)
        ray_distances = self.rays.get_ray_distances()
        collision = self.rays.has_zero_length_ray()
        
        if collision:
            return -100.0, collision, False       
        
        steering_info = self.detect_steering_need(ray_distances)
        reward = 0.0
        curve_severity = self.detect_curve_severity(ray_distances, steering_info)

        center_distance = ray_distances[3] / self.rays.max_distance
        if center_distance > 0.25:
            #print("accelerate now!")
            reward += 0.25 * self.car.velocity - 6

        # PROBLEM 1 FIX: Better curve speed management with anticipation

        if curve_severity > 0.1:  # Lowered threshold for earlier detection
            # Define speed categories with overlapping ranges for smoother learning
            if curve_severity > 0.5:  # Very tight curve
                # Reward any reasonable slowing down
                if 0.125 < self.car.velocity < 0.25:  # Very slow - excellent
                    reward += self.car.velocity /10
                else:  # Too fast - penalty
                    reward += -2
                    
            elif curve_severity > 0.25:  # Moderate curve
                # Reward any reasonable slowing down
                if 0.15 < self.car.velocity < 0.35:  # Very slow - excellent
                    reward += self.car.velocity /12
                else:  # Too fast - penalty
                    reward += -2
                    
            else:  # Slight curve (0.08-0.25)
                # Reward any reasonable slowing down
                if 0.35 < self.car.velocity < 0.7:  # Very slow - excellent
                    reward += self.car.velocity /10
                else:  # Too fast - penalty
                    reward += -2

        else:
            if self.car.velocity > 40:  # Moderate speed - still learning
                reward += self.car.velocity / 20
            elif self.car.velocity < 25:
                reward += -0.5

            # Reset speed consistency tracker on straights
            if hasattr(self, 'speed_consistency_tracker'):
                self.speed_consistency_tracker = {'appropriate': False, 'count': 0}
        
        # STEERING REWARDS WITH PERSISTANCE
        if steering_info['needed']:
            steering_urgency = steering_info['urgency']
            base_steering_reward = 5.0 + (steering_urgency * 4.0)  # 3-7 points
            
            # Track steering persistence
            if not hasattr(self, 'steering_persistence'):
                self.steering_persistence = {'direction': 0, 'count': 0}
                
            correct_action = False
            if steering_info['direction'] == -1:  # Need left
                if self.last_action in [1, 3, 6]:  # Left steering actions
                    correct_action = True
                    # Persistence bonus - reward continued steering
                    if self.steering_persistence['direction'] == -1:
                        self.steering_persistence['count'] += 2
                        persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
                        base_steering_reward += persistence_bonus
                    else:
                        self.steering_persistence = {'direction': -1, 'count': 1}
                    
                    # Extra bonus for combined brake+steer in tight curves - ONLY for correct direction
                    if curve_severity > 0.4 and self.last_action == 6:  # Heavy brake + left steer
                        base_steering_reward += 5.0
                        
            elif steering_info['direction'] == 1:  # Need right
                if self.last_action in [2, 4, 7]:  # Right steering actions
                    correct_action = True
                    # Persistence bonus
                    if self.steering_persistence['direction'] == 1:
                        self.steering_persistence['count'] += 2
                        persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
                        base_steering_reward += persistence_bonus
                    else:
                        self.steering_persistence = {'direction': 1, 'count': 1}
                    
                    # Extra bonus for combined brake+steer in tight curves - ONLY for correct direction
                    if curve_severity > 0.4 and self.last_action == 7:  # Heavy brake + right steer
                        base_steering_reward += 5.0
            
            if correct_action:
                reward += base_steering_reward
            else:
                # Reset persistence on wrong/no action
                self.steering_persistence = {'direction': 0, 'count': 0}
                if steering_urgency > 0.6:
                    penalty = -4.0 * steering_urgency
                    reward += penalty
        else:
            # Reset persistence when steering not needed
            if hasattr(self, 'steering_persistence'):
                self.steering_persistence = {'direction': 0, 'count': 0}
        
        # PROBLEM 3 FIX: More nuanced safety rewards
        speed_factor = self.car.velocity / self.car.max_velocity
        min_side_distance = min([ray_distances[i] for i in [0, 1, 2, 4, 5, 6]]) / self.rays.max_distance
        center_distance = ray_distances[3] / self.rays.max_distance
        
        # Only penalize if VERY close and in a dangerous situation
        if min_side_distance < 0.01:  # Extremely close
            # Scale penalty by speed - more dangerous at high speed
            danger_penalty = -5.0 * (1.0 - min_side_distance * 12.5) * (0.5 + speed_factor * 0.5)
            reward += danger_penalty
            #print("danger")
        elif min_side_distance < 0.0166:  # Close but manageable
            # Very small penalty, only if going fast
            if speed_factor > 0.7:
                minor_penalty = -2 * (1.0 - min_side_distance * 6.67)
                reward += minor_penalty
            #print("slight danger")

        # PROBLEM 4 FIX: Better risk/reward balance
        # Reward safe but efficient driving
        if 0.01666 <= min_side_distance  and center_distance > 0.2:
            #print("good centering")
            # Good positioning bonus
            safety_efficiency_bonus = 0.3
            # Extra bonus if maintaining good speed
            if 0.3 <= speed_factor <= 0.8:
                safety_efficiency_bonus += 0.2
            reward += safety_efficiency_bonus
        
        # Goal completion (unchanged)
        total_goals = len(self.map_generator.goals)
        if self.current_goal_index < total_goals:
            goal = self.map_generator.goals[self.current_goal_index]
            dist = point_to_line_distance(self.car.pos, goal[0], goal[1])
            if dist < 8:
                reward += 7.5
                self.passed_goals.append(self.current_goal_index)
                self.current_goal_index += 1
        
        all_goals_completed = self.current_goal_index >= total_goals
        if all_goals_completed:
            reward += 20.0
        
        # Cap rewards
        reward = max(-15.0, min(reward, 12.0))  # Increased max from 8.0
        
        self.prev_pos = pygame.math.Vector2(self.car.pos)
        return reward, collision, all_goals_completed

    def detect_curve_severity(self, ray_distances, steering_info):
        ray_distances = self.rays.get_ray_distances()
        normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
        
        # Find the longest ray and its index
        longest_distance = max(normalized_ray_distances)
        longest_index = normalized_ray_distances.index(longest_distance)
        
        # Main ray is at index 3 (center ray at 0 degrees)
        main_ray_index = 3
        
        # If main ray is the longest, return 0
        if longest_index == main_ray_index:
            return 0.0
        
        # Get adjacent rays to the longest ray
        left_adjacent_index = max(0, longest_index - 1)
        right_adjacent_index = min(len(normalized_ray_distances) - 1, longest_index + 1)
        
        left_adjacent_distance = normalized_ray_distances[left_adjacent_index]
        right_adjacent_distance = normalized_ray_distances[right_adjacent_index]
        
        # Find which adjacent ray is longer
        if left_adjacent_distance > right_adjacent_distance:
            longer_adjacent_index = left_adjacent_index
            longer_adjacent_distance = left_adjacent_distance
        else:
            longer_adjacent_index = right_adjacent_index
            longer_adjacent_distance = right_adjacent_distance
        
        # Calculate weight for the longest position between longest ray and longer adjacent
        weight = longer_adjacent_distance / longest_distance
        
        ray_angles = [-60, -30, -15, 0, 15, 30, 60]
        
        # Calculate the longest position angle (weighted between longest and longer adjacent)
        longest_ray_angle = ray_angles[longest_index]
        longer_adjacent_angle = ray_angles[longer_adjacent_index]
        longest_pos_angle = longest_ray_angle + weight * (longer_adjacent_angle - longest_ray_angle)
        
        # Front ray direction (ray 3 at 0 degrees)
        front_ray_angle = ray_angles[main_ray_index]  # 0 degrees
        
        # Calculate angle difference
        angle_difference = abs(longest_pos_angle - front_ray_angle)
        
        # Remap angle difference to dot product equivalent
        # 0-50 degrees maps to 0-1 linearly
        if angle_difference >= 50:
            curve_severity = 1.0
        else:
            curve_severity = angle_difference / 40.0
        
        return curve_severity

3. PPO-Network & Agent¶

Networks¶
  • PPO uses two networks: actor chooses actions (PolicyNetwork), critic estimates a value (ValueNetwork) of how good or bad the actions were.
  • The agent does actions and collects: the state he is in state, the action he has done, rewards and how big of an reward was given.
  • This state is the input for both networks.
  • Actor (Policy) Network
    • Inputs the state vector and outputs action probabilities.
    • Uses fully-connected layers (512→256→128) with ReLU activations.
    • Samples actions via categorical distribution for exploration.
    • Stores log-probabilities needed for clipped loss.
  • Critic (Value) Network
    • Inputs the same state vector and predicts a scalar value.
    • Shares similar architecture to the actor (512→256→128).
    • Trained by minimizing mean squared error to observed returns.
    • Compute advantage = reward + next_value - current_value.
    • Provides a baseline to compute advantage (reducing variance).
    • Helps stabilize learning by guiding policy updates.
In [ ]:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import numpy as np

class PolicyNetwork(nn.Module):
    def __init__(self, state_dim, action_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(state_dim, 512),
            nn.ReLU(),
            nn.Linear(512, 256),
            nn.ReLU(),
            nn.Linear(256, 128),
            nn.ReLU(),
            nn.Linear(128, action_dim)
        )
        for layer in self.net:
            if isinstance(layer, nn.Linear):
                nn.init.xavier_uniform_(layer.weight)
                nn.init.constant_(layer.bias, 0)
    
    def forward(self, state):
        return self.net(state)

class ValueNetwork(nn.Module):
    def __init__(self, state_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(state_dim, 512),
            nn.ReLU(),
            nn.Linear(512, 256),
            nn.ReLU(),
            nn.Linear(256, 128),
            nn.ReLU(),
            nn.Linear(128, 1)
        )
        for layer in self.net:
            if isinstance(layer, nn.Linear):
                nn.init.xavier_uniform_(layer.weight)
                nn.init.constant_(layer.bias, 0)
    
    def forward(self, state):
        return self.net(state)
PPOAgent Class Implementation¶
  • Sets up policy (actor) and value (critic) networks.
  • Uses Adam optimizer on both network parameters.
  • Initializes hyperparameters: gamma, clip_eps, epsilon decay, batch sizes.
  • select_action(state)
    • Passes through policy network to get logits.
    • Applies temperature scaling and softmax to get action probabilities.
    • Samples action from Categorical distribution.
    • Returns (action, log_prob) for storage.
  • store_experience(...)
    • Validates inputs (state, next_state, log_prob, reward) for NaNs.
    • Appends tuple to memory if valid.
  • calculate_returns_and_advantages_optimized(rewards, values, dones)
    • Computes returns and advantages in one backward pass (O(n)).
    • Uses Generalized Advantage Estimation (GAE) with λ=0.95.
    • Returns two tensors: returns, advantages.
  • update(epochs=None)
    • Skips if memory is too small.
    • Extracts and stacks experiences into tensors.
    • Checks tensors for invalid values.
    • Computes value predictions for all states.
    • Calls calculate_returns_and_advantages_optimized().
    • Normalizes advantages.
    • Iterates over update_epochs and mini‑batches:
      • Recomputes action log-probs under current policy.
      • Calculates clipped policy loss and MSE value loss.
      • Adds entropy bonus to encourage exploration.
      • Clips gradients and steps optimizer.
    • Clears memory.
    • Returns average losses and entropy if any updates occurred.
  • save(filepath) / load(filepath)
    • Saves/loads checkpoint dict with policy, value, and optimizer states.
In [ ]:
class PPOAgent:
    def __init__(self, state_dim, action_dim, lr=3e-4, gamma=0.99, clip_eps=0.2):
        self.policy = PolicyNetwork(state_dim, action_dim)
        self.value = ValueNetwork(state_dim)
        self.optimizer = optim.Adam(
            list(self.policy.parameters()) + list(self.value.parameters()), 
            lr=lr
        )
        self.memory = []
        self.gamma = gamma
        self.clip_eps = clip_eps
        self.epsilon = 1.0
        self.epsilon_decay = 0.995
        self.epsilon_min = 0.1
        self.mini_batch_size = 256
        self.update_epochs = 4  

    def select_action(self, state):
        state = torch.FloatTensor(state).unsqueeze(0)
        
        # Add input validation
        if torch.isnan(state).any() or torch.isinf(state).any():
            print(f"Warning: Invalid state detected: {state}")
            action = np.random.randint(0, 8)
            log_prob = torch.log(torch.tensor(1/8))
            return action, log_prob
        
        with torch.no_grad():
            logits = self.policy(state)
            
            if torch.isnan(logits).any() or torch.isinf(logits).any():
                print(f"Warning: Invalid logits detected: {logits}")
                action = np.random.randint(0, 8)
                log_prob = torch.log(torch.tensor(1/8))
                return action, log_prob
            
            # Apply temperature scaling
            logits = logits / 1.0
            probs = torch.softmax(logits, dim=-1)
            
            # Add small epsilon to prevent zero probabilities
            probs = probs + 1e-8
            probs = probs / probs.sum(dim=-1, keepdim=True)
            
            dist = Categorical(probs)
            action = dist.sample()
            
        return action.item(), dist.log_prob(action)

    def store_experience(self, state, action, reward, next_state, done, log_prob):
        # Validate inputs before storing
        if not (torch.isnan(torch.FloatTensor(state)).any() or 
                torch.isnan(torch.FloatTensor(next_state)).any() or
                torch.isnan(log_prob).any() or
                np.isnan(reward)):
            self.memory.append((state, action, reward, next_state, done, log_prob))

    def calculate_returns_and_advantages_optimized(self, rewards, values, dones):
        """
        Optimized O(n) calculation of returns and advantages using GAE
        """
        returns = torch.zeros_like(rewards)
        advantages = torch.zeros_like(rewards)
        
        # GAE parameters
        gae_lambda = 0.95
        
        # Calculate advantages and returns in reverse order (O(n))
        last_gae = 0
        for i in reversed(range(len(rewards))):
            if i == len(rewards) - 1:
                next_value = 0  # Terminal state
            else:
                next_value = values[i + 1]
            
            # TD error
            delta = rewards[i] + self.gamma * next_value - values[i]
            
            # GAE advantage
            advantages[i] = last_gae = delta + self.gamma * gae_lambda * last_gae
            
            # Returns = advantages + values
            returns[i] = advantages[i] + values[i]
        
        return returns, advantages

    def update(self, epochs=None):
        if len(self.memory) < 32:  # Minimum batch size
            return None
        
        # Use instance variable if epochs not specified
        if epochs is None:
            epochs = self.update_epochs
            
        # Convert experience buffer to tensors
        states, actions, rewards, next_states, dones, old_log_probs = zip(*self.memory)
        
        states = torch.FloatTensor(np.array(states))
        actions = torch.LongTensor(actions)
        rewards = torch.FloatTensor(rewards)
        old_log_probs = torch.stack(old_log_probs)
        
        # Validate tensors
        if (torch.isnan(states).any() or torch.isnan(rewards).any() or 
            torch.isnan(old_log_probs).any()):
            print("Warning: NaN detected in experience buffer, skipping update")
            self.memory.clear()
            return None
        
        # Get values for all states at once
        with torch.no_grad():
            values = self.value(states).squeeze(-1)
        
        # OPTIMIZED: O(n) returns and advantages calculation
        returns, advantages = self.calculate_returns_and_advantages_optimized(
            rewards, values, torch.zeros_like(rewards)  # dones placeholder
        )
        
        # Normalize advantages
        if len(advantages) > 1 and advantages.std() > 1e-8:
            advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
        
        # Mini-batch training for large datasets
        dataset_size = len(states)
        indices = torch.randperm(dataset_size)
        
        total_policy_loss = 0
        total_value_loss = 0
        total_entropy = 0
        update_count = 0
        
        for epoch in range(epochs):
            # Process in mini-batches to avoid memory issues
            for start_idx in range(0, dataset_size, self.mini_batch_size):
                end_idx = min(start_idx + self.mini_batch_size, dataset_size)
                batch_indices = indices[start_idx:end_idx]
                
                # Get mini-batch
                batch_states = states[batch_indices]
                batch_actions = actions[batch_indices]
                batch_advantages = advantages[batch_indices]
                batch_returns = returns[batch_indices]
                batch_old_log_probs = old_log_probs[batch_indices]
                
                # Forward pass
                logits = self.policy(batch_states)
                probs = torch.softmax(logits, dim=-1) + 1e-8
                probs = probs / probs.sum(dim=-1, keepdim=True)
                
                dist = Categorical(probs)
                new_log_probs = dist.log_prob(batch_actions)
                
                # Policy loss
                ratio = torch.exp(new_log_probs - batch_old_log_probs)
                ratio = torch.clamp(ratio, 0.1, 10.0)
                
                surr1 = ratio * batch_advantages
                surr2 = torch.clamp(ratio, 1 - self.clip_eps, 1 + self.clip_eps) * batch_advantages
                policy_loss = -torch.min(surr1, surr2).mean()
                
                # Value loss
                current_values = self.value(batch_states).squeeze(-1)
                value_loss = nn.MSELoss()(current_values, batch_returns)
                
                # Entropy
                entropy = dist.entropy().mean()
                
                # Total loss
                total_loss = policy_loss + 0.5 * value_loss - 0.01 * entropy  # Reduced entropy coefficient
                
                # Check for NaN
                if torch.isnan(total_loss) or torch.isinf(total_loss):
                    print("Warning: NaN/Inf loss detected, skipping batch")
                    continue
                
                # Optimize
                self.optimizer.zero_grad()
                total_loss.backward()
                
                # Gradient clipping
                torch.nn.utils.clip_grad_norm_(self.policy.parameters(), 0.5)
                torch.nn.utils.clip_grad_norm_(self.value.parameters(), 0.5)
                
                self.optimizer.step()
                
                # Accumulate losses
                total_policy_loss += policy_loss.detach().item()
                total_value_loss += value_loss.detach().item()
                total_entropy += entropy.detach().item()
                update_count += 1
        
        # Clear memory
        self.memory.clear()
        
        if update_count == 0:
            return None
            
        return {
            'policy_loss': total_policy_loss / update_count,
            'value_loss': total_value_loss / update_count,
            'entropy': total_entropy / update_count
        }
    
    def save(self, filepath):
        """Save the model"""
        torch.save({
            'policy_state_dict': self.policy.state_dict(),
            'value_state_dict': self.value.state_dict(),
            'optimizer_state_dict': self.optimizer.state_dict()
        }, filepath)
    
    def load(self, filepath):
        """Load the model"""
        checkpoint = torch.load(filepath, map_location='cpu')
        self.policy.load_state_dict(checkpoint['policy_state_dict'])
        self.value.load_state_dict(checkpoint['value_state_dict'])
        self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])

4. Reward Structure¶

Less Is More¶
  • most of the time fewer rewards are better when it comes to PPO
  • thats because the agent needs to keep track of fewer rewards which ultimatly makes him understand these rewards better
  • resulting in higher quality actions
  • and while the code for the rewards looks like a lot, there are really never alot of rewards given simultaneously
The Rewards¶
  • Collision Penalty: large negative reward, immediate reset.
  • Progress Bonus: reward on crossing each goal.
  • Completion Reward: big bonus on full track.
  • Speed Reward: reward near optimal speed.
  • Steering Reward: positive when pre-turn angle is correct and negative when not.
  • Safety Bonus: small reward for staying center.
  • Edge Penalty: for hugging walls to thight.
  • Collision Penalty: large negative reward, immediate reset.
Why These Rewards Make Sense¶
  • Encourage Forward Motion: Speed and progress bonuses push the agent to move forward consistently.
  • Promote Safe Driving: Penalties for collisions, hugging walls, and extreme proximity discourage risky maneuvers that often lead to failure on unfamiliar layouts.
  • Train Adaptive Steering: Steering rewards tied to detect_steering_need ensure the agent learns to anticipate and execute turns, vital for curves that differ every episode.
  • Balance Speed vs. Control: Curve-based speed management rewards slow-down in tight turns but penalizes over-braking on straights, teaching the agent when to accelerate or decelerate.
  • Motivate Completion: Goal crossing and track completion rewards align short-term steering/speed decisions with the long-term objective of finishing the course, improving overall strategy.
In [ ]:
def calculate_reward(self):
    self.rays.update(self.car.pos, self.car.direction)
    ray_distances = self.rays.get_ray_distances()
    collision = self.rays.has_zero_length_ray()
    
    if collision:
        return -100.0, collision, False       
    
    steering_info = self.detect_steering_need(ray_distances)
    reward = 0.0
    curve_severity = self.detect_curve_severity(ray_distances, steering_info)

    center_distance = ray_distances[3] / self.rays.max_distance
    if center_distance > 0.25:
        #print("accelerate now!")
        reward += 0.25 * self.car.velocity - 6

    if curve_severity > 0.1:  # Lowered threshold for earlier detection
        # Define speed categories with overlapping ranges for smoother learning
        if curve_severity > 0.5:  # Very tight curve
            # Reward any reasonable slowing down
            if 0.125 < self.car.velocity < 0.25:  # Very slow - excellent
                reward += self.car.velocity /10
            else:  # Too fast - penalty
                reward += -2
                
        elif curve_severity > 0.25:  # Moderate curve
            # Reward any reasonable slowing down
            if 0.15 < self.car.velocity < 0.35:  # Very slow - excellent
                reward += self.car.velocity /12
            else:  # Too fast - penalty
                reward += -2
                
        else:  # Slight curve (0.08-0.25)
            # Reward any reasonable slowing down
            if 0.35 < self.car.velocity < 0.7:  # Very slow - excellent
                reward += self.car.velocity /10
            else:  # Too fast - penalty
                reward += -2

    else:
        if self.car.velocity > 40:  # Moderate speed - still learning
            reward += self.car.velocity / 20
        elif self.car.velocity < 25:
            reward += -0.5

        # Reset speed consistency tracker on straights
        if hasattr(self, 'speed_consistency_tracker'):
            self.speed_consistency_tracker = {'appropriate': False, 'count': 0}
    
    # STEERING REWARDS WITH PERSISTANCE
    if steering_info['needed']:
        steering_urgency = steering_info['urgency']
        base_steering_reward = 5.0 + (steering_urgency * 4.0)  # 3-7 points
        
        # Track steering persistence
        if not hasattr(self, 'steering_persistence'):
            self.steering_persistence = {'direction': 0, 'count': 0}
            
        correct_action = False
        if steering_info['direction'] == -1:  # Need left
            if self.last_action in [1, 3, 6]:  # Left steering actions
                correct_action = True
                # Persistence bonus - reward continued steering
                if self.steering_persistence['direction'] == -1:
                    self.steering_persistence['count'] += 2
                    persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
                    base_steering_reward += persistence_bonus
                else:
                    self.steering_persistence = {'direction': -1, 'count': 1}
                
                # Extra bonus for combined brake+steer in tight curves - ONLY for correct direction
                if curve_severity > 0.4 and self.last_action == 6:  # Heavy brake + left steer
                    base_steering_reward += 5.0
                    
        elif steering_info['direction'] == 1:  # Need right
            if self.last_action in [2, 4, 7]:  # Right steering actions
                correct_action = True
                # Persistence bonus
                if self.steering_persistence['direction'] == 1:
                    self.steering_persistence['count'] += 2
                    persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
                    base_steering_reward += persistence_bonus
                else:
                    self.steering_persistence = {'direction': 1, 'count': 1}
                
                # Extra bonus for combined brake+steer in tight curves - ONLY for correct direction
                if curve_severity > 0.4 and self.last_action == 7:  # Heavy brake + right steer
                    base_steering_reward += 5.0
        
        if correct_action:
            reward += base_steering_reward
        else:
            # Reset persistence on wrong/no action
            self.steering_persistence = {'direction': 0, 'count': 0}
            if steering_urgency > 0.6:
                penalty = -4.0 * steering_urgency
                reward += penalty
    else:
        # Reset persistence when steering not needed
        if hasattr(self, 'steering_persistence'):
            self.steering_persistence = {'direction': 0, 'count': 0}
    
    #nuanced safety rewards
    speed_factor = self.car.velocity / self.car.max_velocity
    min_side_distance = min([ray_distances[i] for i in [0, 1, 2, 4, 5, 6]]) / self.rays.max_distance
    center_distance = ray_distances[3] / self.rays.max_distance
    
    # Only penalize if VERY close and in a dangerous situation
    if min_side_distance < 0.01:  # Extremely close
        # Scale penalty by speed - more dangerous at high speed
        danger_penalty = -5.0 * (1.0 - min_side_distance * 12.5) * (0.5 + speed_factor * 0.5)
        reward += danger_penalty
        #print("danger")
    elif min_side_distance < 0.0166:  # Close but manageable
        # Very small penalty, only if going fast
        if speed_factor > 0.7:
            minor_penalty = -2 * (1.0 - min_side_distance * 6.67)
            reward += minor_penalty
        #print("slight danger")

    # risk/reward balance
    # Reward safe but efficient driving
    if 0.01666 <= min_side_distance  and center_distance > 0.2:
        #print("good centering")
        # Good positioning bonus
        safety_efficiency_bonus = 0.3
        # Extra bonus if maintaining good speed
        if 0.3 <= speed_factor <= 0.8:
            safety_efficiency_bonus += 0.2
        reward += safety_efficiency_bonus
    
    # Goal completion (unchanged)
    total_goals = len(self.map_generator.goals)
    if self.current_goal_index < total_goals:
        goal = self.map_generator.goals[self.current_goal_index]
        dist = point_to_line_distance(self.car.pos, goal[0], goal[1])
        if dist < 8:
            reward += 7.5
            self.passed_goals.append(self.current_goal_index)
            self.current_goal_index += 1
    
    all_goals_completed = self.current_goal_index >= total_goals
    if all_goals_completed:
        reward += 20.0
    
    # Cap rewards
    reward = max(-15.0, min(reward, 12.0))  # Increased max from 8.0
    
    self.prev_pos = pygame.math.Vector2(self.car.pos)
    return reward, collision, all_goals_completed
detect_curve_severity(ray_distances, steering_info)¶
  • This function tells us how sharp the next turn is by looking at the car’s surrounding distances:
  • Measure Surroundings: we take the seven ray distances (left to right) and scale them to a 0–1 range.
  • Find the most “Open” Direction by picking the ray with the biggest distance / the direction with the most free space.
  • Check Straight: if the straight‑ahead ray is the widest, there’s no curve → we call it 0 (straight).
  • Smooth the Angle: otherwise, we look at the neighboring ray that’s also fairly open. By mixing the two angles (main and adjacent) in proportion to how open they are, we get a smoother estimate of the true turn angle.
  • Calculate Deviation: find how many degrees that mixed angle is away from straight ahead.
  • Scale to 0–1: if it’s very large (≥50°), we say it’s a full 1.0; for smaller turns, we linearly map the angle difference (0–40°) onto 0–1.
  • The result is a single number between 0 and 1 which is used by the agent to give a reward for correct speed and steering.
In [ ]:
def detect_curve_severity(self, ray_distances, steering_info):
    ray_distances = self.rays.get_ray_distances()
    normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
    
    # Find the longest ray and its index
    longest_distance = max(normalized_ray_distances)
    longest_index = normalized_ray_distances.index(longest_distance)
    
    # Main ray is at index 3 (center ray at 0 degrees)
    main_ray_index = 3
    
    # If main ray is the longest, return 0
    if longest_index == main_ray_index:
        return 0.0
    
    # Get adjacent rays to the longest ray
    left_adjacent_index = max(0, longest_index - 1)
    right_adjacent_index = min(len(normalized_ray_distances) - 1, longest_index + 1)
    
    left_adjacent_distance = normalized_ray_distances[left_adjacent_index]
    right_adjacent_distance = normalized_ray_distances[right_adjacent_index]
    
    # Find which adjacent ray is longer
    if left_adjacent_distance > right_adjacent_distance:
        longer_adjacent_index = left_adjacent_index
        longer_adjacent_distance = left_adjacent_distance
    else:
        longer_adjacent_index = right_adjacent_index
        longer_adjacent_distance = right_adjacent_distance
    
    # Calculate weight for the longest position between longest ray and longer adjacent
    weight = longer_adjacent_distance / longest_distance
    
    ray_angles = [-60, -30, -15, 0, 15, 30, 60]
    
    # Calculate the longest position angle (weighted between longest and longer adjacent)
    longest_ray_angle = ray_angles[longest_index]
    longer_adjacent_angle = ray_angles[longer_adjacent_index]
    longest_pos_angle = longest_ray_angle + weight * (longer_adjacent_angle - longest_ray_angle)
    
    # Front ray direction (ray 3 at 0 degrees)
    front_ray_angle = ray_angles[main_ray_index]  # 0 degrees
    
    # Calculate angle difference
    angle_difference = abs(longest_pos_angle - front_ray_angle)
    
    # Remap angle difference to dot product equivalent
    # 0-50 degrees maps to 0-1 linearly
    if angle_difference >= 50:
        curve_severity = 1.0
    else:
        curve_severity = angle_difference / 40.0
    
    return curve_severity

5. Training- Loop¶

Initialization¶
  • Creates the driving environment and the PPO agent.
  • Sets up frame‑rate targets (how fast physics and rendering run).
  • Optionally loads a saved model so training can resume.
Episode Loop¶
  • Repeats forever (or until you quit):
  • Reset the track and car to start a new run.
  • Zero out counters for total reward, steps taken, collisions, completed laps, and steering stats.
Step Loop¶
  • Until you hit the maximum number of steps per episode:
  • Check for a quit command (so you can close the window).
  • Ask the agent: which action would you take?
  • Apply that action (accelerate, brake, steer) to advance the car.
  • Observe the new state, get a reward score, and see if the car crashed or finished.
  • Record this experience (state, action, reward, next state) for learning later.
  • Track whether the agent needed to steer and if it did so correctly.
  • If the car crashed or completed the course, reset it; otherwise, continue.
Optionally draw the scene (road, car, vision rays) and overlay stats like reward, goals hit, and steering accuracy.¶
Learning Update¶
  • After each episode, if enough experiences have been gathered, call the agent’s update() method to run the PPO optimization (using the stored batch of experiences).
  • Every so often, gently lower the learning rate to fine‑tune.
  • Every 10 episodes, save the agent’s model to disk.
Reporting¶
  • Print a summary each episode:
  • Total and average reward.
  • Steering performance.
  • Goals reached, collisions, and action distribution.
  • Frames-per-second or steps-per-second statistics.
In [ ]:
async def train(fps=120, display=True, batch_size=32, action_space=ACTION_SPACE, load_model=False):
    env = TrainingEnvironment()
    state = env.get_state()
    state_size = len(state)
    action_size = action_space
    
    # Increase learning rate slightly for better steering learning
    agent = PPOAgent(state_size, action_size, lr=2e-3)
    
    rewards_history = deque(maxlen=100)
    steering_rewards_history = deque(maxlen=100)
    total_episodes = 0
    
    render = display
    target_fps = fps
    simulation_fps = fps
    dt = 1.0 / simulation_fps
    
    print(f"Training - Simulation FPS: {simulation_fps}, Render FPS: {target_fps}, Display: {render}, Batch Size: {batch_size}")
    print(f"State size: {state_size}, Action size: {action_size}")
    
    last_time = time.time()
    frame_count = 0
    steps_per_second_history = deque(maxlen=10)

    if load_model: 
        # Initialize the agent with the same state and action sizes used during training
        agent = PPOAgent(state_size, action_size)
        user_device = "cuda" if torch.cuda.is_available() else "cpu"
        # Load the checkpoint file
        checkpoint = torch.load(LOADED_MODEL, map_location=user_device) 

        # Load the state dictionaries into the agent's components
        agent.policy.load_state_dict(checkpoint['policy_state_dict'])
        agent.value.load_state_dict(checkpoint['value_state_dict'])
        agent.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
        print(f"Loaded Base Model successfully: {LOADED_MODEL}")
    
    while True:
        env.reset()
        state = env.get_state()
        total_reward = 0
        total_steering_reward = 0
        steps = 0
        collision_count = 0
        completion_count = 0
        epoch_start_time = time.time()
        
        # Action statistics - Initialize properly
        action_counts = [0] * action_space
        steering_needed_count = 0
        correct_steering_count = 0

        while steps < MAX_STEPS:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    return
            
            action, log_prob = agent.select_action(state)

            if isinstance(action, torch.Tensor):
                action_int = int(action.item())
            elif isinstance(action, np.ndarray):
                action_int = int(action.item())
            else:
                action_int = int(action)
            
            env.execute_action_dispatch(action_int, dt)  
            next_state = env.get_state()
            reward, collision, all_goals_completed = env.calculate_reward()

            if 0 <= action_int < len(action_counts):
                action_counts[action_int] += 1
            
            total_steering_reward += env.last_steering_reward
            
            # Check if steering was needed and if action was correct
            ray_distances = env.rays.get_ray_distances()
            steering_info = env.detect_steering_need(ray_distances)
            if steering_info['needed']:
                steering_needed_count += 1
                if ((steering_info['direction'] == -1 and action_int in [1, 3]) or
                    (steering_info['direction'] == 1 and action_int in [2, 4])):
                    correct_steering_count += 1
            
            done = (steps == MAX_STEPS - 1)
            agent.store_experience(state, action, reward, next_state, done, log_prob)
            
            if collision or all_goals_completed:
                if collision:
                    collision_count += 1
                if all_goals_completed:
                    completion_count += 1
                env.reset_car()
                state = env.get_state()
            else:
                state = next_state
            
            total_reward += reward
            steps += 1
            frame_count += 1

            if render and (steps % max(1, simulation_fps // target_fps) == 0):
                current_time = time.time()
                screen.fill((255, 255, 255))
                env.map_generator.draw(screen)
                env.car.draw(screen)
                
                # Draw rays
                for i, (angle, offset) in enumerate(zip([-60, -30, -15, 0, 15, 30, 60], [14, 22, 27, 26, 27, 22, 14])):
                    if i < len(env.rays.last_collisions):
                        ray_dir = env.car.direction.rotate(angle).normalize()
                        origin = env.car.pos + ray_dir * offset
                        end_point = env.rays.last_collisions[i]
                        pygame.draw.line(screen, (255, 255, 0), 
                                       (int(origin.x), int(origin.y)), 
                                       (int(end_point.x), int(end_point.y)), 
                                       width=2)
                
                # Calculate FPS
                actual_sps = frame_count / (current_time - last_time) if (current_time - last_time) > 0 else 0
                steps_per_second_history.append(actual_sps)
                avg_sps = sum(steps_per_second_history) / len(steps_per_second_history)
                
                # Display information
                font = pygame.font.Font(None, 36)
                info_text = f"Epoch: {total_episodes + 1} | Step: {steps}/{MAX_STEPS}"
                screen.blit(font.render(info_text, True, (0, 0, 0)), (10, 10))
                reward_text = f"Total Reward: {total_reward:.1f}"
                screen.blit(font.render(reward_text, True, (0, 0, 0)), (10, 50))
                goals_text = f"Goals: {len(env.passed_goals)}/{len(env.map_generator.goals)} | Velocity: {env.car.velocity:.1f}"
                screen.blit(font.render(goals_text, True, (0, 0, 0)), (10, 90))
                stats_text = f"Collisions: {collision_count} | Completions: {completion_count}"
                screen.blit(font.render(stats_text, True, (0, 0, 0)), (10, 130))
                
                # Steering performance
                steering_accuracy = (correct_steering_count / max(steering_needed_count, 1)) * 100
                steering_text = f"Steering Accuracy: {steering_accuracy:.1f}% ({correct_steering_count}/{steering_needed_count})"
                screen.blit(font.render(steering_text, True, (0, 0, 0)), (10, 170))
                
                speed_text = f"Target FPS: {simulation_fps} | Actual SPS: {avg_sps:.1f}"
                screen.blit(font.render(speed_text, True, (0, 0, 0)), (10, 210))
                
                pygame.display.flip()
                clock.tick(target_fps)
                if frame_count > 0:
                    last_time = current_time
                    frame_count = 0
        
        epoch_end_time = time.time()
        epoch_duration = epoch_end_time - epoch_start_time
        actual_sps = MAX_STEPS / epoch_duration if epoch_duration > 0 else 0
        
        # Update and report
        if len(agent.memory) >= batch_size:
            loss_info = agent.update()
            if loss_info:
                print(f"Agent updated - Policy Loss: {loss_info['policy_loss']:.4f}")
        else:
            print(f"Not enough experiences for update ({len(agent.memory)}/{batch_size})")
            agent.memory.clear()
            
        rewards_history.append(total_reward)
        steering_rewards_history.append(total_steering_reward)
        total_episodes += 1
        avg_reward = sum(rewards_history) / len(rewards_history)
        avg_steering_reward = sum(steering_rewards_history) / len(steering_rewards_history)

        # Learning rate decay
        if total_episodes > 50:
            for param_group in agent.optimizer.param_groups:
                param_group['lr'] = max(5e-5, param_group['lr'] * 0.999)

        # Calculate steering accuracy
        steering_accuracy = (correct_steering_count / max(steering_needed_count, 1)) * 100
        
        print(f"\n=== Epoch {total_episodes} Complete ===")
        print(f"Total Reward: {total_reward:.1f} | Avg (100): {avg_reward:.1f}")
        print(f"Steering Reward: {total_steering_reward:.1f} | Avg (100): {avg_steering_reward:.1f}")
        print(f"Steering Accuracy: {steering_accuracy:.1f}% ({correct_steering_count}/{steering_needed_count})")
        print(f"Goals Completed: {len(env.passed_goals)}/{len(env.map_generator.goals)}")
        print(f"Collisions: {collision_count} | Completions: {completion_count}")
        print(f"Action Distribution: {dict(zip(['Accel', 'Left', 'Right', 'Accel+L', 'Accel+R', 'Brake'], action_counts))}")
        print("="*80)

        if total_episodes % 10 == 0:
            agent.save(f"car_model_epoch_{total_episodes}.pth")
            print(f"Model saved at epoch {total_episodes}")

if __name__ == "__main__":
    asyncio.run(train(fps=SIMULATION_FPS, display=True, batch_size=BATCH_SIZE, action_space=ACTION_SPACE, load_model=True))

6. Possible Improvements & Future Work¶

Size Matters¶
  • Reduce model size for inference: A smaller actor and critic network can process states faster, allowing higher simulation speeds.
  • Large networks introduce latency in action selection, slowing down both training and real-time evaluation.
  • Optimize layer dimensions: Pruning or using fewer hidden units may maintain performance while cutting compute requirements by up to 30%.
  • Empirical studies show that over-parameterization yields diminishing returns once basic driving behaviors are learned.
Real Environments¶
  • Add moving objects: Incorporate pedestrians, AI-driven cars, or cyclists to teach the agent to anticipate and react safely.
  • Real traffic involves unpredictable agents; learning in a static world limits transferability to real scenarios.
  • Include traffic signals and signs: Stop signs, lights, and yield markers enforce rule-based behavior essential for real roads.
  • Rule compliance reduces randomness and builds trust for human oversight in shared environments.
  • Vary terrain elevation: Random hills, ramps, and uneven surfaces challenge the car’s speed control and traction management.
More for Speed Optimized Setup¶
  • Adjust reward scales for speed: Increasing the weight on forward velocity can incentivize faster travel when safe.
  • Under the current reward, the agent prefers caution over efficiency, leading to unnecessarily slow laps.
  • Introduce time-based penalties: Minor penalties for excessive lap times push the agent to balance safety with speed.
  • Time constraints emulate real-world deadlines, urging the agent to optimize route and throttle.
  • Configure curriculum learning: Start with gentle curves and gradually ramp up difficulty to teach high-speed control.
Thanks for reading :D¶