sdasdadas
sdasdadas

Reputation: 25096

How do I rewrite (def) out of this Clojure code?

I have written a game loop based on deWitter's game loop.

However, I am unsure how to transfer it to a more functional state. I realize that there may need to be some mutable state left within the code but are there any general principles for cleaning up extraneous defs?

(ns beepboop.core)

(def ticks-per-second 25)
(def skip-ticks (/ 1000 ticks-per-second))
(def max-frameskip 5)

(defn update []
  (println "Updating."))

(defn display [delta]
  (println "Displaying with delta: " delta))

(defn -main []
  (def *next-tick* (System/currentTimeMillis))
  (while true
    (def *loops* 0)
    (while (and
            (> (System/currentTimeMillis)
               *next-tick*)
            (< *loops*
               max-frameskip))
      (update)
      (def *next-tick* (+ *next-tick* skip-ticks))
      (def *loops* (+ *loops* 1)))
    (display
     (/ (+ (System/currentTimeMillis) skip-ticks (* -1 *next-tick*))
        skip-ticks))))

Upvotes: 1

Views: 162

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

You should use loop and recur for updating your loop variables:

(defn -main []
  (loop [next-tick (System/currentTimeMillis)]
    (let [next-next 
          (loop [next-tick next-tick
                 loops 0]
            (if (and (> (System/currentTimeMillis) next-tick)
                     (< loops max-frameskip))
                (do (update)
                    (recur (+ next-tick skip-ticks) (+ loops 1)))
                next-tick))]
      (display (/ (+ (System/currentTimeMillis) skip-ticks (- next-next))
                  skip-ticks))
      (recur next-next))))

Upvotes: 3

Related Questions