Skip to content

Instantly share code, notes, and snippets.

@plexus
Last active October 14, 2017 13:01
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 plexus/bba60540e714b31dcac02eb7cdf02fbc to your computer and use it in GitHub Desktop.
Save plexus/bba60540e714b31dcac02eb7cdf02fbc to your computer and use it in GitHub Desktop.
;; # A game of snake
;; First create the board that the snake will move on. For now the board is just an empty rectangle, but it's a cell so what's inside it can change. We'll update the board later so it contains the snake.
(defcell board
(let [square #(colorize "white" (rectangle 10 10))]
(->> (range 20))
(apply above (map #(apply beside (map square (range 20))) (range 20)))))
(defcell last-key nil)
(defcell direction [self]
(or
(get {37 :left
38 :up
39 :right
40 :down} @last-key)
@self
:down))
(defcell snake [[2 2] [2 3] [2 4] [2 5]])
(defn move-piece [[x y]]
(let [[x+ y+] (case @direction
:left [dec identity]
:right [inc identity]
:up [identity dec]
:down [identity inc])
wrap #(cond (< % 0) 9 (> % 9) 0 :else %)]
[(wrap (x+ x)) (wrap (y+ y))]))
(defn move! []
(swap! snake #(conj (butlast %) (move-piece (first %)))))
(defn compute-board []
(->>
(for [y (range 10)
x (range 10)]
(cond->> (colorize "white" (rectangle 20 20)) (some #{[x y]} @snake) (colorize "blue")))
(partition 10)
(map #(apply beside %))
(apply above)))
(defn tick! []
(move!)
(reset! board (compute-board))
nil)
(defcell game-loop []
(interval 200 tick!))
(goog.events.listen js/document goog.events.EventType.KEYDOWN #(reset! last-key (.-keyCode %)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment