如何从这个Clojure代码中重写(def)?

时间:2013-03-31 04:37:59

标签: clojure functional-programming lisp state

我写了一个基于deWitter's game loop的游戏循环。

但是,我不确定如何将其转移到更实用的状态。我意识到代码中可能需要保留一些可变状态,但是有没有清除无关def s的一般原则?

(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))))

1 个答案:

答案 0 :(得分:3)

您应该使用looprecur来更新循环变量:

(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))))