ClojureScript+React/Om clone of 2048
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.9KB

  1. (ns ttfe.core
  2. (:require [om.core :as om :include-macros true]
  3. [om.dom :as dom :include-macros true]
  4. [ttfe.board :refer [move-left move-right move-up move-down
  5. add-tile]]))
  6. (enable-console-print!)
  7. (def app-state
  8. (atom
  9. {:board [[ 4 4 2 2 ]
  10. [nil nil nil nil]
  11. [nil 8 nil nil]
  12. [nil nil nil nil]]}))
  13. (def move-fns [move-up move-right move-down move-left])
  14. (defn divs-for-board [board]
  15. (reduce (fn [row-acc row-n]
  16. (let [row (nth board row-n)]
  17. (concat row-acc
  18. (reduce (fn [acc col-n]
  19. (let [cell (nth row col-n)]
  20. (if (nil? cell)
  21. acc
  22. (conj acc
  23. (dom/div #js {:className (str "tile title-" (inc row-n) " tile-position-" (inc col-n) "-" (inc row-n))}
  24. (dom/div #js {:className "tile-inner"} cell))))))
  25. []
  26. (range (count row))))))
  27. '()
  28. (range (count board))))
  29. (defn tiles-view [app owner]
  30. (reify
  31. om/IRender
  32. (render [_]
  33. (let [cell-divs (divs-for-board (:board app))]
  34. (apply dom/div
  35. #js {:id "tiles" :className "tile-container"}
  36. cell-divs)))))
  37. (defn init []
  38. (let [input-manager (js/KeyboardInputManager.)]
  39. (.on input-manager
  40. "move"
  41. (fn [direction]
  42. (let [move-fn (nth move-fns direction)]
  43. (swap! app-state
  44. (fn [state]
  45. (let [board (:board state)]
  46. (update-in state [:board] (fn [b]
  47. (add-tile (move-fn b))))))))))
  48. (om/root tiles-view
  49. app-state
  50. {:target (. js/document (getElementById "tiles"))})))