Some time ago I implemented a neural network for the classic Chrome dinosaur game. The only thing it learns is when to jump. Simple premise, interesting rabbit hole.
The idea
No frameworks, no libraries for the neural network itself. Just the math from scratch and see if it works. It did, eventually.
I ended up doing three implementations: JavaScript on canvas, C with Raylib and then compiled to WASM to run it on the browser.
The Neural Network
The network has 4 inputs:
- Distance to the next obstacle
- Height of the next obstacle
- Y velocity of the dinosaur
- Is it on the ground?
Not the most optimal set of parameters but good enough to get the job done. Each dinosaur in the population starts jumping randomly and within a few generations they figure it out.
Implementation in JS
The easiest one. Everything runs on an HTML canvas.
Three main pieces: a Neuron with weights, bias, activate, mutate and clone. A NeuralNetwork with predict, mutate and clone. And a Population which is the set of dinosaurs running at the same time.
The rest is just drawing on the canvas.
Implementation in C
I came across Raylib and wanted to try it in C. It is a library normally used for games so it felt like the right fit.
The code is split into a few header files to keep things clean:
nn.h / nn.c— everything related to the neural networkobstacle.h / obstacle.c— obstacle generation and managementmain.c— Raylib integration and core game loop
Could have been done in a single file but this is more readable.
Implementation in WASM
Wanted to put a live demo on GitHub Pages so I compiled the C code to WASM using Emscripten.
The Makefile has a few flags for compiling with ASYNCIFY which meant I did not have to change anything from the original C version to make it run on the web. Raylib has good documentation for this.