Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(require '[clojure.string :as s])
;; Maze GENERATION
(defn north-of [[row col]] [(dec row) col])
(defn south-of [[row col]] [(inc row) col])
(defn west-of [[row col]] [row (dec col)])
(defn east-of [[row col]] [row (inc col)])
(defn neighbours [rows cols cell]
(filter (fn [[i j]] (and (< -1 i rows) (< -1 j cols))) ((juxt north-of east-of south-of west-of) cell)))
(defn visited? [fallen-walls rows cols cell]
(some fallen-walls (for [n (neighbours rows cols cell)] #{n cell})))
(defn find-unvisited-neighbours [fallen-walls rows cols cell]
(let [n (neighbours rows cols cell)]
(remove #(visited? fallen-walls rows cols %) n)))
(defn generate-maze [rows cols]
(loop [fallen-walls #{}
backtrackstack '([0 0])]
(if-some [cell (peek backtrackstack)]
(if-some [unvn (seq (find-unvisited-neighbours fallen-walls rows cols cell))]
(let [next (rand-nth unvn)]
(recur
(conj fallen-walls #{next cell})
(conj backtrackstack next)))
(recur fallen-walls (pop backtrackstack)))
{:fallen-walls fallen-walls
:cols cols
:rows rows})))
;; Maze PRINTING
(defn print-maze [{:keys [fallen-walls rows cols]}]
(doseq [j (range cols)]
(print "+---"))
(println "+")
(doseq [i (range rows)]
(doseq [j (range cols)]
(print (if (fallen-walls #{[i j] [i (dec j)]}) " " "| ")))
(println "|")
(doseq [j (range cols)]
(print (if (fallen-walls #{[i j] [(inc i) j]}) "+ " "+---")))
(println "+")))
;; Maze DRAWING
(defn draw-maze [{:keys [fallen-walls rows cols]}]
(let [w (* 10 (inc cols))
h (* 10 (inc rows))
img (java.awt.image.BufferedImage. w h java.awt.image.BufferedImage/TYPE_INT_RGB)
g (.createGraphics img)]
(doto g
(.translate 10 10)
(.scale 10 10)
(.setBackground java.awt.Color/BLACK)
(.setColor java.awt.Color/WHITE)
(.setStroke (java.awt.BasicStroke. 0.5))
(.clearRect 0 0 w h))
(doseq [[[i j] [ii jj]] (map seq fallen-walls)]
(.drawLine g j i jj ii))
img))
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.