Klecs: an Entity Component System in Scheme

I came across the term ‘entity component system’ or ECS sometime during my browsing the internet and wanted to learn more about it. Having read some blog posts I decided to implement a library for this in scheme. ECS is a paradigm for game development that aims to simplify code and decouples elements of game design.

In my implementation, an entity is a list of components and a component has a symbol as name and any scheme value as value (so a component is a simple key-value pair, with a symbol key). The world is the the set of all entities and keeps track of which entities implement which components as well as storing all components for each entity. This world can by queried to get the entities that have certain components (queries on the component values are not possible). The query is implemented as a macro and allows for negation, conjunction and disjunction. So for example:

(query (and (not 'sprite) (or 'position 'velocity)))

would return a function that when applied to a world object returns all entities that have a position and velocity component but no sprite. The last element of ECS, “system” is then a function that applies to all entities matching a query. Systems are simple scheme functions.

When designing this library, I wanted to enable a purely functional style to game programming (an area where typically side-effects are plentiful) and I was surprised how well ECS enables this. So in a typical game loop, after having created a world with entities, one would then apply a set of systems, each being a function that take a world as input and return a modified world.

The library is currently completely un-documented, and only provides 2 example games in the ‘examples/’ folder to showcase its usage. I hope to get around to fixing this. I am very pleased with the library name ‘klecs’ which is German (originally written Klecks or sometimes Klacks) for blot/smudge and also part of the expression “Das war ein Klacks” meaning a task that was easy to achieve.

The library was quite helpful for the game development during my last game jam. In the future, I hope to implement the VGDL (video game description language) atop of this framework to make game development much easier (in fact providing a no-code/low-code environment).