luangrezende/neural-network-circuit-game
关于
Watch 80 cars learn to drive Interlagos, or a track you draw, and switch between four learning algorithms while it runs. About 2,700 lines of Python and NumPy, no deep-learning framework.
人工智能与机器学习实测星标增长
- 24小时
- 0
- 7天
- 正在收集历史
- 15天
- 正在收集历史
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文Neural Network Circuit Game
Watch 80 cars learn to drive Interlagos, or a track you draw, and switch between four learning algorithms while it runs to see how each one finds better drivers. About 2,600 lines of Python and NumPy, with no deep-learning framework.

Interlagos, genetic algorithm. White cars survived from the last generation, blue ones are mutated copies, lilac ones mix two parents and orange ones are brand new. The green car is the leader.
benchmark.py runs the four algorithms below (see Four ways to learn) without a window. On Interlagos, 3 seeds each, up to 250 generations:
| Algorithm | First lap, generation (seeds 1 / 2 / 3) | 10 laps, generation (seeds 1 / 2 / 3) |
|---|---|---|
| Random search | never (best car: 8% of a lap) | never |
| Hill climbing | 69 / 123 / 38 | 75 / 125 / 56 |
| Genetic algorithm | 109 / 114 / never (64% of a lap) | 163 / 124 / never |
| Evolution strategy | 248 / 220 / 124 | never (4.6 laps) / 227 / 182 |
Random search never gets past the first corner. On this track the simple hill climber is the fastest, and the
genetic algorithm and the evolution strategy each miss once in 250 generations: one seed can change the result a
lot, which is part of what is worth watching. Reproduce it with
python benchmark.py --seeds 1 2 3 --max-gens 250.
Every car is a small neural network reading seven distance sensors. The whole population drives at once; when the last car stops, each one gets a score and the chosen algorithm builds the next 80 networks from those scores. There is no backpropagation: weights only change by copying, mixing and adding noise.
Status: hobby project (v2.0.1, November 2026), maintained when I have time. Runs from source on Python 3.11+ and as a Windows executable; issues are welcome. MIT licensed.
What you see on screen
| On the track | Meaning |
|---|---|
| Car colour | Where its network came from: white kept or copied as is, blue mutated, lilac crossed from two parents, orange brand new. The legend is in the algorithm panel |
| Green car with a ring | The leader right now. The network panel shows its neurons firing as it drives |
| White rays | The leader's 7 sensors. The tip turns red when a wall is close |
| White lines | The path of the best car in each of the last few generations, the newest brightest |
| Red x | A car that crashed or stalled in this generation. Press d to also show every crash so far |
Scroll the mouse wheel over the track to zoom in where the pointer is, and press 0 to see the whole track again.
The follow the leader button (or f) puts the camera on the leading car so you can watch it drive; scrolling
while following changes how close the camera is.

Under the generation number, one line says how far the best car of the previous generation got. The chart at the bottom left tracks that distance, in laps, for every generation; the dotted line is one full lap.
The two panels on the right follow the leader as it drives. AI commands shows what its network is doing right now: steering, throttle (gas above 0.5, brake below) and speed. After the first lap, the red mark on the speed bar is the minimum speed; below it the car loses points. Events lights up whatever is earning or costing the leader points at that moment: speed, a completed lap, getting too close to a wall, driving the wrong way or going too slow (how a car is scored).
Four ways to learn
Press 1 to 4 at any time to restart training with another algorithm. They share the track, the cars and the
score; only the step from one generation to the next changes.
| Key | Algorithm | How the next generation is built |
|---|---|---|
1 |
Random search | 79 new random networks plus the best one ever seen. It does not learn, which makes it a good baseline |
2 |
Hill climbing | One champion, 79 copies of it with random noise. The best car becomes the next champion |
3 |
Genetic algorithm | The 10 best survive; 60 children copy or mix two of them with mutation; 10 random newcomers keep variety. Noise grows when progress stalls |
4 |
Evolution strategy | One centre network and 79 noisy versions of it. The new centre is a weighted average of the 10 best, so it moves in the direction that raised the score: a gradient estimate without backpropagation |
Quick start
Windows executable
Download the latest .zip from Releases,
extract it and run neural-network-circuit-game.exe. No Python needed. The executable is not code-signed, so
Windows SmartScreen may ask you to confirm. Options such as --track original also work on the .exe.
From source
Python 3.11 or newer:
git clone https://github.com/luangrezende/neural-network-circuit-game.git
cd neural-network-circuit-game
python -m venv .venv
.venv\Scripts\activate # Linux / macOS: source .venv/bin/activate
pip install -r requirements.txt
python main.py
On Windows, run.cmd does the same, using uv when it is installed.
python main.py --track original --algo es --seed 3 --speed 4
| Option | Default | |
|---|---|---|
--track |
interlagos |
interlagos, original, custom (from the editor) or a path to a track .json |
--algo |
genetico |
aleatorio, subida, genetico or es (keys 1 to 4) |
--seed |
random | Same seed, same training run |
--speed |
1 |
Simulation steps per drawn frame: 1, 2, 4, 8, 16 or 32 |
Keys
| Key | |
|---|---|
r |
Run again from generation 1 (or click run again); asks first |
1 to 4 |
Restart with another algorithm; asks first |
space |
Pause |
+ / - |
Speed up or slow down (1x to 32x) |
n |
Finish the current generation instantly |
s / t / d |
Sensor rays, trails, every crash so far, on or off |
f |
Follow the leader with the camera |
mouse wheel / 0 |
Zoom in and out / whole track |
h |
Help |
q |
Quit |
Training ends when a car completes 10 laps. Run from source, it then saves the winning network's weights, the
generation, the algorithm and the best lap time to resultados.json.
Draw your own track
python track_editor.py
python main.py --track custom
Click to place control points, set the width with the slider and save. The start line sits between the first two
points, and the editor writes tracks/custom.json.
The neural network
8 inputs (7 distance sensors + speed)
↓
14 hidden units (sigmoid)
↓
2 outputs: steer (-1..+1), throttle (0..1) (sigmoid)
156 weights in total. Population size, rewards, penalties and car physics are all in config.json; the code
layout, the track format and how the executable is built are in docs/development.md.
How a car drives
Every simulation step, the two outputs move the car:
| Output | Effect per step |
|---|---|
| Steer | The heading turns by up to 12°, in proportion to the output (0.5 turns 6°). Turning does not depend on speed, so a stopped car can spin in place |
| Throttle | No middle ground: above 0.5 the speed goes up by 0.025, below it goes down by 0.025. Speed stays between 0 and 1 unit per step |
Then the car moves straight ahead, along its heading, by its speed. Every car starts at rest and needs 40 steps of full throttle to reach top speed, and 40 steps of braking to stop again (on Interlagos, 1 unit is 20 m). With no coasting, the only way to hold a speed is to alternate gas and brake. Speed is also the eighth input, so the network knows how fast it is going when it decides.
How a car is scored
The score is what the cars learn, so every rule closes a cheap way to earn points. It is the sum of what a car
earns and loses every step, plus lap rewards, and the rules change after the first lap: before it, the goal is to
get round; after it, to get round fast. All the numbers below come from config.json.
Every step
| Rule | Points | When |
|---|---|---|
| Progress | +15 for every new centreline point reached, × a speed factor from 0.2 (stopped) to 1 (top speed). Only new ground counts | Always |
| Wall distance | +3 × shortest sensor reading × speed. Small on purpose: a tie-breaker | Always |
| Speed | Above a minimum speed, up to +8 per step; below it, up to −4 per step, in proportion to the gap. The minimum starts at 20% of top speed and rises 5 points per lap (90% at most); both weights grow by 2 per lap. It is the red mark on the speed bar | After lap 1 |
| Wall ahead | Up to −4 per step when one of the three front sensors (−22.5°, 0°, 22.5°) sees a wall closer than one track width; more the closer it is | After lap 1 |
| Wrong way | When the car points against the track direction, nothing it earns in that step counts. After lap 1 it also loses up to 12 per step: little when sideways, 12 when facing backwards | Always |
On lap 5, for example, the minimum speed is 40%, top speed earns 16 per step and standing still costs 12.
Every lap
A lap counts only if the car crosses the finish line after covering at least 70% of the centreline and getting at least 5 units away from the start, so driving back and forth over the line earns nothing.
| Reward | Points |
|---|---|
| Lap | +1,000 |
| Lap time | +800 × record ÷ lap time: 800 for matching the record, 400 for taking twice as long. Before there is a record, the reference is 200 steps; every faster lap becomes the new record |
| Personal best | +1,000 × fraction of time cut × laps completed × 2. Cutting 10% on lap 5 is worth 1,000 |
Leaving the race
| Reason | Rule |
|---|---|
| Off track | The car touches the wall: −800 and it stops |
| No progress | Every 40 steps the car must have moved at least 10 centreline points forward, otherwise it stops. Without this, spinning in place would be a valid strategy. Each car starts this count at a random step so they are not all checked at once |
| Continuous point loss | The score fell by more than 40 in the last 40 steps (25 after lap 1) and the total is negative. A safety net that rarely fires with the current weights |
Final score
When the generation ends, a car that finished at least one lap has its score multiplied by record ÷ its best lap. The code clamps this factor between 0.4 and 2.5, but the record already includes this generation's laps, so in practice it lies between 0.4 and 1: the record holder keeps its score and a car twice as slow keeps half. Finishing a lap stops being enough; it has to be fast.
The Events panel shows these rules firing for the leader as it drives: Progress, LAP!, RECORD!, Wall!, Wrong way!.
Why not NEAT-Python or ML-Agents?
NEAT-Python evolves the network's shape as well as its weights, and Unity ML-Agents trains agents with reinforcement learning inside a game engine. Use them for real projects. This one is meant to be read and watched: a fixed 8-14-2 network, four short learning loops side by side, physics and collision in NumPy, all small enough to follow in an afternoon.
Credits
The Interlagos layout (Autódromo José Carlos Pace, São Paulo) comes from OpenStreetMap, © OpenStreetMap contributors, under the ODbL. It is scaled to 1 unit = 20 m and widened so the cars fit.
License
MIT.
探索相关项目
加载中…