Maze generation: Difference between revisions

Line 3,286:
| | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+</pre>
 
=={{header|Racket}}==
 
Maze generator
<lang racket>
#lang racket
 
;; the structure representing a maze of size NxM
(struct maze (N M tbl))
 
;; managing cell properties
(define (connections tbl c) (dict-ref tbl c '()))
 
(define (connect! tbl c n)
(dict-set! tbl c (cons n (connections tbl c)))
(dict-set! tbl n (cons c (connections tbl n))))
 
(define (connected? tbl a b) (member a (connections tbl b)))
 
;; Returns a maze of a given size
(define (build-maze N M)
(define tbl (make-hash))
(define (visited? tbl c) (dict-has-key? tbl c))
(define (neigbours c)
(filter
(match-lambda [(list i j) (and (<= 0 i (- N 1)) (<= 0 j (- M 1)))])
(for/list ([d '((0 1) (0 -1) (-1 0) (1 0))]) (map + c d))))
; generate the maze
(let move-to-cell ([c (list (random N) (random M))])
(for ([n (shuffle (neigbours c))] #:unless (visited? tbl n))
(connect! tbl c n)
(move-to-cell n)))
; return the result
(maze N M tbl))
</lang>
 
Printing out the maze
 
<lang racket>
;; Shows a maze
(define (show-maze m)
(match-define (maze N M tbl) m)
(for ([i N]) (display "+---"))
(displayln "+")
(for ([j M])
(display "|")
(for ([i (- N 1)])
(if (connected? tbl (list i j) (list (+ 1 i) j))
(display " ")
(display " |")))
(display " |")
(newline)
(for ([i N])
(if (connected? tbl (list i j) (list i (+ j 1)))
(display "+ ")
(display "+---")))
(displayln "+"))
(newline))
</lang>
 
Example:
<pre>
-> (define m (build-maze 10 7))
-> (show-maze m)
+---+---+---+---+---+---+---+---+---+---+
| | | | |
+ +---+---+ + + +---+ +---+ +
| | | | | | |
+ + +---+ + +---+ +---+---+ +
| | | | | | |
+ +---+ +---+---+ +---+---+ + +
| | | | | |
+ + +---+---+---+ + + +---+ +
| | | | | | |
+---+ + +---+ +---+ + + +---+
| | | | | | |
+ +---+ + +---+ +---+---+---+ +
| | |
+---+---+---+---+---+---+---+---+---+---+
</pre>
 
=={{header|Rascal}}==
Anonymous user