This Game of 'Snake' Takes Place Inside its Own Source Code

In this version of Snake, the playing field is the game’s code itself, made with some very creative programming.

This is a companion discussion topic for the original entry at

Real missed opportunity not writing this in Python

(I kid, this is honestly really cool)


That would be a cute pun, but the payoff from writing it in C++ is arguably better. The article elided this bit of trickery from the author’s description:

There are a number of techniques used to make quinesnake as small as possible. Perhaps the most interesting one is that it compiles itself. Making the source file executable and executing it invokes g++ on itself with a number of flags, includes and defines. This works because the first line of the program, /*bin/ls>/dev/null... , is interpreted as a shell command, despite also being a valid C++ comment.

To keep track of the state of the game, and to make the source as confusing to read as possible (which is also important!), quinesnake stores the game state in the spare bits of the source-as-data string used by the quine. The type of this string is std::wstring, a string class for storing wide (>=16 bit, or wchar_t ) characters. Since quinesnake only uses it to store 8-bit ASCII characters, that leaves the rest spare to store the state of the character in the output (empty, snake, or food. 2 bits needed), and the direction of the snake pixel that proceeds this one (up, down, left or right. Also 2 bits needed), if it’s part of the snake. Every other wchar_t in the string contains these 4 bits of game state in the higher order bits above the regular character, so they’re removed by casting the wchar_t down to char when printing.

The author goes on to explain this character encoding hack with some more details. I’m sure it’s possible to do all this in Python too, but I bet the bit fiddling is easier in C++.


Of course, I was just being silly. Thanks for sharing the blogpost though!

I’ve been reading through the commented source code on git and it is a very clever design. The quine version of it goes far over my head, but the tricks at play are neat!