Skip to content

Instantly share code, notes, and snippets.

@branneman
Created October 8, 2019 10:57
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 branneman/8fa0625e921ddcaeb4fdd403a651e4e1 to your computer and use it in GitHub Desktop.
Save branneman/8fa0625e921ddcaeb4fdd403a651e4e1 to your computer and use it in GitHub Desktop.
(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