eztraffic-light
v1.0.2
Published
Powerful traffic light logic engine for animations, games, and smart city simulations. Features fluent API and built-in real-time dashboard.
Maintainers
Readme
traffic-light 🚦
A flexible, event-driven Node.js & Browser package for managing traffic light logic in simulations, 3D games (like Three.js), and smart city models.
Easily create complex intersections, pedestrian crossings, and timed sequences with a fluent, readable API.
Features
- Fluent API: Chain methods like
wait(10).andTurnGreen()orif(light).green.then(other).red. - Event-Based: React to color changes using listeners.
- Built-in Prefabs: Quickly initialize 2-way intersections and pedestrian crosswalks.
- Safety Logic: Conditional linking prevents unsafe states (e.g. two roads being green simultaneously).
- Broken State: Support for "Broken" lights for realistic game scenarios.
- Isomorphic Core: Native ESM Support (
core.js) for Vite, Three.js, and modern Node. - Dynamic Time Scaling:
system.setTimeScale(2.0)updates all active timers immediately. - Conflict Groups:
system.addConflictGroup([a, b])prevents multiple green lights in high-risk zones. - State History:
light.getHistory()returns a buffer of recent performance for analytics. - Fluent Setup:
light.setCycle(['red','green']).setDurations([10,5]). - First-Class Flashing:
light.startFlashing('yellow', 500)managed natively by the engine. - Smart Crosswalks:
requestCrossing()triggers logic to safely shorten car green lights. - State Serialization:
toJSON()andimport(json)for instant game saves/loads.
🏗️ ESM Integration
The package is built with standard ES Modules. No hacks or custom configurations are required for Vite or modern Node.
// Browser / Vite / Three.js
import { TrafficSystem } from 'eztraffic-light/core.js';
// Node.js (with Dashboard)
import { TrafficSystemServer } from 'eztraffic-light';Usage
⚙️ Scaling Simulation Time
const system = new TrafficSystem({ devInfo: true });
system.setTimeScale(2.0); // Make simulation 2x faster (instantly updates active timers)🛡️ Preventing Collisions (Conflict Groups)
const roadA = system.createLight('Road A');
const roadB = system.createLight('Road B');
// Safety: If Road A is Green, Road B is BLOCKED from turning green
system.addConflictGroup([roadA, roadB]);
roadA.turnGreen();
roadB.turnGreen(); // Will be BLOCKED and logged as a safety violation🚥 Creating Lights
const mainRoad = system.createLight('Main Road');
const crossWalk = system.createPedestrianLight('Crosswalk');
// Simple color changes
mainRoad.turnGreen();
mainRoad.turnYellow();
mainRoad.turnRed();
// Timed sequences
mainRoad.wait(5).andTurnYellow();
mainRoad.wait(8).andTurnRed();🔗 Linking Logic (Safety Constraints)
You can link lights together so they always maintain safe states automatically.
// Whenever Main Road turns Green, the Crosswalk MUST turn Red (Don't Walk)
mainRoad.ifGreen().then(crossWalk).turnsDontWalk();
// Conditional triggers
mainRoad.ifRed().then(otherRoad).turnsGreen();🏗️ Using Built-in Scenarios (Prefabs)
Initialize common configurations in one line:
// Create a 2-way intersection that prevents simultaneous green lights
const intersection = system.createIntersection('North/South', 'East/West');
intersection.startStandardCycle(10, 3); // 10s Green, 3s Yellow
// Create a vehicle street + pedestrian walkway crosswalk
const landing = system.createPedestrianCrossing('Avenue 1', 'Crosswalk');
landing.startStandardCycle(12, 6); // 12s Car green, 6s Walk time🚨 Handling Malfunctions (Gamer Mode)
Simulate realistic city issues in your game:
light.break(); // Starts flashing Red
light.fix(); // Resumes normal operation🌙 Warning Mode (Night/Maintenance)
Force the entire system into a caution state (Yellow flashing for cars, Red flashing for peds):
system.setWarningMode(true);💾 Saving & Loading (Serialization)
Perfect for game saves or syncing state between clients:
const saveData = system.toJSON(); // Export everything
system.import(saveData); // Restore everythingDashboard & Simulation
If you provide a port in the constructor, the package starts an Express server that broadcasts states via Socket.io. You can use this to:
- Visually test your logic at http://localhost:SERVER_PORT.
- Use the provided real-time state object to update your Three.js or Unity scenes.
// In your Frontend/Dashboard
socket.on('update', (states) => {
// states['Main Road'] = { state: 'green', isBroken: false, type: 'vehicle' }
});