Frage

I am trying to write a game in Clojure using Quil.

(qc/defsketch sketch
  :title "My Game"
  :size [800 600]
  :setup #(qc/smooth)
  :draw draw
  :mouse-pressed mouse-pressed
  :key-pressed key-pressed)

(I can use (def position (atom 0)) and (swap! position inc) and @position to make a moving ball, but I have no idea how to scale this.)

Notice that I provide to the sketch a function for drawing (and input handlers). If I am just doing a quick sketch, one draw function is fine.

But in my game, I need to draw different things depending on whether the main menu, instructions, level selector, or game is the active view. Some of these (mainly the game view) need to have data associated with them that will be updated in each draw.

How can I go about this? The more I read about Clojure, the more confused I get. (Should each view be a record that satisfy a protocol? Should they be stored as atoms, or should their internal state be stored as atoms? Or should the game simulation state be a separate atom – except I don't want it taking up memory until the game view is activated ...) This would be so easy in OOP, but I want to learn functional programming.

Update

If you're interested in what I ended up doing, see Mini Pinions.

War es hilfreich?

Lösung

The blog post http://stevelosh.com/blog/2012/07/caves-of-clojure-02/ describes a design that I think would work well here. Game UIs are a stack (vector) of records. In that blog post they do not implement a protocol, instead a draw-ui multimethod dispatches on the kind of UI (main screen, instructions, etc.). However you can modify this as you please. The design uses records to model state.

Remember it is not always necessary to reach for a reference type (var, atom, ref, agent) to model state in Clojure.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top