game.cljs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. (ns bombnet.web.game
  2. (:require [cljs.core.async :refer [<! >! chan]]
  3. [bombnet.web.display :refer [render-game]])
  4. (:require-macros [cljs.core.async.macros :refer [go]]))
  5. (defrecord Game [conn state local])
  6. (defn ^:private send-msg [game & params]
  7. (let [{conn :conn} @game]
  8. (bombnet.web.ws/send! conn (apply hash-map (conj params :type)))))
  9. (defn ^:private send-action [game & params]
  10. (let [action (apply hash-map (conj params :type))]
  11. (send-msg game "action"
  12. :action action)
  13. (swap! game update [:local :action] action)))
  14. (defn action-move [game dir]
  15. (send-action game "move" :dir dir))
  16. (defn action-bomb [game timer]
  17. (let [diagonal? (get-in @game [:local :diagonal?])]
  18. (send-action game "bomb" :timer timer :diagonal? diagonal?)))
  19. (defn action-nop [game]
  20. (send-action game "nop"))
  21. (defn toggle-diagonal [game]
  22. (swap! game update-in [:local :diagonal?] not))
  23. (defn msg-handler [game msg]
  24. (cond
  25. (:game msg) (do
  26. (swap! game assoc :state (:game msg))
  27. (render-game game))
  28. (:message msg) (.log js/console (:message msg))))
  29. (defn key-handler [game code]
  30. (let [{conn :conn} game
  31. k (fn [v] (aget js/ROT (str "VK_" v)))
  32. move (partial action-move game)
  33. bomb (partial action-bomb game)]
  34. (condp #(= (k %) %2) code
  35. "R" (send-msg game "start")
  36. "X" (toggle-diagonal game)
  37. "PERIOD" (action-nop game)
  38. "UP" (move "up")
  39. "DOWN" (move "down")
  40. "LEFT" (move "left")
  41. "RIGHT" (move "right")
  42. "1" (bomb 1)
  43. "2" (bomb 2)
  44. "3" (bomb 3)
  45. "4" (bomb 4)
  46. "5" (bomb 5)
  47. nil)))
  48. (defn init-game [id conn]
  49. (atom (->Game conn nil {:id id})))