Skip to content

Instantly share code, notes, and snippets.

@bnferguson
Created March 25, 2011 17:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bnferguson/887256 to your computer and use it in GitHub Desktop.
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.
; 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)
@bnferguson
Copy link
Author

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

@bnferguson
Copy link
Author

Updated it to use lazy sequences instead of tracking a bunch of global state. There is still the current-fram counter.

@bnferguson
Copy link
Author

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