# Self-driving cars that learn by deep Q-learning, with drift and reverse, in pure KingCobra

> Source: <https://dev.to/divyanshusinha136/self-driving-cars-that-learn-by-deep-q-learning-with-drift-and-reverse-in-pure-kingcobra-25j3>
> Published: 2026-11-24 06:36:27+00:00

**Recommendation:** Share one network's weights across many identical agents and feed each its own observation, as this simulator did to train all cars with a single Double DQN.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

I built a self-driving-car simulator where **every car on the road is driven by the same neural network**, trained with Double DQN. The cars have a proper dynamic tyre model, so they can understeer, **drift with a handbrake** and **drive in reverse**. Everything is written in [KingCobra](https://github.com/DivyanshuSinha136/KingCobra), my programming language, using only its standard library (`std.nn`, `std.http`, `std.json` and `std.system`). There is no Python and there are no external dependencies.

Repo: [https://github.com/DivyanshuSinha136/KingCobra-Self-Driving-Car-DQN](https://github.com/DivyanshuSinha136/KingCobra-Self-Driving-Car-DQN)

*The dashboard, captured from the real app: the AI and four NPC cars on a track the network never saw, all driven by one network.*

| **Laps** | **100 %** completed on 3 tracks the network never saw, at about 14 m/s, with no wrecks | 
| **Training** | 1.7 minutes on one CPU core, for a network of about 21,000 parameters | 
| **Agent** | one shared Double DQN, 3-step returns, Huber loss, gradient clipping, soft target updates, 12 actions (steering × pedal) | 
| **Physics** | dynamic bicycle model, tyre friction circle, handbrake drift, reverse gear, soft walls, car-to-car collisions | 
| **Reproducible** | one seed controls everything, and two runs with the same seed give bit-identical models | 

*47 seconds recorded from the real dashboard: AI traffic on an unseen track, the chase camera, the drifter model, a human adding a handbrake drift and reversing, then the AI taking back over.*

You need KingCobra 1.0 (`kingcobra` on your `PATH`), and `node` only for the front-end tests.

```
git clone https://github.com/DivyanshuSinha136/KingCobra-Self-Driving-Car-DQN
cd KingCobra-Self-Driving-Car-DQN

make serve    # open http://127.0.0.1:8766, two pre-trained models are included
make eval     # laps on seen and unseen tracks, with traffic
make train    # retrain from scratch (about 2 minutes on one CPU core)
make test     # 67 KingCobra tests plus front-end tests
```

No `make`? Every target is one command: `kingcobra run src/main.kc <command> [options]`, with the commands `train`, `eval`, `serve` and `info`.

This is **parameter sharing**, the standard way to train many identical agents:

```
                    Shared KingCobra NN      (one set of weights)
                           |
                           +--- Observation 01 -> Action 01      car 1
                           +--- Observation 02 -> Action 02      car 2
                           +--- Observation 03 -> Action 03      car 3
                           +--- Observation N  -> Action N       car N
```

*The panel in the dashboard shows this live: one row per car, the observation going in and the action coming out.*

**Observation (22 numbers per car).**

**Actions (12).** Steering {left, straight, right} × pedal {gas, coast, brake/reverse, handbrake}. Steering is rate-limited, so a car can't snap between full locks.

**Reward.** Progress along the centre line, a small time cost so speed matters, a small lateral-offset cost, penalties for wall scrapes (−0.4) and car contacts (−1), a +20 bonus for finishing a lap, and an optional drift bonus. A run ends on a lap, on being stuck, going the wrong way, wrecking (14 scrapes) or a time limit.

Each car is a **dynamic bicycle model**, with mass, inertia, two axles and four 25 ms sub-steps per 0.1 s tick, not a point on rails. Tyre lateral force is linear in the slip angle until it saturates at `μ·load`, and it shares that grip budget with the longitudinal force (a friction circle). That gives the behaviour you'd expect from a real car:

*A human driver in a handbrake drift.*

Two networks ship, trained with the same code. Only the reward differs (`reward.drift`):

|  | `driver_ddqn` (racing) | `drifter_ddqn` (drift) | rule-based driver | 
|---|---|---|---|
| laps completed, unseen tracks | **100 %** | **100 %** | 92 % | 
| laps completed, training tracks | **100 %** | 98 % | 88 % | 
| mean speed, unseen tracks | 13.9 m/s | 7.5 m/s | 13.2 m/s | 
| mean lap time, unseen tracks | **28.4 s** | 52.9 s | 29.9 s | 
| time spent drifting | 0.4 % | **53.7 %** | 2.2 % | 
| car contacts per run (unseen) | **0.00** | **0.00** | 1.11 | 
| wall scrapes per run (unseen) | **0.4** | 0.3 | 1.2 | 

The numbers come from `make eval` (3 start positions per track, 4 cars on the road). The rule-based driver is blind to the handbrake and reverse. An honest reading: the racer is the fastest *and* the most reliable. The drifter is a style model that trades a lot of speed for sliding. It learns to drift because the bonus pays, so treat it as a demonstration, not as a better driver.

*The drifter model sliding through a bend.*

The dashboard is a dependency-free front-end served by KingCobra's own `std.http`. You can drive the cyan car yourself: `↑`/` W` gas, `↓`/` S` brake and then reverse, `←` `→` or `A` `D` to steer, and `Space` for the handbrake. Pressing a driving key takes the wheel. Other keys: `Space` play/pause, `N` step, `R` reset, `M` AI/You, `C` camera, `[` and `]` for speed.

*The chase camera, with the ego car's lidar (cyan, amber or red by distance) and the NPCs.*

*What the network wants: Q(s, a) for all 12 actions.*

*Telemetry: speed, slip angle, yaw rate, scrapes, contacts and drift time.*

*The built-in benchmark races the network against the rule-based driver on the same roads and starts.*

It also works on a phone.

An *episode* is a pack of 4 cars driving together on a random training track from random start positions. The **checkpoint is chosen on separate validation tracks**, and the final numbers are measured on **test tracks that were never used for training or for any decision**. That separation matters, because it means the 100 % figure is not about tracks the agent memorised.

*Training curves over 90 episodes.*

Every tunable lives in `config/default.json` and is documented in `docs/TRAINING.md`. Unknown keys and nonsensical values are rejected with a clear message. For example:

```
kingcobra run src/main.kc eval --starts 3                  # the AI, 3 start positions per track
kingcobra run src/main.kc eval --baseline --starts 3       # the hand-written driver, same roads
kingcobra run src/main.kc train --name drifter_ddqn --set reward.drift=0.4 --set train.select=last
kingcobra run src/main.kc train --set sim.cars=6 --set sim.spacing=15 --episodes 120   # busier traffic
src/
  main.kc        CLI (train · eval · serve · info)
  config.kc      defaults, JSON overlay, --set overrides, validation
  track.kc       procedural roads + occupancy grid for fast lidar
  car.kc         dynamic car: tyres, drift, reverse, soft walls, road lidar
  world.kc       several cars: collisions, car radar, rewards, respawn
  features.kc    the 22-number observation of one car
  replay.kc      one circular buffer for all cars (optional prioritised sampling)
  agent.kc       the shared Double DQN: batched inference, vectorised learning step
  trainer.kc     training loop, evaluation on seen / unseen tracks, checkpointing
  baseline.kc    the hand-written driver to compare against
  server.kc      routing, sessions, models, security headers, static assets
  util.kc        RNG, statistics, helpers
web/             index.html · style.css · app.js
config/          default.json
models/          pre-trained driver_ddqn and drifter_ddqn (+ model cards and curves)
```

The server has a small JSON API (`/api/state`, `/api/reset`, `/api/ai-step`, `/api/drive`, `/api/models`, `/api/model`, `/api/metrics`, `/api/tracks`, `/api/track`, `/api/benchmark` and `/api/health`). Games are per session, and each session has its own cars and chosen model.

`make test` runs **67 KingCobra tests** covering:

There are also unit tests for the front-end's pure functions, and a smoke test that runs the real `app.js` against a live server with a stub DOM.

This is the same approach as my [Snake DQN agent](https://dev.to/divyanshusinha136/a-double-dqn-agent-that-plays-snake-written-entirely-in-kingcobra-493h), pushed further: continuous physics, several agents sharing one network and a harder evaluation protocol. The background on DQN and Double DQN is in my `std.nn` guide: [https://github.com/DivyanshuSinha136/KingCobra/blob/main/tutorial/KingCobra_std_nn_Complete_Guide_Expanded.pdf](https://github.com/DivyanshuSinha136/KingCobra/blob/main/tutorial/KingCobra_std_nn_Complete_Guide_Expanded.pdf)

MIT licensed. If you retrain it with other settings, or add a feature like junctions or traffic lights, tell me and I'll link it. A star helps other people find it.
