Created
November 28, 2012 01:43
-
-
Save ehaliewicz/4158525 to your computer and use it in GitHub Desktop.
Random flood fill
This file contains 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
;;; recur is like clojure's loop/recur | |
;;; | |
;;; declare a tail-recursive loop with | |
;;; (recur ( (var-name (&optional type) init-val) ... more vars)) | |
;;; | |
;;; recur back to the beginning with | |
;;; (tail-recur (var-name new-value) ... more vars) | |
;;; (exit &optional val) | |
;;; leaves the recursion returning either nil, or the given value | |
;;; start the algorithm with a random position on the stack and a depth of 1 | |
(recur ((stack list `(,(make-pos :x (random width) :y (random height)))) (depth fixnum 1)) | |
;; if the stack is empty, we're done | |
(if (null stack) | |
(progn | |
(format t "Done.~%") | |
(setf filling nil) | |
;; exit from recursion | |
(exit)) | |
;; otherwise, | |
;; if there are empty spots around this pixel, | |
;; recur deeper | |
(if (empty-spots (pos-x (car stack)) (pos-y (car stack)) arr width height) | |
;; new color based on depth | |
(let ((r (truncate (max 0 (- 255 (* 0.0004 depth))))) | |
(g (truncate (max 0 (- 255 (* 0.00066 depth))))) | |
(b (truncate (max 0 (- 255 (* 0.0004 depth)))))) | |
;; -> is a threading operator | |
;; | |
;; _ is an anaphor that refers to the | |
;; previous value in the thread | |
;; | |
;; (-> 2 (+ 3 _) => (+ 4 (+ 3 2) | |
;; (+ 4 _ _)) (+ 3 2)) | |
;; | |
;; | |
;; you can also use single arg functions | |
;; (-> 2 square sqrt) => (sqrt (square 2)) | |
;; choose the next direction random and recur further down | |
(-> (elt empty-spots (random (length empty-spots))) | |
;; make a draw task (draw now if progressive) | |
(make-draw-task (pos-x _) (pos-y _) r g b arr progressive)) | |
;; place the drawn position on the stack and increment depth | |
(tail-recur (stack (cons _ stack)) (depth (1+ depth)))) | |
;; if there are no empty spaces, | |
;; recur back up the stack | |
(tail-recur (stack (cdr stack)) (depth (1- depth))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment