-
-
Save plexus/bba60540e714b31dcac02eb7cdf02fbc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; # 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