2013-03-31 121 views
1

我寫了一個基於deWitter's game loop的遊戲循環。如何從Clojure代碼中重寫(def)?

但是,我不確定如何將其轉移到更多功能狀態。我意識到可能需要在代碼中留下一些可變的狀態,但是有沒有清除無關的一般原則def

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

使用'let'綁定本地變量,和''設置更新它們! – Barmar

+0

@Barmar這對我來說似乎是錯誤的。我覺得'let'不能更新,因爲它只是一個詞法範圍。 – sdasdadas

回答

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)))) 
+1

謝謝,這真棒。編輯:唯一的問題是'next-tick'在循環之外(在顯示調用中)。 – sdasdadas

+1

@sdasdadas好的,讓我解決這個問題。 –

+2

@sdasdadas好吧,我已經修復了我所知道的最好的方法。我不是Clojurian(我是Schemer),所以那些活着和呼吸Clojure的人應該提出進一步的改進建議。 :-) –