Skip to content
Back to projects

Neural Network from Scratch

AI Cars (Vanilla JS)

Vanilla JSNeural NetworkGenetic AlgorithmHTML5 CanvasZero Dependencies

A neural-network self-driving car simulation written from scratch in vanilla JavaScript - no libraries, no build step, no dependencies. Open index.html and it runs.

Each car has a fixed-topology network: N sensor rays cast forward in a fan, six hidden neurons, and four outputs that drive up/left/right/down. The network is step-activated and mutation-only - there is no backpropagation, no gradient descent, no math library. Training runs as a genetic algorithm: a population of 100 cars all start with brains derived from the all-time best, car 0 keeps the champion brain unmutated (elitism), every other car gets a mutated copy. A generation ends when every car crashes; the highest-fitness car (distance + topSpeed*5 - crashPenalty) becomes the new champion. If best fitness fails to improve for three generations, mutation rate auto-increases to escape the plateau.

The live UI is the entire point. The driving canvas shows the road, traffic, the ghost-faded population, the highlighted best car with its sensor rays, tire trails, and crash particles. A second canvas draws the best car's brain - connection thickness proportional to weight magnitude, color showing sign, node radius pulsing with activation, bias rings showing each neuron's threshold. A third canvas plots best (green) and average (faint white) fitness per generation. A control panel lets you tune population, mutation rate, sensor ray count, ray length, and sim speed without reloading. There is a 1x/2x/5x/10x speed multiplier for fast-forward training, manual driving mode with spawn invulnerability, save/load brains to localStorage and to/from JSON files (drag-and-drop supported), light/dark theme with system-preference detection, and an FPS/HUD overlay.

A pre-trained champion brain is committed at champion-brain.json - drop it onto the page to load a driver that survived 325k pixels (about 6,500 car-lengths) without crashing.

Deployed at car-ai.halemogpa.com.

Live training

Open in new tab
Demo loads on scroll...