Skip to content

Instantly share code, notes, and snippets.

@jcromartie
Last active February 25, 2016 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcromartie/a6c7ecc1402bb29214e9 to your computer and use it in GitHub Desktop.
Save jcromartie/a6c7ecc1402bb29214e9 to your computer and use it in GitHub Desktop.
(defn add-component
[system entity component data]
(-> system
(update-in [:identity entity] (comp set conj) component)
(assoc-in [component entity] data)))
(defn delete-component
[system entity component]
(-> system
(update-in [:identity entity] disj component)
(update-in [component] dissoc entity)))
(defn get-component
[system id component]
(get-in system [component id]))
(defn update-component
[system component f]
(let [component-map (get system component)
component-map' (transient component-map)]
(doseq [map-entry component-map
:let [id (key map-entry)
data (val map-entry)]]
(when-let [result (f id data)]
(assoc! component-map' id result)))
(assoc system component (persistent! component-map'))))
(defn make-mayhem
[n]
(reduce (fn [system id]
(-> system
(add-component id :position [(rand-int 800) (rand-int 600)])
(add-component id :velocity [(- (rand-int 4) 2) (- (rand-int 4) 2)])
(add-component id :visible {:width 32
:height 32
:source-x (* 32 (rand-int 10))
:source-y (* 32 (rand-int 10))
:source-image-name (rand-nth image-files)})))
{}
(range n)))
(defn update-position
[system]
(update-component system :position
(fn [id position]
(when-let [velocity (get-component system id :velocity)]
(vec+ position velocity)))))
(defn update-velocity
[system]
(update-component system :velocity
(fn [_ velocity]
(vec+ velocity [(- (rand) 0.5) (- (rand) 0.5)]))))
(defn update-mayhem
[state input]
(-> state
update-velocity
update-position))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment