Created
February 21, 2017 03:48
-
-
Save drakezhard/94c6f04464014d8aa51b56fa70414623 to your computer and use it in GitHub Desktop.
sierpinski triangle
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
(ns sierpinski-triangle.app | |
(:require [quil.core :as q :include-macros true] | |
[quil.middleware :as m])) | |
(defn setup [] | |
(q/frame-rate 30) | |
{:corner-2 [(/ (q/height) 4) (/ (* -1 (/ (q/height) 2) (Math/sqrt 3)) 2)] | |
:corner-3 [(/ (q/height) 2) 0] | |
:triangles [[0 0 (/ (q/height) 2) (* -1 (/ (q/height) 2) (Math/sqrt 3)) (q/height) 0]] | |
:max-iterations 5}) | |
(defn mean [a b] | |
(/ (+ a b) | |
2)) | |
(defn scale [[x1 y1 x2 y2 x3 y3]] | |
[x1 y1 | |
(mean x1 x2) (mean y1 y2) | |
(mean x1 x3) (mean y1 y3)]) | |
(defn translate [[x y][x1 y1 x2 y2 x3 y3]] | |
[(+ x1 x) (+ y1 y) | |
(+ x2 x) (+ y2 y) | |
(+ x3 x) (+ y3 y)]) | |
(defn triplicate [fractal corner-2 corner-3] | |
(-> fractal | |
(into (mapv (partial translate corner-2) fractal)) | |
(into (mapv (partial translate corner-3) fractal)))) | |
(defn halve [[x y]] | |
[(/ x 2) | |
(/ y 2)]) | |
(defn updater [state] | |
(if (> (:max-iterations state) 0) | |
(-> state | |
(update :triangles #(mapv scale %)) | |
(update :triangles #(triplicate % (:corner-2 state) (:corner-3 state))) | |
(update :corner-2 halve) | |
(update :corner-3 halve) | |
(update :max-iterations dec)) | |
state)) | |
(defn draw [state] | |
(q/background 255) | |
(q/fill 0) | |
(q/with-translation [(/ (q/width) 100) (q/height)] | |
(doseq [p (:triangles state)] | |
(apply q/triangle p)))) | |
(defn init [] | |
(let [canvas (. js/document (getElementById "canvas")) | |
_ (set! (.-width canvas) (.-innerWidth js/window)) | |
width (.-width canvas) | |
_ (set! (.-height canvas) (.-innerHeight js/window)) | |
height (.-height canvas)] | |
(q/sketch | |
:setup setup | |
:draw draw | |
:update updater | |
:host "canvas" | |
:size [width height] | |
:middleware [m/fun-mode]))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment