【问题标题】:Using C-style encapsulation techniques in Clojure?在 Clojure 中使用 C 风格的封装技术?
【发布时间】:2011-03-14 22:21:09
【问题描述】:

我正在处理我的第一个(非平凡的)Clojure program 我对如何在全球范围内声明我所有的可变状态感到不舒服。例如:

(def next-blocks (atom []))
(def num-next-blocks 1)
(def is-game-over (atom false))
(def user-name (atom (str)))
(def hs-xml (atom nil))

由于我在工作中经常使用 C,因此我想出了使用常见 C 风格封装技术的想法。它通常涉及作为第一个参数传递给对其进行操作的任何“成员函数”的结构对象。例如,请参阅udev。

将它应用到 Clojure 会产生如下所示的函数(未经测试):

(defstruct gamestate)

(defn game-new []
  (struct-map gamestate
    :level            (atom 0)
    :score            (atom 0)
    ;etc...
    ))

(def game-get-score [game]
    @(game :score))

(defn game-set-score [game new-score]
  (reset! (game :score) new-score))

(defn game-get-level [game]
  @(game :level))

(defn game-inc-level [game]
  (swap! (game :level) inc))

; etc...

我认为这肯定会向我目前使用的全局定义迈出一步。

那么这是推荐的方式吗?还是有更标准的 Clojure 方式?

更新

我目前正在使用 Clojure 1.1.0。

【问题讨论】:

  • 您始终可以在全局函数顶部使用“let”块,以将非公共函数保持在源文件中定义的范围内。试图将 C 的做事方式强加于像 Clojure 这样的函数式语言似乎是相当变态的 :-)
  • 您使用的是哪个版本的 Clojure?它改变了我们可以推荐的语言设施。

标签: clojure


【解决方案1】:

函数式编程的基本思想是全局变量很少,但大部分是局部变量(参见Rich Hickey's article on state and identity)。以这种范式编写游戏可能具有挑战性,我推荐this post on functional programming for games(不过,示例是用 Erlang 编写的)。

我不知道你想实现什么样的游戏。这是我将如何处理局部变量的代码 sn-p improv。

(defn play-game [name score blocks]
  (let [level (start-mission (:level score) blocks)]
    (if level
      (assoc score :level level)
      score)))

(defn the-whole-game []
  (let [name (ask-username)
        score (or (load-score name) {:level 0, :score 0}]
    (when-let [new-score (play-game name score [])]
       (save-score name new-score))))

您可能想查看another Tetris clone in clojure,不过它使用的是 opengl。

【讨论】:

  • 这是俄罗斯方块,请参阅我帖子中的链接。
  • 我没有仔细阅读。我相应地更新了我的答案。
【解决方案2】:

在我的 Clojure 游戏中,我使用一个包含地图的原子来存储我所有可变的游戏状态。这包括用户界面状态的某些元素。

目前定义如下:

(def state 
  (atom 
    {:game (gamefactory/make-game)
     :scroll [0 0]
     :mouseover [0 0]
     :command-state nil
     :commands (clojure.lang.PersistentQueue/EMPTY)
     :animations {}
     :player-id nil}))

这个模型对我来说效果很好。您可以轻松地直接访问状态元素,例如(:game @state),或者定义访问器函数。

【讨论】:

    【解决方案3】:

    您可以使用映射来模拟 C 风格的结构。你也可以使用(如果你使用的是 v1.2)你可以使用 deftype/defrecord。

    (defn get-game-score [game]
       (:score game))
    
    (defn set-game-store [game new-score]
       (assoc game :score new-score))
    

    我建议使用 Map esp。因为这些可以很容易地用于多种方法。
    要记住的最重要的事情是,您不应该像在 C 中那样考虑在 clojure 中使用变量,并且原子与变量不同。

    【讨论】:

    • 我目前使用的是 Clojure 1.1,但我会看看 devtype/devrecord 功能。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2012-12-10
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多