I tore my ACL so I learned GameDev & ECS
My adventures and learnings from building a tiny ecs module.
Michael Yoniles
4484 ⏲ Reading Time:20 Minutes, 22 Seconds
2026-10-18 17:09 -0500
Overcomplicating Flappy Bird: Writing a Tiny ECS in Go
I built a small Entity-Component-System framework in Go on top of Ebitengine so I could make a deliberately overcomplicated Flappy Bird clone. Here’s what I built, what I got wrong, and what I’d do differently.
Why?
Every once in a while, I go down the rabbit hole of watching devlogs on YouTube. These projects often seem like so much fun, partially because I am an Epic Gamer 😎 myself and partially because the problems that game devs have to solve are complex but also intuitive. I’d never have to model fluid dynamics or program particle effects in my day job! So, given that I have been taking time off of work recently due to a surgery, I thought that learning game programming and ECS would be a good use of my time while loopy off of pain medications.
Picking a framework
A little background: I am not entirely a noob.
I grew up making tiny games, first in Scratch (you can bet your bottom dollar that I was the coolest kid on the playground for recreating TRON during computer lab), and later in p5.js, following along with The Coding Train as I learned the ropes of programming in general.
These toy languages are just that: toys.
I knew that if I wanted to solve the problems that I find so interesting about gamedev, I would need a “real” framework.
The conventional wisdom at the time I outgrew p5 was to use either Unity or Unreal Engine. Godot had only just been open-sourced and was nowhere near the public zeitgeist that it is today. Of the two options that were in the public conciousness, Unreal cost money, so that was immediately out as far as College-Freshman-Mike was concerned. So, after I failed to get an internship between freshman and sophomore year, I dedicated myself to building resume projects, one of which was a game in Unity. I was inspired by a lecture on “near-perfect” or “good enough” algorithms, and so the only game I produced was about coloring tripartite graphs. (This is ancient code, so don’t judge me, but I also visualized it in Qt5) As you can tell, even as I grew older, I was still the coolest kid on the playground.
Fast-forward to a week or two ago. I knew that I did not want to pick up Unity again; I always felt like I was learning Unity more than I was learning games programming. That is also why I stayed away from Godot. Although it shows so much promise as not just a good open-source game engine but as a great game engine, period, I wanted more transferable skills. I had also been around gamedev circles long enough to have heard about ECS, and even though this would be my first real game, I thought that learning ECS would be a good secondary goal. That led me to look for a framework rather than an engine, specifically one that either natively supports ECS or lets me implement it myself.
I liked the idea of using Kotlin or even my beloved Java with libGDX, but the tooling immediately turned me off (I accidentally deleted my project folder using gdx-liftoff), and it’s a pain in the keister to compile to WASM or give demos to other people. Bevy immediately caught my eye. Not only have I been wanting to learn Rust for a long time, but it is a battle-tested ECS engine. I backed away from it, however, because learning game dev, Rust, and ECS all at once felt like too much on my plate, especially while I am bedridden, in pain post-surgery, and/or loopy off of the pain medication.
To retain my sanity and enjoyment of programming, I decided to implement a little ECS framework in Go using Ebitengine (Eh-bee-ten-jin). I kinda know Go. Like, I’ve written a few command-line applications in Go for my day job, but it’s such a simple and effective little language that I feel as though I have been able to be good at my job without actually becoming proficient in it. So my goal is simple: learn ECS, learn game dev and sharpen my Go skills along the way.
Reading through the example code for Ebitengine also inspired me on what to build. There is a little one-file example recreation of Flappy Bird. Surely, I will not over-complicate this.
I should also mention that I used AI as part of building this, BUT I used it almost exclusively to ask questions about how other engines solve problems. In fact, as you will see later in the article, I disagreed a lot with how the AI wanted me to implement things. This is partially because we do not share the same taste, and partially because it correctly thought I was over-engineering a Flappy Bird clone.
The rest of this article is a guided tour through the code base, some failed or less-than-ideal implementations, and lessons learned.
I don’t even see the code anymore
What is ECS?
I have been name-dropping ECS a lot so far without actually explaining what it is.
ECS stands for Entity-Component-System, the three main pieces of the architecture.
Entities are things in the game, the nouns.
Components are kinda like adjectives. They describe the capabilities of entities and carry data.
You can think of entities as buckets for components with a name tag.
In Flappy bird for example, the bird component may have a Sprite component to show an image, and a Transform (position) component to describe where it is.
The last architectural piece, systems hold all of the game logic by acting on those components.
A GravitySystem for example may update the bird’s position downward by updating its Transform.
The system itself does not know that the entity in question is the bird though, it just knows that it has been marked to be pulled down.
Serious ECS engines like Bevy or flecs also store each component type contiguously in memory, so systems iterate over tightly packed data and are very cache-friendly.
Mine does not do that.
My goal in building this is not too dissimilar from what I used to do back when I first learned programming: painfully try to write a naive version myself over a weekend and be amazed when I upgrade to a professionally maintained project.
In my laziness genius, I embarked on this project with literally zero knowledge of how an ECS engine optimized for performance, I wanted to engineer a solution as I went along.
My thought process was, just like when I first started programming, that I would run into the same problems other engineers ran into, create a naive or primitive solution, and learn a lot in the process.
Foundation: the ECS framework
As a base, I started with a design based off of this blog post from co0p.
That has some unfortunate side effects, but for now, life is super simple:
type ComponentType string
// Every component reports its own type, which is how entities index them
type ComponentTyper interface {
Type() ComponentType
}
type Entity struct {
id string
components map[ComponentType]ComponentTyper
}
type System interface {
Update(w *World)
}
Tying it all together is the World, which holds every entity and system and runs them once per tick:
type World struct {
entities []*Entity
systems map[GameState][]System
queue *EventQueue
handlers map[handlerKey][]EventHandler
// ...plus game state, transitions, and resources, which I'll get to later
}
// Query returns every entity that has a component of type c
func (w World) Query(c ComponentType) []*Entity {...}
func (w *World) Update() {
w.updateSystems() // run every system registered for the current state
w.processEvents() // drain the event queue, calling any registered handlers
w.transition() // switch game states if something asked to
w.cleanup() // actually delete the entities removed this tick
}
Query is a linear scan over every entity 👀, every frame 👀, often ran multiple times per-system 👀.
I warned you when I said that this was a naive approach, I would certainly feel a performance hit if the game had more than 5 entities on screen at any given time.
I also used the GetComponent method described in that article.
Because I used this November 2021 article as a starting point, I missed the opportunity to use generics, released in 2022.
So I originally fetched all of my components with a type assertion like this:
t := e.GetComponent(component.TransformType).(*component.Transform)
Even with the helper function HasComponent(ct ComponentType), this is unwieldy to use, and if I pair the wrong ComponentType with the wrong struct, the type assertion panics at runtime.
Now, what did Senior Engineer Claude (who was told not to make mistakes) offer as a solution?
Reflection. Something along these lines, where components are keyed by their Go type instead of by a string I picked:
components map[reflect.Type]ComponentTyper
func Get[T ComponentTyper](e *Entity) (T, bool) {
c, ok := e.components[reflect.TypeFor[T]()]
...
}
I, of course, have strong opinions about reflection, so I knew that I couldn’t take this advice.
Although, if I am being honest with myself, this seems like a reasonable time to use it.
My entire contention against reflection is that it can move compile-time errors to runtime, or make your program’s output dependent on internal code structure.
Neither of those issues would arise here; in fact, keying by reflect.Type would remove a class of runtime errors, since two components could no longer accidentally share a ComponentType string.
Nonetheless, I am a man of principle and so decided to use generics to save me:
func Get[T ComponentTyper](e *Entity) (T, bool) {
var zero T
c, ok := e.components[zero.Type()]
if !ok {
return zero, false
}
return c.(T), true
}
Which turns that earlier line into:
t, ok := ecs.Get[*component.Transform](e)
This is totally fine; there’s no reflection. There is some type-system tomfoolery though.
Every component is stored as a pointer, so T is something like *component.Transform, and zero is a nil pointer.
Calling zero.Type() on a nil pointer works only because every Type() method has a pointer receiver and just returns a constant without dereferencing anything.
The upside is that nothing gets allocated, and if I forget the * and write ecs.Get[component.Transform], the compiler rejects it, because only the pointer type implements ComponentTyper.
Yes, I can still mess up by accidentally reusing a ComponentType string, but I get to sleep at night knowing that I did not succumb to reflection at first blush.
It’s the Catalina Wine Mixer: collisions and events
From there, I was able to whip up some components and systems blazingly fast.
I started with Sprite, Transform, and Velocity components and painted them onto my canvas.
I had neither movement nor collisions, but I was feeling great about my progress.
It’s when I went to write the CollisionSystem that I came across an issue that made be abandon the pure-ecs approach.
Remember when I said there are maybe five entities on screen?
Well the bird does something different when colliding for all five of those entities.
When a bird hits a pipe or the floor its game over, when it hits the ceiling, I expect it to be bounced down without losing the game,
and finally if it passed through the middle section of a pipe, the bird scores a point.
And that’s just the bird. I also need to account for a pipe not colliding with the floor or ceiling.
When I was just getting things working, I put all four reactions directly into the CollisionSystem, which meant that one system knew every rule in the game.
Very clearly this is not single-responsibility and not sustainable.
The other extreme would be a shared isColliding helper called from four separate systems.
But then there is no collision system at all, just four systems re-checking the same pairs of entities every frame.
In a more traditional, puritanical ECS library, this would be handled with components.
For example, the collision system could attach a colliding component to the bird entity holding a pointer or reference to the pipe entity it hit.
Separate systems then query for that component and react to it, and the collision components are cleaned up before the next frame.
Instead, I added a second e to ECS and made an event queue.
This is an unorthodox but not unprecedented approach to message passing between systems.
Bevy actually has both: buffered messages that systems read each frame, and events that immediately trigger observers.
What I ended up with isn’t a pure pub/sub pattern, rather its most-naive approach.
Systems Emit events into the queue, handlers subscribe to an EventType, and once per tick the world drains the queue and calls every subscribed handler.
Handlers can emit events too, and those get handled in the same tick.
If I ever return to this, I would like to create actual topics or message brokers to handle unique message bodies.
(My method, ofc, is the primordial-soup version of pub/sub, but its not the real deal)
type EventType string
type Event struct {
Subject *Entity
Object *Entity
Verb EventType
}
type EventHandler func(w *World, e Event)
func (w *World) Emit(event Event) {
w.queue.Enqueue(event)
}
// OnEvent registers h to run whenever an event of type e is processed
func (w *World) OnEvent(e EventType, h EventHandler) {...}
func (w *World) processEvents() {
for {
event, ok := w.queue.Dequeue()
if !ok {
break
}
for _, handler := range w.handlers[handlerKey{State: AnyState, Event: event.Verb}] {
handler(w, event)
}
for _, handler := range w.handlers[handlerKey{State: w.state, Event: event.Verb}] {
handler(w, event)
}
}
}
(Ignore the State part of handlerKey for now. It’ll make sense once we get to game states.)
Like I said, I don’t love this. Every event is forced to have the same shape. If I were building a bigger, more complex game, I would probably want to use generics so that any struct can go in the queue and carry metadata about the event. Although events are more versatile and natural (imo) for a simple game like this, the lack of types actually makes them less flexible than the stricter pure-ECS method that I described above. Updating this system is an exercise for a later date. For now, I don’t need to communicate complex information, so a simple sentence (in Subject-Object-Verb order, for some reason) can describe what happened.
That makes my collision system look like this:
func (c CollisionSystem) Update(w *ecs.World) {
entities := w.Query(component.ColliderType)
for i, e := range entities {
// start at i+1 so each pair is checked once and never against itself
for _, other := range entities[i+1:] {
if isColliding(e, other) {
event := ecs.Event{
Subject: e,
Object: other,
Verb: CollisionEvent,
}
w.Emit(event)
}
}
}
}
// isColliding checks the collision layer, and then sees if they collide
// given their transform and collision box
func isColliding(e1 *ecs.Entity, e2 *ecs.Entity) bool {...}
Each Collider has a Layer and a Mask bitmask, so the bird collides with pipes, but pipes never bother colliding with each other.
On the Sub side of this pattern, three different handlers subscribe to a CollisionEvent.
w.OnEvent(system.CollisionEvent, system.HandleCoinScored)
w.OnEvent(system.CollisionEvent, system.HandleBounce)
w.OnEvent(system.CollisionEvent, system.HandlePoison)
Since the event only says “something hit something,” the handlers have to figure out the details on their own.
For example, anything that ends the game on contact (the pipes and the floor) has an empty Poisoner marker component, and the bird has a Poisonee component.
To find out if the bird hit something deadly, I cannot check for the sentence “bird hit pipe” in my event queue; the bird can be either the subject or the object.
Instead, I have to check both possible orderings:
func HandlePoison(w *ecs.World, event ecs.Event) {
if hasPoisoned(event.Subject, event.Object) {
w.Emit(ecs.Event{
Verb: GameLossEvent,
})
}
}
func hasPoisoned(e, other *ecs.Entity) bool {
if e.HasComponent(component.PoisoneeType) && other.HasComponent(component.PoisonerType) {
return true
}
if e.HasComponent(component.PoisonerType) && other.HasComponent(component.PoisoneeType) {
return true
}
return false
}
Notice that HandlePoison doesn’t end the game itself.
The event queue will burn through all events emited that tick so we jsut throw another event on the queue.
A different handler who only has the job of ending the game handles that. I know that we only have on lose-condition in this game but it feels single-responsibility-y.
Cross-entity concerns: the scoreboard
I mentioned earlier that I used Claude to ask about implementations. I wish that I had specified that I was trying to get a feel for writing and working with an ECS system, because twice it nudged me toward the simplest solution rather than the most resilient one.
The first time was the scoreboard, which is a cross-entity concern: one entity (the bird) earns the points, but a different entity (the score text at the top of the screen) has to display them.
Claude’s suggestion was to skip all of that and make score a World-level attribute that got updated after a CollisionEvent between a coin and the bird.
This sounds reasonable but flies completely in the face of what ECS is supposed to get you.
My little ECS library would now be prescribing that the World cares about some score, specifically a single int32.
What if I wanted to use this module to make a multi-player game?
What if a game made with my little library wanted its score to be represented in a more complex way, like {GoodEnding: false, Coins: 100, Morality: 0.5}?
Of course, an int32 is actually overkill for Flappy Bird, but the problem is that I was now mixing game logic into the framework itself.
In the current iteration of the game, the bird has a Scorer component that tracks its points, and a separate scoreboard entity has a Scoreboard marker component and a Text component.
The invisible coin between the pipes is an entity with a Consumable component.
When a Scorer collides with a Consumable, HandleCoinScored increments the score, removes the coin, and emits a ScoreUpEvent with the scorer as its subject.
This handler then picks that up and updates the scoreboard’s Text:
func HandleUpdateScoreboard(w *ecs.World, event ecs.Event) {
scoreBoards := w.Query(component.ScorerBoardType)
scorer := event.Subject
scoreComp, ok := ecs.Get[*component.Scorer](scorer)
if !ok {
log.Panicf("Entity %s has no Scorer", scorer.Id())
}
newScore := scoreComp.Score()
if len(scoreBoards) == 0 {
log.Panic("There should be at least one scoreboard")
}
sb := scoreBoards[0]
txt, ok := ecs.Get[*component.Text](sb)
if !ok {
log.Panicf("Scoreboard %s has no Text", sb.Id())
}
txt.Text = fmt.Sprintf("Score:\n%d", newScore)
}
(ScorerBoardType is the ComponentType of the Scoreboard component. Naming things is hard.)
Set the scene: game states
The second time Claude led me astray was suggesting a simple world.Lost() function to determine when the game was over.
This worked initially as a quick way to iterate on and validate the main gameplay loop, but, just like the score, it forces every game built on the module to care about a win/loss state.
Instead, the world has a generic GameState (just a string), along with w.State() and w.SetNextState().
Systems and handlers can call SetNextState() at any point during a tick, but the switch only happens after all of that tick’s events have been processed.
When it does, the world runs any Transitioners registered for that pair of states:
type GameState string
type Transitioner interface {
Transition(w *World)
}
type transition struct {
To GameState
From GameState
}
func (w *World) AddTransitioner(from, to GameState, t Transitioner) {
tr := transition{From: from, To: to}
w.transitioners[tr] = append(w.transitioners[tr], t)
}
The game itself defines four states: Title, Play, Pause, and End.
Instead of setting w.lost = true, Losing the game is internally set by setting w.nextState to End.
It is up to any related Transitioner to handle that move from Play to End
As an example of a transition, let’s look at how the game starts.
The game creates its world with ecs.NewWord(state.Title), which queues up Title as the next state.
The world starts out with no state at all, so on the very first tick it transitions into Title and runs this transitioner:
func (t *TitleTransition) Transition(w *ecs.World) {
windowConf := config.GetWindowConfig()
textConf := config.TitleTextConfig()
centerX := windowConf.LogicalWidth/2
// Header
titleText := ecs.NewEntity("Title")
titleText.AddComponent(&component.Text{
Text: "Overcomplicated\nFlappy Bird",
FontSize: textConf.FontSize,
Color: textConf.Color,
})
titleText.AddComponent(&component.Transform{X: centerX, Y: 200})
titleText.AddComponent(&component.StateScoped{Active: state.Title})
w.AddEntity(titleText)
// How to start
help := ecs.NewEntity("HelpText")
textConf = config.HelperTextConfig()
help.AddComponent(&component.Text{
Text: "Press Space to start",
FontSize: textConf.FontSize,
Color: textConf.Color,
})
help.AddComponent(&component.Transform{X: centerX, Y: windowConf.LogicalHeight - 100})
help.AddComponent(&component.StateScoped{Active: state.Title})
w.AddEntity(help)
}
Cleaning up after a scene
Notice the StateScoped component on both entities. That makes the components get cleaned up in any state that isn’t their Active state.
A CleanupSystem runs in every state and flags any state-scoped entity that doesn’t belong:
entities = w.Query(component.StateScopedType)
for _, e := range entities {
scope, ok := ecs.Get[*component.StateScoped](e)
if !ok {
continue
}
if w.State() != scope.Active {
event := ecs.Event{Subject: e, Verb: DestroyEvent}
w.Emit(event)
}
}
So when the player starts the game, the title text cleans itself up on the next tick.
Because I am working with fairly simple scenes and states, transitioning to the Pause state can work the same way, and I can discard entities for the pause screen after resuming the game.
In an earlier rendition, before StateScoped existed, a Transitioner had two functions, OnEnter and OnLeave, which acted as a constructor and destructor for a scene.
For example, pause.OnEnter() would create the entities to dim the screen, and pause.OnLeave() would clean them up.
I threw this idea away because every state needed a Transitioner just to clean up after itself, and the play transitioner ended up responsible for entering from title and end and for both entering and leaving pause. That’s too many responsibilities for a single type.
Transitions from any state
This works great for our simple game, but let’s put our ECS Module Designer hat back on.
What if a dev wants a transition to run when going from any state to state A?
If a dev wants to, say, change the music for the pause screen, do they have to register the same transitioner from states B, C, and D?
The answer is a special ecs.AnyState value that can stand in for the From state.
When switching from A to B, the world does two lookups in its table: first the transitioners registered for A -> B, and then the ones registered for AnyState -> B.
That way, a dev can register a PlayPauseMusic transitioner once, and it plays regardless of whether the player enters pause from play, inventory, or anywhere else.
This is technically how the Title transitioner is written. Because there is no initial state, the exmaple above is registered to transition from AnyState -> Title.
I haven’t needed the reverse yet (something that runs whenever we leave B), but it would just be a third lookup for B -> AnyState.
Systems and handlers per state
One final caveat, now that we have the concept of GameState, is that we don’t want all of our systems running all the time.
For example, if the GravitySystem kept running while paused, the bird would silently accelerate while the player was looking at the pause menu and would be moving at terminal velocity when they resumed play.
We could either deregister and re-register systems as we transition between states, or we could register each system for only the states that care about it.
I chose the latter because I could definitely see myself forgetting to add/clean up a system or two when entering/leaving a state.
I also think it’s easier to reason about when I declare, ahead of time, exactly which systems run in which states.
This ends up taking the form of:
// AddSystem is the same as AddSystemIn(AnyState, sys)
func (w *World) AddSystem(s ...System) {
w.AddSystemIn(AnyState, s...)
}
func (w *World) AddSystemIn(g GameState, s ...System) {
w.systems[g] = append(w.systems[g], s...)
}
Each tick, the world runs the AnyState systems and then the systems for the current state:
w.AddSystem(system.FlapSystem{})
w.AddSystem(system.CleanupSystem{})
w.AddSystemIn(state.Play, system.GravitySystem{})
w.AddSystemIn(state.Play, system.MovementSystem{})
w.AddSystemIn(state.Play, system.CollisionSystem{})
That’s also what the State in handlerKey was for earlier because I scoped EventHandlers in the same way.
Its a kinda-hacky way to handle input. I register a keypress as an event so a FlapEvent is registered to multiple state-specific input systems.
w.OnEventIn(state.Title, system.FlapEvent, system.HandleStart)
w.OnEventIn(state.End, system.FlapEvent, system.HandleStart)
w.OnEventIn(state.Play, system.FlapEvent, system.HandleFlap)
Working with Ebitengine
I have to say, this is a really fun and refreshingly minimal library. It abstracted away all of the things that I needed it to, such as image rendering, input, etc. I just had to glue together a three-method interface to get this working.
func (g *Game) Update() error {
in := poll()
g.World.SetResource(&in)
g.World.Update()
return nil
}
func (g *Game) Draw(screen *ebiten.Image) {
screen.Fill(color.RGBA{63, 63, 225, 50})
render.RenderWorld(g.World, screen)
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
cfg := config.GetWindowConfig()
return cfg.LogicalWidth, cfg.LogicalHeight
}
Ebitengine calls Update at a fixed 60 ticks per second and calls Draw once per rendered frame, which is not necessarily the same rate.
In an interest to keep my game logic separate from engine logic, and the face that update != draw, rendering is not an ecs system in the world.
RenderWorld walks through all of the entities in world and renders any that have a Text or Sprite component.
Input gets polled once per tick and stored as a resource, a world-wide singleton keyed by type, which systems like FlapSystem read to decide whether to emit a FlapEvent.
If that sounds like the world-level score I complained about earlier, the difference is that the framework only provides a generic slot.
Its different because thats why.
The real reason is because the ecs module does not persribe what the resource has to be or if the game has to have resources at all.
I recommend Ebitengine for anybody who wants to be a little more hands-on with their game programming but does not actually want to get into the weeds that badly.
Lessons learned
Now, remember, the initial inspiration for this project was a ONE-FILE Flappy Bird demo. I have so many files and systems and haven’t even touched adding sound, but I still feel as though I learned so much. If I did it again and/or wanted to put more time into this game:
- Start with generics
- Let the LLM know that I am overcomplicating things.
- It was right to tell me not to write a state machine for flappy bird. I do not fault it for that. It simply didn’t know that I was trying to learn and get a feel for ECS.
- Give events types
- It works for Flappy Bird but complex games should be able to share complex data types, or have dedicated topics.
- If I ever return, I am optimizing the heck out of this.
- I proudy made the simplest design. Now I need to pump up those entity numbers. I want to have 10000 entities all simulating hunger, wounds, dreams, etc.
The game itself
ENOUGH YAPPIN. Here is the source code. Here it is, my overcomplicated Flappy Bird clone: