Created
March 25, 2011 17:47
-
-
Save bnferguson/887256 to your computer and use it in GitHub Desktop.
Daniel Shiffman's initial example in his PVector + Processing Tutorial re-written in clojure as an exercise.
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
; Daniel Shiffman's initial example in his PVector + Processing Tutorial | |
; re-written in clojure | |
(ns example1 | |
(:use [rosado.processing] | |
[rosado.processing.applet])) | |
(set! *warn-on-reflection* true) | |
(defn bounced? | |
"Checks to see if the ball has crossed any of our bounds" | |
[location, bound, current-speed] | |
(or (and (> location bound) (> current-speed 0)) | |
(and (< location 0) (< current-speed 0)))) | |
(def initial-ball-state {:x 100 :y 100 :xspeed 1 :yspeed 3.3}) | |
(defn next-ball-state | |
[{:keys [x y xspeed yspeed]}] | |
{:x (+ x xspeed) | |
:y (+ y yspeed) | |
:xspeed (if (bounced? x (width) xspeed) | |
(* xspeed -1) | |
xspeed) | |
:yspeed (if (bounced? y (height) yspeed) | |
(* yspeed -1) | |
yspeed)}) | |
(def ball-states (iterate next-ball-state initial-ball-state)) | |
(defn draw-background | |
[] | |
(no-stroke) | |
(fill 255 10) | |
(rect 0 0 (width) (height))) | |
(defn draw-ball | |
[{:keys [x y & _]}] | |
(stroke 0) | |
(fill 175) | |
(ellipse x y 16 16)) | |
(defn setup | |
"The setup. Gets run once." | |
[] | |
(smooth) | |
(background 255)) | |
(defn draw | |
"Draw loop. Gets called for every frame." | |
[] | |
(draw-background) | |
(draw-ball (first (nthnext ball-states (frame-count))))) | |
;; Now we just need to define an applet: | |
(defapplet example1 :title "An example." | |
:setup setup :draw draw :size [200 200]) | |
(run example1) | |
;; (stop example1) |
Updated it to use lazy sequences instead of tracking a bunch of global state. There is still the current-fram counter.
hey look at that processing already has a frame counter. Killed that bit of state (in my program).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm sure this is not as idiomatic Clojure as it should be. I'm just happy to reproduce the effect at all at this point. :D