Solaxun
Solaxun

Reputation: 2792

Handling stdin Clojure

The below doesn't seem to work, but I'm not quite sure why. All move-board does is take in a 2D array and return a 2D array, rest of the code is all there. Basically I'm trying to accomplish something like the following python:

While True:
  do stuff
  if gameover:
    print("Game Over!")
    break

Clojure that isn't working (prints board once, asks for input, then hangs)

(defn game-loop [board]
  (loop [b board]
    (if (game-over? b) "Game Over!"
        (do (print-board b)
            (recur (move-board (read-line) b))))))

Upvotes: 1

Views: 386

Answers (1)

Micah Elliott
Micah Elliott

Reputation: 10264

We would need to see what your other functions are doing. I fabricated them minimally to what seems likely, and reindented to make the if-branch clearer. Your loop also was unnecessary.

(defn game-over? [b] false)
(defn print-board [b] (println b))
(defn move-board [ln b] (println "moving board:" ln))

(defn game-loop [b]
  (if (game-over? b)
    "Game Over!"
    (do (print-board b)
        (recur (move-board (read-line) b)))))

(game-loop :bored)

With those top three functions, your loop behaves as expected: prompting for a single line, infinitely. Well, at least the first time, but then your "hang" issue is reproduced.

This is likely being caused by this issue with the JVM. Also discussed here.

Upvotes: 2

Related Questions