Guest User

Untitled

a guest
Jul 5th, 2015
243
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (ns cmaze.maze
  2.   (use cmaze.cell))
  3.  
  4. (defrecord Maze [cells size])
  5.  
  6. (defn- create-maze-cell [index size]
  7.   "Creates a cell depending on its location in the maze."
  8.   (let [is-only-cell (= size 1)
  9.         [is-corner-cell corner] (m-corner-cell? index size)
  10.         [is-wall-cell side] (m-wall-cell? index size)]
  11.     (cond (true? is-only-cell) (create-cell)
  12.           (true? is-corner-cell) (create-corner-cell corner)
  13.           (true? is-wall-cell) (create-wall-cell side)
  14.           :else (create-unbound-cell))))
  15.  
  16. (defn create-maze [size]
  17.   "Create a maze sizeXsize large."
  18.   (Maze.
  19.     (let [total-cells (* size size)]
  20.       (map-indexed (fn [idx _] (create-maze-cell idx size))
  21.         (range total-cells)))
  22.     size))
  23.  
  24. (defn get-cell [maze x y]
  25.   (let [cells (:cells maze)
  26.         size (:size maze)
  27.         index (+ x (* y size))]
  28.     (when (> index (* size size)) (throw (IllegalArgumentException. (format "Index (%s, %s) exceeds size of maze." x y))))
  29.     (nth cells index)))
  30.  
  31. (defn- link [cell dir]
  32.   (assoc cell :open-dirs dir))
  33.  
  34. (defn- link-cell [maze cell idx]
  35.   (let [{cells :cells size :size} maze
  36.         {open-dirs :open-dirs} cell]
  37.     (doseq [open-dirs open-dirs]
  38.       (fn [open-dir]
  39.         (case open-dir
  40.           :east  (link (nth cells (inc idx)) :west)
  41.           :west  (link (nth cells (dec idx)) :east)
  42.           :north (link (nth cells (- idx size)) :south)
  43.           :south (link (nth cells (+ idx size)) :north))))
  44.     cell))
  45.  
  46. (defn link-cells [maze cells]
  47.   (for [cell cells
  48.         idx (range (count cells))]
  49.     (link-cell maze cell idx)))
  50.  
  51. (defn traverse [maze f]
  52.   (let [{cells :cells size :size} maze]
  53.       (map (fn [cell] (f cell))
  54.         cells)))
  55.  
  56. (defn binary-tree [cell]
  57.   (let [valid-dirs (:valid-dirs cell)]
  58.     (cond
  59.       (and (contains? valid-dirs :north) (contains? valid-dirs :east)) (assoc cell :open-dirs #{:east})
  60.       (contains? valid-dirs :north) (assoc cell :open-dirs #{:north})
  61.       (contains? valid-dirs :east) (assoc cell :open-dirs #{:east})
  62.       :else cell)))
  63.  
  64. ;; sample usage: (link-cells (traverse maze binary-tree))
RAW Paste Data