首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用if on Quil更新状态

使用if on Quil更新状态
EN

Stack Overflow用户
提问于 2017-09-30 02:55:00
回答 1查看 375关注 0票数 2

我正试图用Quil编写10 PRINT代码。我试图将这个代码从使用露娜的twitter帖子https://twitter.com/ACharLuk/status/913094845505445890中转换出来。

这是我的密码

代码语言:javascript
复制
(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]
             )

看上去就像这样。我试图拆分状态更新,但是它说您不能有要更新的重复变量。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-30 11:53:38

您的代码在正确的方向,您成功地绘制了第一条线。当update-state被呼叫时,它就崩溃了。为了修复代码,我做了以下工作:

  • Clojure使用的是纯函数,您不能像在update-state中那样“设置”值( do只返回最后一个表达式,而不是两个值)。要实现update-state,您需要返回一个全新的状态。
  • q/heightq/widths是返回高度和宽度的函数,因此调用它们(用圆括号包围它们)以得到数字。
  • 当您在update-state中重新绘制背景时,旧行已经消失,所以将(q/background 0)放在setup中。
    • (q/no-loop)update-state移动到程序的draw-state入口点。

在文体上,我改变了这一点:

以下是工作版本:

代码语言:javascript
复制
(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])

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46499143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档