KingCobra 深度 Q-learning 自動駕駛車模擬器:支援漂移及倒車
Self-driving cars that learn by deep Q-learning, with drift and reverse, in pure KingCobra
以 KingCobra 編寫的自動駕駛車模擬器,使用 Double DQN 訓練同一個神經網絡操控所有車輛,並支援漂移及倒車。模型在 3 條未見賽道均完成 100% 圈數,訓練約 1.7 分鐘,網絡約有 21,000 個參數。程式只用 KingCobra 標準函式庫,沒有使用 Python 或外部依賴。
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, 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

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.
The result
| 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.
Try it
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.
One network, many drivers
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
- One brain, N bodies. Each car senses its own world (its lidar, its neighbours, its own slip) and gets its own action, but the weights are shared, so everything any car learns helps all of them.
- One batched forward pass per tick. The observations of every running car are stacked and sent through the network together, which is much cheaper than one pass per car. A test checks that the batch gives exactly the per-car answers.
- One replay buffer. Every car's transitions go into the same buffer, so a 4-car pack produces 4× the experience per tick.
- At serving time too. In the dashboard the NPCs and (in AI mode) the ego car use the same network. When you take the wheel, you replace only the ego car's action, and the NPCs keep using the network.

The panel in the dashboard shows this live: one row per car, the observation going in and the action coming out.
What the network sees and does
Observation (22 numbers per car).
- 7 lidar rays to the road edge.
- A 7-sector radar that gives the distance to the nearest other car in each 30° sector. Thin rays would miss a neighbour a few metres to the side.
- Forward speed, sideways speed and yaw rate (so the network can feel a slide), and steering angle.
- Lateral offset, heading error, and the road's curvature 10 m and 25 m ahead.
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.
Car physics: drift and reverse
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:
- Understeer: brake or accelerate hard in a bend and the front tyres run out of grip.
- Drift: the handbrake locks the rear wheels (a small friction budget), the rear lets go, and the car rotates and slides. The dashboard flags it and shows tyre marks and smoke.
- Reverse: the "brake / reverse" pedal brakes while moving forward and, once stopped, drives the car backwards (up to 6 m/s), so the cars can back out of trouble.
- Soft walls: touching the road edge pushes the car back and scrubs speed (a scrape) instead of ending the run. Too many scrapes wreck it.

A human driver in a handbrake drift.
Racer and drifter
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
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.
Training
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
The code layout
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.
Tested like a real project
make test runs 67 KingCobra tests covering:
- track determinism and drivable bends,
- the physics: acceleration, braking distance, reverse, the grip limit, the handbrake breaking the rear loose, and soft walls,
- the multi-car world: collisions, car radar, end conditions and respawn,
- the shared network: a batched pass equals per-car passes, and observation i maps to action i,
- the Double-DQN target against a reference,
- exact save and load round-trips,
- determinism of whole training runs,
- and the real server booted as a child process and driven over HTTP.
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.
Honest limits
- The simulator is 2-D and the roads are procedural loops, with no junctions, traffic rules or pedestrians.
- The racer rarely drifts or reverses on its own, because a racing reward gives it no reason to. Those abilities show up in the drifter and in human drivers.
- The NPCs are the same network as the ego car, not independent policies, so they cooperate by construction.
- The server is single-threaded, and a benchmark request blocks other requests while it runs.
- Training runs on the interpreter, on one CPU core, at about 1,500 transitions per second including learning.
- The results come from one seed, so there are no confidence intervals across seeds.
Where this comes from
This is the same approach as my Snake DQN agent, 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
Get it
- Self-driving car DQN: https://github.com/DivyanshuSinha136/KingCobra-Self-Driving-Car-DQN
- KingCobra: https://github.com/DivyanshuSinha136/KingCobra
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.
來源:DEV Community · dev.to
