Chapter I of series of tutorials on how to build a game from scratch with TypeScript and native browser APIs

Image for post

Welcome to the first article in the series “Gamedev Patterns and Algorithms in Action with TypeScript”! We start our journey with one of the most widely used patterns: Entity Component System.


Table of Contents:

  1. What is ECS?
  2. Implementing Component
  3. Implementing Entity
  4. Testing
  5. Conclusion

What is ECS?

It’s one of the architectural patterns that allows us to combine and composite elements of the codebase without creating strong hierarchical interconnections. In a gist, it enables attaching/detaching functionality to elements of the system in a runtime.

Ok, but what does it mean, exactly? Consider the RPG game where the player can cast magic spells. Different ways of playing available depending on what character class Player chooses. For example, Mage can cast spells, and Paladin can slaughter enemies with the heavy sword. From a technical perspective, all these behaviors can be attached to the player when they choose the class. Even more, this can happen in real-time: when a player reached a new level, new behaviors can become available to them.

Image for post

In this example, the player is an Entity, while the abilities to cast the spell or fight with the sword are Components. We can assign different components to an entity to provide new functionality without changing the code of it.

An Entity can be anything: Player, grid, scene, bullets, even game itself. ECS does not apply any restrictions on the functionality of the Entity. There is only one rule: an Entity has to be able to handle Components.

A component can be anything as well as long as it can be attached to an Entity. Some components can be required by an Entity, which means: Entity cannot really exist without it.

In our game, we will have quite a few Entities and Components. One example is the Ship, which can flight, attack, take damage, etc.


Implementing Component

First, we should take a look at our project. The source code is located at the GitHub. Switch to the init branch and you should see a completely set up but empty project.

Take a look at the srcfolder. All it has is an empty main.ts file and a dummy test in main.spec.ts. Let’s killmain.spec.ts since we don’t need it anymore.

Image for post

In this post, we are creating helpers that put in place the Entity Component System. We are going to use ECS in later chapters for building game elements: Ships, Player, Grid, and Nodes.

These helpers, however, don’t depend on the game itself and can be potentially reused in other games. Let’s start by dedicating a folder that will hold all helpers like that in this project. I’ll call it utils.

#algorithms #typescript #design-patterns #javascript #gamedev #algorithms

Gamedev Patterns and Algorithms in Action with TypeScript.
1.85 GEEK