Self-driving car (neuroevolution)

A learning project: a 2D car that learns to drive using a small neural network and a genetic algorithm, written in Python and NumPy.

Learning projectNov '26Python, NumPy, pygameGitHub ↗

What it is

A small learning project. A 2D car learns to drive around a track using a neural network trained with a genetic algorithm. I built it to learn the basics of neural networks and Python, after seeing commonLuke’s video “Can I Make a Better AI Than AI?”.

How it works

The car measures the distance to the edge of the road in 7 directions and knows its own speed. A small neural network (8 inputs, 8 hidden neurons, 2 outputs) turns those into steering and throttle. I wrote the network and the genetic algorithm by hand in NumPy, without ML libraries. The game runs in pygame.

Speed90° left60° left30° leftAhead30° right60° right90° rightSpeedSteerGasInputsHiddenOutputsGasBrake

Training

Each generation, 50 cars drive the training tracks. The best 10 are used to make the next generation: the best one is kept as it is, and the others are mixed and changed slightly at random. Each track has checkpoints that must be passed in order, which is how progress is scored.

There are 25 tracks: 18 for training and 7 kept aside for testing.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25

What I changed along the way

It took four training runs. Each one showed a problem that I then fixed:

RunWhat happenedWhat I changed
1On simple tracks it never learned to brake, so it crashed on a tight hairpin.I added harder tracks.
2It still didn’t brake, because the score rewarded extra laps on the easy tracks.I capped each track at one lap.
3It learned to brake, but stopped in front of obstacles and stayed there. It couldn’t sense its own speed.I added speed as an input, two more rays, partial credit for getting closer to the next checkpoint, and ranked cars by tracks finished first.
4That fixed the stopping.–
Best score per generation in the final training run.

Results

17 of 18 training tracks and 5 of 7 test tracks completed. It still fails on tracks with dead-end side roads, because to its rays a dead end looks like normal road. Each setting was only run once, so the results aren’t statistically solid.

Training tracks17 of 18 completed

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 8
  8. 10
  9. 13
  10. 15
  11. 16
  12. 17
  13. 47%19
  14. 21
  15. 22
  16. 23
  17. 24
  18. 25

Test tracks5 of 7 completed

  1. 7
  2. 29%9
  3. 11
  4. 12
  5. 14
  6. 18
  7. 71%20

What I learned

The result depended mostly on what the car could sense and what the score rewarded. Most of my fixes were changes to the inputs and the scoring, not to the network itself.

Next

oneclient