Skip to content

Instantly share code, notes, and snippets.

@tacticiankerala
Last active May 17, 2019 05:41
Show Gist options
  • Save tacticiankerala/6079da46875ae071d3a9955e663732a2 to your computer and use it in GitHub Desktop.
Save tacticiankerala/6079da46875ae071d3a9955e663732a2 to your computer and use it in GitHub Desktop.
;; namespaces
;; macro
;; P5.js
(ns p5.core
(:require [vecvec.v2d :as v2d]))
;; operation
(enable-console-print!)
;;;; STATE
;; VAR
;; decouple state + identitiy
;; Don't: re-define a symbol with an updated value
(def canvas-size [500 500])
;; for changing states use `atoms`
;; deref, reset!, swap!,
(defonce triangles (atom []))
(defonce circles (atom []))
;; Initialization
(defn create-triangle []
(let [x1 (rand-int 500)
y1 (rand-int 500)
x2 (rand-int 500)
y2 (rand-int 500)
x3 (rand-int 500)
y3 (rand-int 500)
r (rand-int 100)
g (rand-int 100)
b (rand-int 100)]
{:points {:x1 x1 :y1 y1
:x2 x2 :y2 y2
:x3 x3 :y3 y3}
:fill-color {:r r :g g :b b}}))
(defn create-circle []
(let [x (rand-int 500) y (rand-int 500) d (rand-int 20)]
{:x x
:y y
:d d
:fill-color {:r (rand-int 200) :g (rand-int 200) :b (rand-int 200)}}))
(defn init-state []
(dotimes [_ 500]
(swap! triangles conj (create-triangle))
(swap! circles conj (create-circle))))
(defn clear-state []
(reset! triangles [])
(reset! circles []))
;; The REPL!!
;; The REPL!!
;;;; P5
(defn draw-triangle [triangle-attrs]
(let [points (:points triangle-attrs)
fill-color (:fill-color triangle-attrs)]
(js/fill (:r fill-color) (:g fill-color) (:b fill-color))
(js/triangle (:x1 points) (:y1 points)
(:x2 points) (:y2 points)
(:x3 points) (:y3 points))))
(defn draw-circle [circle-attrs]
(let [fill-color (:fill-color circle-attrs)]
(js/fill (:r fill-color) (:g fill-color) (:b fill-color))
(js/ellipse (:x circle-attrs) (:y circle-attrs) (:d circle-attrs) (:d circle-attrs))))
;; called once
(defn setup []
(init-state)
(apply js/createCanvas canvas-size)
(js/rectMode "CENTER")
(js/noStroke))
;; called in a loop
(defn draw []
(doseq [triangle (deref triangles)]
(draw-triangle triangle))
(doseq [circle (deref circles)]
(draw-circle circle)))
(defn mouse-clicked []
(js/background 240)
(clear-state)
(init-state))
;;;; INIT
(doto js/window
(aset "setup" setup)
(aset "draw" draw)
(aset "mouseClicked" mouse-clicked))
;;;; FIGWHEEL
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! *state update-in [:__figwheel_counter] inc)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment