Traffic Simulator Project

Traffic Simulator: Smart Signal Control Tutorial

This interactive tutorial teaches students how to create intelligent traffic light control systems using JavaScript. By harnessing real-time data from a traffic simulation, students learn to write algorithms that optimize traffic flow at an intersection.

What You'll Learn

  • How to listen for custom events in JavaScript
  • How to access and interpret real-time traffic statistics
  • How to use conditional logic to make automated decisions
  • How to optimize traffic signals based on multiple factors

Key Concepts

The tutorial introduces the trafficStatsChange event that provides live data about traffic conditions, including:

  • Wait times for vehicles
  • Number of stopped cars
  • Traffic throughput and efficiency metrics
  • Time since traffic signals last changed

Students implement progressively more sophisticated control algorithms:

  1. Simple timed signal changes
  2. Traffic volume-based control
  3. Wait time optimization
  4. Multi-factor "pressure score" systems

Interactive Environment

The split-screen layout provides:

  • A code editor where students write JavaScript to control traffic signals
  • A live traffic simulation showing the effects of their algorithms
  • Real-time statistics to evaluate their solution's effectiveness

This project offers a practical application of programming concepts in a relatable real-world scenario that students can visualize and optimize through experimentation.

Using the trafficStatsChange Event

The traffic simulator provides real-time statistics through a custom event called trafficStatsChange. You can use this event to create smart traffic light controllers that respond to changing traffic conditions!

Step 1: Create an Event Listener

First, you need to set up a listener that will run your code whenever new traffic data becomes available. The event listener connects to the simulation container and gives you access to real-time traffic statistics.

document.getElementById('simulation-container').addEventListener('trafficStatsChange', function(event) {
  // Your traffic control logic goes here
  const stats = event.detail;
  
  // Example: Log the current stats to see what's happening
  console.log(stats);
});
Step 2: Access Traffic Statistics

The event.detail object contains all the data you need about the current traffic situation. Each field provides specific information that you can use to make intelligent decisions about when to change the traffic lights.

Field Name Description
'Time since last signal change'Seconds since traffic lights changed - use this to prevent lights from changing too frequently
'Time since first car stopped'Seconds since the first car stopped - helps identify long waits at red lights
'Number of cars stopped'Current count of stopped cars - indicates congestion at red lights
'Total cars passed'Total cars that passed through - measures overall throughput of your system
'Total cars approached'Total cars that approached - shows total traffic volume handled
'Avg cars per minute'Average throughput rate - indicates efficiency of your signal timing
'Avg approaches per minute'Average approach rate - shows traffic demand over time
'Avg wait time (sec)'Average wait time per car - key measure of driver experience
Step 3: Create Logic to Control Signals

Now comes the fun part! You can write conditional statements (if statements) that decide when to change the traffic lights based on the statistics you're receiving. The goal is to create a system that keeps traffic flowing efficiently.

Tip: Use document.getElementById('toggleLights').click() to change traffic lights. This simulates clicking the button that controls the signals.
Example: Change Lights After Set Time

This simple approach changes lights on a fixed schedule, similar to traditional traffic lights:

// Change lights every 30 seconds
if (stats['Time since last signal change'] >= 30) {
  document.getElementById('toggleLights').click();
}
Example: Change Based on Traffic Volume

This smarter approach responds to the number of cars waiting at red lights, but still ensures a minimum green time:

// Change lights when more than 5 cars are waiting
if (stats['Number of cars stopped'] > 5 && stats['Time since last signal change'] >= 15) {
  document.getElementById('toggleLights').click();
}
Example: Change Based on Wait Time

This approach focuses on driver experience by monitoring the average wait time:

// Change when average wait time is too high
if (stats['Avg wait time (sec)'] > 20 && stats['Time since last signal change'] >= 10) {
  document.getElementById('toggleLights').click();
}
Challenge: Smart Traffic Control

Create a traffic control algorithm that balances wait times and throughput by considering multiple factors at once. This more advanced approach uses a scoring system to weigh different aspects of the traffic situation:

// Calculate a "pressure score" based on multiple factors
const waitScore = stats['Number of cars stopped'] * 2;   // More weight for stopped cars
const timeScore = stats['Avg wait time (sec)'] * 1.5;    // Some weight for waiting time
const totalScore = waitScore + timeScore;

// Change lights if pressure exceeds threshold and minimum time has passed
if (totalScore > 25 && stats['Time since last signal change'] >= 10) {
  console.log(`Changing lights: Score=${totalScore.toFixed(1)}`);
  document.getElementById('toggleLights').click();
}
Using If/Else Statements for More Advanced Control

Sometimes you need to make different decisions based on various conditions. This is where if/else statements become powerful:

// Basic if/else structure
if (condition) {
  // Code that runs when condition is true
} else {
  // Code that runs when condition is false
}

// Example: Different behavior based on traffic direction
if (stats['Number of cars stopped'] > 8) {
  // Heavy congestion - change lights immediately
  document.getElementById('toggleLights').click();
} else {
  // Lower congestion - log status but don't change yet
  console.log("Traffic still flowing well, maintaining current signal");
}
Multiple Conditions with Else If

For more complex decision trees with multiple options, use else if:

// Different actions based on congestion level
if (stats['Number of cars stopped'] > 10) {
  // Heavy congestion - immediate action
  console.log("Heavy congestion detected!");
  document.getElementById('toggleLights').click();
} else if (stats['Number of cars stopped'] > 5) {
  // Medium congestion - check wait time before deciding
  if (stats['Avg wait time (sec)'] > 15) {
    console.log("Medium congestion with significant wait times");
    document.getElementById('toggleLights').click();
  }
} else {
  // Light traffic - maintain regular timing
  if (stats['Time since last signal change'] >= 30) {
    console.log("Regular signal change on timer");
    document.getElementById('toggleLights').click();
  }
}
Nested If Statements

You can place if statements inside other if statements to create more complex logic:

// Nested decision example
if (stats['Time since last signal change'] >= 10) {
  // Minimum time has passed, now we can consider changing
  if (stats['Number of cars stopped'] > 3) {
    // Check if cars have been waiting too long
    if (stats['Time since first car stopped'] > 20) {
      console.log("Cars waiting too long - changing lights");
      document.getElementById('toggleLights').click();
    }
  }
}
Tip: While nested if statements are powerful, don't make them too complex! Too much nesting can make your code hard to understand and maintain.

Try modifying these examples to create your own traffic control system! What factors do you think are most important? Can you create an algorithm that outperforms standard timed lights?

Traffic Signal Logic Editor