Programming, game design, and faith

Entity-Component-System architecture

Recently I have been learning about the Entity-Component-System architecture for video game programming. I think it will help out with my “World’s Tiniest RTS” game. I learned about it here, in Robert Nystrom’s Game Programming Patterns. I also heard on the Exploding Rabbit podcast how Jay Pavlina (of Super Mario Bros. Crossover fame) uses the pattern. Here is my Clojure code for it, currently:

(defn create-game []
  {:entities {}})

(defn create-entity []
  [(java.util.UUID/randomUUID)
   {}])

(defn add-entity [game entity]
  (update-in game [:entities] conj entity))

(defn add-component [game entity com data]
  (assoc-in game [:entities (first entity) com] data))

;;example
(let [e1 (create-entity)]
  (->
    (create-game)
    (add-entity e1)
    (add-component e1 :position [3 4])
    (add-component e1 :name "ball")))

Next

Switching strategies

1 Comment

  1. This is not quite right. A better way to do it is to make the game a map of maps. The keys are the component types. Each value is a map of component values, keyed on the entity ID. The example code is the same, but the defn’s work a little differently. An entity is just a UUID, and the game map is accessed through component type and entity ID, instead of entity ID and then component type.

Leave a Reply

Your email address will not be published. Required fields are marked *

Powered by WordPress & Theme by Anders Norén