c# Snake in the browser

yowl yowlxx
2 min readMar 23, 2020

--

Following on from https://medium.com/@MStrehovsky/building-a-self-contained-game-in-c-under-8-kilobytes-74c3cf60ea04 , would it be possible to do the same in the browser using WebAssembly (Wasm)?

Just want the answer? WasmSnake

In the above article Michal uses the CoreRT compiler to create a single executable of the snake game using C# and a minimal runtime. CoreRT has an experimental Wasm back end built on LLVM and emscripten so it’s possible to take the same code and create a Wasm version. Where the Windows version calls out to the system’s API for things like console writing and keyboard reading, in Wasm those calls can be replaced either with emscripten API calls, e.g. for Thread.Sleep, or javascript for keyboard reading and display. The Windows version uses the Console as its display, for Wasm we use an HTML table with fixed space font.

How big is it? I’ve tried not to cheat and only use javascript for the equivalent Windows calls. To build the LLVM (that CoreRT produces with the wasm target) and the Wasm, we use

For the runtime:

emcc MiniRuntime.wasm.c -c -o MiniRuntime.bc -s WASM=1 -Os

C# compilation:

csc.exe /debug /O /noconfig /nostdlib /runtimemetadataversion:v4.0.30319 MiniRuntime.cs MiniBCL.cs Game\FrameBuffer.cs Game\Random.cs Game\Game.cs Game\Snake.cs Pal\Thread.Wasm.cs Pal\Environment.Wasm.cs Pal\Console.Wasm.cs Pal\Console.cs /out:zerosnake.ilexe /langversion:latest /unsafe

LLVM compilation:

ilc — targetarch=wasm zerosnake.ilexe -o zerosnake.bc — systemmodule:zerosnake — Os -g

Wasm compilation using emscripten/llvm

emcc.bat “zerosnake.bc” -o “zerosnake.html” -s WASM=1 — emrun MiniRuntime.bc -s ASYNCIFY=1 — js-library pal\console.js — shell-file pal\shell_minimal.html -Os — llvm-lto 2

We are using -Os and — llvm-lto 2 as the obvious options to reduce size and the Wasm comes in at 13KB. (There’s a bunch of emscripten javascript that comes as standard when building with — emrun, no doubt a fair chunk of that could be deleted e.g. the WebGL stuff)

Browser running c# Wasm snake

Code at github

--

--