Skip to content

Instantly share code, notes, and snippets.

@metamorph
Created June 29, 2015 19:16
Show Gist options
  • Save metamorph/2d368ecb85198b356a2a to your computer and use it in GitHub Desktop.
Save metamorph/2d368ecb85198b356a2a to your computer and use it in GitHub Desktop.
(ns amaze-me.core
(:require [quil.core :as q]
[quil.middleware :as m]))
(defn ball-setup
"initial state of tha ball."
[]
(q/smooth)
(q/background 255)
{:direction {:x 4 :y 5}
:fill [100 80 40]
:size {:x 60 :y 60}
:position {:x 100 :y 100}})
(defn within
"Check if a value is within the bounds of max/min"
[min max value] (and (> value min) (< value max)))
(defn with-bounce
"Invert the direction of the value is outside of the bounds (max/min)"
[min max value direction]
(if (within min max value)
direction
(* -1 direction)))
(defn ball-state
"Calculate the next state for the ball."
[state]
(let [x (get-in state [:position :x])
y (get-in state [:position :y])
x-buf (q/round (/ (get-in state [:size :x]) 2))
y-buf (q/round (/ (get-in state [:size :y]) 2))
dir-x (with-bounce x-buf (- (q/width) x-buf) x (get-in state [:direction :x]))
dir-y (with-bounce y-buf (- (q/height) y-buf) y (get-in state [:direction :y]))
new-x (+ x dir-x)
new-y (+ y dir-y)]
;; Check if the we're at a wall. If so, update the direction and re-evaluate the 'ball-state'.
(-> state
(assoc-in [:direction :x] dir-x)
(assoc-in [:direction :y] dir-y)
(assoc-in [:position :x] new-x)
(assoc-in [:position :y] new-y))))
(defn ball-draw
"Render the ball"
[state]
(q/background 255)
(q/with-fill (:fill state)
(q/ellipse
(get-in state [:position :x])
(get-in state [:position :y])
(get-in state [:size :x])
(get-in state [:size :y]))))
(q/defsketch ball
:size [400 400]
:setup ball-setup
:draw ball-draw
:update ball-state
:middleware [m/fun-mode])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment