On Sat, Jan 3, 2009 at 12:14 AM, Mark H. <mark.hoem...@gmail.com> wrote:
>
> On Jan 2, 5:39 pm, "Mark Volkmann" <r.mark.volkm...@gmail.com> wrote:
>> For anyone still following this, the latest code that incorporates
>> many of the suggestions I've received here is 
>> athttp://www.ociweb.com/mark/programming/ClojureSnake.html, replacing my
>> original version. It now uses refs. I think I have the dosyncs
>> optimally placed.
>
> I noticed that the new-game function which is called in a transaction
> does IO (it displays "You killed the snake!").  Transactions may be
> retried (see http://clojure.org/refs) so that message might get
> displayed more than once.  There's an "io!" macro (doesn't seem to be
> documented on the web page, but it's in core.clj in the Clojure source
> with a nice docstring) which serves only to help programmers avoid
> putting IO in their transactions -- it doesn't magically make IO work
> right in a transaction.  (Refs and transactions don't solve the
> problem that IO is inherently stateful and destructive -- Clojure
> relies on the IO system itself to handle that, which it should nicely
> in your case.)

What do you think of this way of resolving the issue? Note the use of
the local variable "message". That can get set to either "You win!" or
"You killed the snake!" inside dosync. Then outside dosync I check
that and call new-game only if it's set.

(defn process-move []
  (with-local-vars [message nil]
    (dosync
      (if (@snake :alive)
        (if (adjacent-or-same-cell? (snake-head) (@apple :cell))
        ; Use the next line instead to require collision with the apple.
        ;(if (= (snake-head) (@apple :cell))
          (do
            (ref-set apple (make-apple))
            (move-snake true)
            (if (= (snake-length) *length-to-win*)
              (var-set message "You win!")))
          (move-snake false))
        (var-set message "You killed the snake!"))))
    (if (var-get message) (new-game (var-get message)))))

-- 
R. Mark Volkmann
Object Computing, Inc.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to 
clojure+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to