Skip to content

Commit

Permalink
Add 0.3 and 0.3e along with some cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
Ramblurr committed May 28, 2024
1 parent 48f48af commit 0c07f81
Show file tree
Hide file tree
Showing 12 changed files with 199 additions and 63 deletions.
3 changes: 2 additions & 1 deletion deps.edn
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
:exec-args
{:paths ["notebooks/**"]
:index "notebooks/index.md"
:out-path "public"}}
:out-path "public"
:cas-prefix "/nature-of-code/"}}

:watch
{:exec-fn user/start-with-shadow!
Expand Down
4 changes: 2 additions & 2 deletions dev/user.clj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
(def ^{:doc "static site defaults for local and github-pages modes."}
defaults
{:out-path "public"
:cas-prefix "/nature-of-code/"})
:cas-prefix "/"})

(defn start!
"Starts a Clerk server process "
Expand Down Expand Up @@ -108,7 +108,7 @@
:out-path "public"})

(static-build! {:paths ["notebooks/**"]
;; :index "notebooks/index.md"
:index "notebooks/index.md"
:out-path "public"})

;;
Expand Down
20 changes: 0 additions & 20 deletions notebooks/chapter_0.clj

This file was deleted.

101 changes: 101 additions & 0 deletions notebooks/chapter_0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Chapter 0

```clojure
(ns chapter-0
{:nextjournal.clerk/visibility {:code :hide} :nextjournal.clerk/toc true}
(:require [nextjournal.clerk :as clerk]
[noc.quil-clerk :refer [show-sketch]]))
```

## [Example 0.1: A Traditional Random Walk](https://natureofcode.com/random/#example-01-a-traditional-random-walk)

```clojure
^{::clerk/no-cache true ::clerk/viewer clerk/code}
(slurp "src/noc/chapter_0_1.cljs")

(show-sketch :walker)
```


## [Example 0.2: A Random-Number Distribution](https://natureofcode.com/random/#example-02-a-random-number-distribution)


```clojure
^{::clerk/no-cache true ::clerk/viewer clerk/code}
(slurp "src/noc/chapter_0_2.cljs")

(show-sketch :rand-dist)
```

## [Example 0.3: A Walker That Tends to Move to the Right](https://natureofcode.com/random/#example-03-a-walker-that-tends-to-move-to-the-right)

```clojure
^{::clerk/no-cache true ::clerk/viewer clerk/code}
(slurp "src/noc/chapter_0_3.cljs")

(show-sketch :walker-right)
```

## [Exercise 0.3: Dynamic Walker](https://natureofcode.com/random/#exercise-03)

```clojure
^{::clerk/no-cache true ::clerk/viewer clerk/code}
(slurp "src/noc/chapter_0_3e.cljs")
```

For this exercise I the walker has a 50% chance of moving in the direction of the mouse by one step.
The other 50% of the time it moves randomly up, down, left, right, or back towards the center.

The move-towards function uses the Euclidean distance between the walker and the mouse to determine the direction.

```clojure
(clerk/tex "d = \\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}")
```

To move a point B towards point A by a small step using the Euclidean distance, you calculate the direction vector (dx, dy) and normalize it.

1. **Calculate the Direction Vector:**
Find the difference in x-coordinates and y-coordinates between points A and B.

$$
dx = x_A - x_B
\\
dy = y_A - y_B
$$

2. **Normalize the Direction Vector:**
Calculate the Euclidean distance (magnitude) between points A and B to normalize the direction vector.

$$
\text{distance} = \sqrt{dx^2 + dy^2}")
$$

Then, divide each component of the direction vector by this distance to get the unit vector in the direction from B to A.

$$
\text{unit\_dx} = \frac{dx}{\text{distance}}
\\
\text{unit\_dy} = \frac{dy}{\text{distance}}
$$

3. **Scale the Unit Vector:**
Multiply the unit vector by the desired step size.

$$
\text{step\_dx} = \text{step} \times \text{unit\_dx}
\\
\text{step\_dy} = \text{step} \times \text{unit\_dy}
$$

4. **Update the Coordinates of B:**
Add the scaled vector to the coordinates of B to get the new position.

$$
x_B' = x_B + \text{step\_dx}
\\
y_B' = y_B + \text{step\_dy}
$$

```clojure
(show-sketch :walker-dynamic)
```
4 changes: 2 additions & 2 deletions notebooks/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Implementing it in Clojure lets me train my functional muscles and it's rather f

Though I've tried to keep the code as close to the original as possible, Clojure is an immutable functional programming language, and my translation of the examples adhere to that property.

To learn how I've structured the code to avoid willy-nilly mutation or what tech I'm using to render all of this, check out the [background](background.md).
To learn how I've structured the code to avoid willy-nilly mutation or what tech I'm using to render all of this, check out the [background](notebooks/background).

## Table of Contents

Expand All @@ -49,6 +49,6 @@ To learn how I've structured the code to avoid willy-nilly mutation or what tech
[:div.text-xs.text-gray-500.group-hover:text-indigo-600.leading-normal description]]])
[{:title "Chapter 0"
:preview (io/resource "assets/img/chapter0.png")
:path "notebooks/chapter_0.clj"
:path "notebooks/chapter_0"
:description "Randomness"}])))
```
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@
"p5": "^1.9.4"
},
"scripts": {
"serve": "http-server -c-1 -o -p 8080"
"serve": "http-server -c-1 -o -p 8080 public"
}
}
29 changes: 29 additions & 0 deletions src/noc/chapter_0_3.cljs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
(ns noc.chapter-0-3
(:require
[quil.core :as q]))

(def size [640 240])

(defn init-state [{:keys [width height]}]
{:walker {:x (quot width 2)
:y (quot height 2)}})

(defn setup! []
(q/background 255))

(defn tick [{:keys [width height] :as state}]
(let [r (q/random 1)
step (fn [{:keys [x y]}]
(cond
(< r 0.4) {:x (inc x) :y y}
(< r 0.6) {:x (dec x) :y y}
(< r 0.8) {:x x :y (inc y)}
:else {:x x :y (dec y)}))
constrain (fn [{:keys [x y]}]
{:x (q/constrain x 0 (- width 1))
:y (q/constrain y 0 (- height 1))})]
(update state :walker (comp constrain step))))

(defn draw! [{:keys [walker]}]
(q/stroke 0)
(q/point (:x walker) (:y walker)))
45 changes: 45 additions & 0 deletions src/noc/chapter_0_3e.cljs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
(ns noc.chapter-0-3e
(:require
[quil.core :as q]))

(def size [640 240])

(defn init-state [{:keys [width height]}]
{:walker {:x (quot width 2)
:y (quot height 2)}})

(defn setup! []
(q/background 255))

(defn move-towards [ax ay bx by step]
(let [dx (- ax bx)
dy (- ay by)
distance (Math/sqrt (+ (* dx dx) (* dy dy)))
unit-dx (/ dx distance)
unit-dy (/ dy distance)]
{:x (+ bx (* step unit-dx))
:y (+ by (* step unit-dy))}))

(defn tick [{:keys [width height] :as state}]
(let [r (q/random 1)
mx (q/mouse-x)
my (q/mouse-y)
centerx (quot width 2)
centery (quot height 2)
step (fn [{:keys [x y]}]
(cond
(< r 0.5) (move-towards mx my x y 1)
(< r 0.6) {:x (inc x) :y y}
(< r 0.7) {:x (dec x) :y y}
(< r 0.8) {:x x :y (inc y)}
(< r 0.9) {:x x :y (dec y)}
:else (move-towards centerx centery x y 1)))

constrain (fn [{:keys [x y]}]
{:x (q/constrain x 0 (- width 1))
:y (q/constrain y 0 (- height 1))})]
(update state :walker (comp constrain step))))

(defn draw! [{:keys [walker]}]
(q/stroke 0)
(q/point (:x walker) (:y walker)))
23 changes: 0 additions & 23 deletions src/noc/dots.cljs

This file was deleted.

1 change: 0 additions & 1 deletion src/noc/render.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
nextjournal.clerk.viewer/mark-presented))])
:attrs {:class "foobar"}
:render-fn '(fn [blob-or-url opts]
(prn "ATTRV" (-> opts :viewer :attrs))
[:img (merge {:src #?(:clj (nextjournal.clerk.render/url-for blob-or-url)
:cljs blob-or-url)}
(-> opts :viewer :attrs))])})
Expand Down
8 changes: 8 additions & 0 deletions src/noc/sketch.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
(ns noc.sketch)

(defmacro sketch-> [chapter]
`{:init ~(symbol (str chapter "/init-state"))
:setup ~(symbol (str chapter "/setup!"))
:tick ~(symbol (str chapter "/tick"))
:draw ~(symbol (str chapter "/draw!"))
:size ~(symbol (str chapter "/size"))})
22 changes: 9 additions & 13 deletions src/noc/sketch.cljs
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
(ns noc.sketch
(:require-macros [noc.sketch :refer [sketch->]])
(:require [quil.core :as q]
[quil.sketch :as ap :include-macros true]
[noc.chapter-0-1 :as c0.1]
[noc.chapter-0-2 :as c0.2]
[noc.dots :as dots]))
[noc.chapter-0-3 :as c0.3]
[noc.chapter-0-3e :as c0.3e]))

(def sketches {:dots dots/sketch
:walker {:init c0.1/init-state
:setup c0.1/setup!
:tick c0.1/tick
:draw c0.1/draw!
:size c0.1/size}
:rand-dist {:init c0.2/init-state
:setup c0.2/setup!
:tick c0.2/tick
:draw c0.2/draw!
:size c0.2/size}})
(def sketches {:walker (sketch-> c0.1)
:rand-dist (sketch-> c0.2)
:walker-right (sketch-> c0.3)
:walker-dynamic (sketch-> c0.3e)})

(defn load-sketch [s]
(when-let [sk (get sketches s)]
Expand Down Expand Up @@ -79,7 +74,7 @@
(try
(q/state :state)
(catch js/Error e
(.error js/log e)
(.error js/console e)
nil)))

(defn pause [sketch*]
Expand All @@ -105,6 +100,7 @@
(defn tick-wrapper [tick state]
(->
state
(assoc :width (q/width) :height (q/height))
(tick-time (time-now!) (q/current-frame-rate))
(tick)))

Expand Down

0 comments on commit 0c07f81

Please sign in to comment.