在 Quil 上用 if 更新状态

Update state with if on Quil

我正在尝试使用 Quil 编写 10 PRINT 代码。我尝试从使用 luna

的推特 post https://twitter.com/ACharLuk/status/913094845505445890 转换这段代码

这是我的代码

(ns tenprint.core
  (:require [quil.core :as q]
            [quil.middleware :as m]))

(defn setup []
  (q/frame-rate 30)
  (q/color-mode :hsb)
  {:x 0
   :y 0
   :scale 20
   }
  )

(defn update-state [state]

  (let [x (:x state) y (:y state) s (:scale state)]
    {
     :x (do (+ x s) ((if (>= x q/width) 0)))
     :y (do (if (>= x q/width) (+ y s)) (if (>= x q/height) (+ y s)))
     :scale (+ s 0)
     }
    )
  )

(defn draw-state [state]
  (q/background 0)

  (q/stroke 255)

  ;(q/line 0 10 10 0)

  (let [x (:x state) y (:y state) s (:scale state)]
    (if (> (rand) 0.5)
      (q/line x y (+ x s) (+ y s))
      (q/line x (+ y s) (+ x s) y)
      )
    )
  )

(q/defsketch tenprint
             :title "10PRINT"
             :size [500 500]
             :setup setup
             :update update-state
             :draw draw-state
             :settings #(q/smooth 2)
             :features [:keep-on-top]
             :middleware [m/fun-mode]
             )

它就是这样出现的。我试图拆分状态的更新,但它说你不能有重复的变量要更新

谢谢。

您的代码方向正确,您成功绘制了第一条线。调用 update-state 时崩溃。为了修复代码,我做了以下事情:

  • Clojure 与纯函数一起工作,你不能像在 update-state 中那样 "set" 值(使用 do only the last expression is returned, not two values). To update-state 你需要 return 一个全新的状态。
  • q/heightq/widths是return高度和宽度的函数,所以调用它们(用括号括起来)得到数字。
  • 当您在 update-state 中重绘背景时,较旧的线条已消失,因此请将 (q/background 0) 放入 setup
    • (q/no-loop)update-state 移动到程序的 draw-state 入口点。

在文体上我改变了这个:

低于工作版本:

(ns tenprint.core
  (:require [quil.core :as q]
            [quil.middleware :as m]))

(defn setup []
  (q/background 0) ; move setting background to setup, otherwise the state is overwritten
  (q/frame-rate 30)
  (q/stroke 255)
  (q/color-mode :hsb)
  {:x 0
   :y 0
   :scale 20})

(defn update-state [{:keys [x y scale] :as state}] ; destructure
  ;; height and width are functions you need to `(call)` to get the value
  {:x (if (>= x (q/width)) 0 (+ x scale)) ; fix if-statements
   :y (if (>= x (q/width)) (+ y scale) y) ; 'do' does something different than you think
   :scale scale}) ; no need to add 0

(defn draw-state [{:keys [x y scale] :as state}] ; destructure
  (if (>= y (q/height))
    (q/no-loop)
    (if (> (rand) 0.5)
      (q/line x y (+ x scale) (+ y scale))
      (q/line x (+ y scale) (+ x scale) y))))      

(q/defsketch tenprint
  :title "10 PRINT"
  :size [500 500]
  :setup setup
  :draw draw-state
  :update update-state
  :features [:keep-on-top]
  :middleware [m/fun-mode])