Skip to content

Instantly share code, notes, and snippets.

@raspasov
Created March 31, 2016 11:12
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 raspasov/e894a0c6c26e5814d752b3fc9075c601 to your computer and use it in GitHub Desktop.
Save raspasov/e894a0c6c26e5814d752b3fc9075c601 to your computer and use it in GitHub Desktop.
ClojureScript + core.async + Om + animation-cljs = WIN!
(defn no-bugs [{:keys [] :as data} owner {:keys []}]
(reify
om/IInitState
(init-state [_]
{:comm-ch (chan)
:obstacle {:x 50 :width 50 :height 50}
:animated {:x 10}})
om/IDidMount
(did-mount [_]
(let [{:keys [comm-ch]} (om/get-state owner)
anim (a/init-animated-value owner [:animated :x])
_ (util/add-document-event-listener
:keydown
(fn [e]
(let [kc (.-keyCode e)
move
(condp = kc
37 :left
39 :right
:no-move)]
(put! comm-ch {:event move}))))]
;COMPONENT EVENT LOOP
(go (loop []
(let [{:keys [event data] :as e} (<! comm-ch)
x (om/get-state owner [:animated :x])
obstacle (om/get-state owner :obstacle)]
(condp = event
:left
(do
(a/animated-value-fn! anim dec 0 a/linear))
:right
(do
(if (< x (- (:x obstacle) 10))
(a/animated-value-fn! anim inc 0 a/linear)))
;no match
(println "Unrecognized event::" e)))
(recur)))))
om/IRenderState
(render-state [_ {{:keys [x]} :animated obstacle :obstacle}]
(let []
(html
[:div {:style {:width "300px"
:position "relative"
:height "300px"
:backgroundColor "silver"}}
[:div {:style {:height "40px"
:width "300px"
:backgroundColor "green"}}]
[:div {:style {:height (str (:height obstacle) "px")
:position "absolute"
:left (str (:x obstacle) "px")
:width (str (:height obstacle) "px")
:backgroundColor "black"}}]
[:div {:style {:height "30px"
:position "absolute"
:left (str x "px")
:width "10px"
:backgroundColor "red"}}]])))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment