A simple and pure win32 Snake game, without any compressor trickery, just under 2,953 bytes!
The original source code was taken from MattKC's "Can you fit a whole game into a QR code?" video. If you haven't watched the video prior, watch it here for context and what not.
- No crinker/compressor is used. Just pure C and compiler shenanigans.
- A few visual and gameplay fixes to make it much closer to the HTML version that was shown in the video.
- You can pause the game now by pressing the enter key instead of the pause or 'P' key.
- You can retry the game by pressing the 'R' key.
To see the differences between the original and this version first-hand, it's best to view the original file and see what's different from a programming perspective. Regardless, here is a list of the main changes between the two:
- The input system has been reworked to utilize only 2 variables instead of using an array of valid/invalid inputs. This rework reduces quite a considerable amount of taken up space inside the executable, as the game now does less interanally for the same result.
- The food starts at a constant position instead of calling the
rand
function at startup. - All integers are
size_t
. - A custom
rand
is implemented instead of relying on the C standard version. - Code to change the snake's color depending on the game state (playing/won/lost) has been reworked to be completely branchless.
WM_TIMER
'swhile
loop has been converted to a singleif
statement.- Removed the
bool moved
variable inWM_TIMER
and usedgoto
instead. - Removed the
else
statement atif (snake_len == MAX_TILE_COUNT)
. - Removed
GetModuleHandleA
andAdjustWindowRect
. - The app now uses allocates memory into the stack instead of the heap to allocate
snake_pos
. - Removed
if (msg.message == WM_QUIT)
in the main loop. - Removed
TranslateMessage
in the main loop.
- The original
snake.c
leaked memory by continuously not doingDeleteObject
when callingCreateSolidBrush
. It's even stated in the official Win32 documentation that you should useDeleteObject
once you're done with the brush. This bug fix does come with a caveat, that being it takes up a bit of space in the executable for it to be implemented.
- The apple is now green.
- You can now retry the game at anytime by pressing 'R'.
- The game's performance has been improved (less branching,
PosEqual
does one check instead of 2, etc). - The pause button has been changed from
VK_PAUSE
andP
toVK_ENTER
. - Regular
WNDCLASSA
andCreateWindowA
are used instead of the expanded versions. - The game doesn't overallocate
dir_queue
like it did in the original.
NOTE: cl.exe
is assumed to be x86, not x64! Compiling it in 64-bit will considerably increase the size of the binary.
Just copy the terminal commands from Makefile
and paste them into the terminal.
This requires downloading msvc
from msvc-wine. After that, just run make
and you'll get correct binaries.
Once you compiled snake.exe
, on Unix you can run make qrcode
to generate code.png
.