Skip to content

Instantly share code, notes, and snippets.

@branneman branneman/snake.clj

Created Oct 8, 2019
Embed
What would you like to do?
(ns main (:gen-class))
;; Snake :: [[int int]…]
;; vector of x,y tuples
;; head is first, tail is last
;; out-of-bounds? :: (int int int) -> bool
;; grid-size is 1-indexed, x+y are 0-indexed
(defn out-of-bounds? [grid-size x y]
(or (neg? x) (neg? y) (>= x grid-size) (>= y grid-size)))
;; intersects-snake :: (Snake [int int]) -> bool
(defn intersects-snake [snake [x y]]
(some
#(and (= x (first %)) (= y (second %)) true)
snake))
;; move-snake :: (int char Snake) -> Snake
(defn move-snake [grid-size direction snake]
(let [
[x y] (first snake)
head (cond
(= direction \E) [(+ x 1) y]
(= direction \S) [x (+ y 1)]
(= direction \W) [(- x 1) y]
(= direction \N) [x (- y 1)])
] (butlast (cons head snake))))
;; random-xy :: int -> [int int]
(defn random-xy [size]
[(rand-int size) (rand-int size)])
;; random-food :: (fn int Snake) -> [int int]
(defn random-food [random-xy size snake]
(let [xy (atom (random-xy size))]
(while (intersects-snake snake @xy)
(swap! xy (fn [& xs] (random-xy size))))
@xy))
(defn -main
[& args]
(println "Hello, World!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.