Last active
December 17, 2015 19:59
-
-
Save sevvie/5664676 to your computer and use it in GitHub Desktop.
I've fallen head-over-heels for Clojure. x.x Working through _Clojure Programming_, though, I've run into a problem I just can't seem to figure out; it behaves as if it's working, except it doesn't actually draw the maze. Forgive my spacious manner of writing Lisps. It just makes it easier to visualize everything for me.
This file contains hidden or 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
(defn wilson-maze | |
"Returns a random maze carved out of walls; walls is a set of | |
two-item sets, #{a b}, where a and b are locations. The returned | |
maze is a set of the remaining walls." | |
[walls] | |
(let [paths (reduce | |
(fn [index [a b]] (merge-with into index {a [b] b [a]})) | |
{} (map seq walls)) | |
start-loc (rand-nth (keys paths))] | |
(loop [walls walls | |
unvisited (disj (set (keys paths)) start-loc)] | |
(if-let [loc (when-let [s (seq unvisited)] (rand-nth s))] | |
(let [walk (iterate (comp rand-nth paths) loc) | |
steps (zipmap (take-while unvisited walk) (next walk))] | |
(recur (reduce disj walls (map set steps)) | |
(reduce disj unvisited (keys steps)))) | |
walls)))) | |
(defn maze-grid [w h] | |
(set (concat | |
(for [i (range (dec w)) j (range h)] #{[i j] [(inc i) j]}) | |
(for [i (range w) j (range (dec h))] #{[i j] [i (inc j)]})))) | |
(defn swing-draw [w h maze] | |
(doto (javax.swing.JFrame. "Maze") | |
(.setContentPane | |
(doto (proxy [javax.swing.JPanel] [] | |
(paintComponent [^java.awt.Graphics g] | |
(let [g (doto ^java.awt.Graphics2D (.create g) | |
(.scale 10 10) | |
(.translate 1.5 1.5) | |
(.setStroke (java.awt.BasicStroke. 0.4)))] | |
(.drawRect g -1 -1 w h) | |
(doseq [[[xa ya] [xb yb]] (map sort maze)] | |
(let [[xc yc] (if (= xa xb) | |
[(dec xa) ya] | |
[xa (dec ya)])] | |
(.drawLine g xa ya xc yc)))))) | |
(.setPreferredSize (java.awt.Dimension. (* 10 (inc w)) (* 10 (inc h)))))) | |
.pack | |
(.setVisible true))) | |
(swing-draw 40 40 (wilson-maze (maze-grid 40 40))) |
FIXED. I was a complete idiot and didn't let (wilson-maze) return anything to be (map sort)'ed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
EDIT. I tucked in my parentheses for you all.