|
| 1 | +(ns noc.chapter-1-7 |
| 2 | + (:require |
| 3 | + [noc.quil.util :as u] |
| 4 | + [thi.ng.math.core :as tm] |
| 5 | + [thi.ng.geom.vector :as v] |
| 6 | + [quil.core :as q])) |
| 7 | + |
| 8 | +(def size [640 240]) |
| 9 | + |
| 10 | +(defn init-state [{:keys [width height] :as state}] |
| 11 | + {:mover {:position (v/vec2 (q/random width) (q/random height)) |
| 12 | + :velocity (v/vec2 (q/random -2 2) (q/random -2 2))}}) |
| 13 | + |
| 14 | +(defn setup! [{:keys [width height]}] |
| 15 | + (q/background 255)) |
| 16 | + |
| 17 | +;; These were my first pass at the implementation |
| 18 | +;; but I wasn't happy that it has so much repeated code |
| 19 | +(comment |
| 20 | + (defn enforce-bound-x [width position] |
| 21 | + (let [x (v/x position)] |
| 22 | + (cond (>= x width) (v/vec2 0 (v/y position)) |
| 23 | + (<= x 0) (v/vec2 width (v/y position)) |
| 24 | + :else position))) |
| 25 | + |
| 26 | + (defn enforce-bound-y [height position] |
| 27 | + (let [y (v/y position)] |
| 28 | + (cond (>= y height) (v/vec2 (v/y position) 0) |
| 29 | + (<= y 0) (v/vec2 (v/y position) height) |
| 30 | + :else position)))) |
| 31 | + |
| 32 | +;; ... so I refactored it to this |
| 33 | +;; `dimension` is either width or height |
| 34 | +;; `component` is either :x or :y, perhaps there's a better name? |
| 35 | +(defn enforce-bound [dimension component position] |
| 36 | + (let [value (component position)] |
| 37 | + (cond (>= value dimension) (assoc position component 0) |
| 38 | + (<= value 0) (assoc position component dimension) |
| 39 | + :else position))) |
| 40 | + |
| 41 | +(defn tick-mover [width height {:keys [velocity] :as mover}] |
| 42 | + (-> mover |
| 43 | + (update :position #(tm/+ % velocity)) |
| 44 | + (update :position #(enforce-bound width :x %)) |
| 45 | + (update :position #(enforce-bound height :y %)))) |
| 46 | + |
| 47 | +(defn tick [{:keys [width height] :as state}] |
| 48 | + (-> state |
| 49 | + (update :mover #(tick-mover width height %)))) |
| 50 | + |
| 51 | +(defn draw-mover [{:keys [position]}] |
| 52 | + (q/stroke 0) |
| 53 | + (q/stroke-weight 2) |
| 54 | + (q/fill 127) |
| 55 | + (q/ellipse (v/x position) (v/y position) 48 48)) |
| 56 | + |
| 57 | +(defn draw! [{:keys [mover]}] |
| 58 | + (q/background 255) |
| 59 | + (draw-mover mover)) |
0 commit comments