2

我正在尝试10 PRINT用 Quil 编写代码。我尝试从使用 luna的推特帖子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]
             )

它只是看起来像这样。我试图拆分状态的更新,但它说你不能有重复的变量要更新

在此处输入图像描述

谢谢你。

4

1 回答 1

4

您的代码方向正确,并且您设法绘制了第一行。调用时它崩溃了update-state。为了修复代码,我做了以下事情:

  • Clojure 与纯函数一起工作,在这些纯函数中,您无法像您想要的那样“设置”值update-statedo仅返回最后一个表达式,而不是两个值)。你update-state需要返回一个全新的状态。
  • q/height并且q/widths是返回高度和宽度的函数,因此调用它们(用括号括起来)以获取数字。
  • 当你重绘背景时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])

10打印

于 2017-09-30T11:53:38.537 回答