2011-05-02 37 views
5

我正在開發我的第一個合適的Clojure程序 - 一個象棋遊戲。我有以下幾點:Clojure的(讀線)返回零;不提示

(defn human-move [board] 
    (board-utils/print-board board) 
    (print "Enter your move, like this: 'E7 E5' ...") 
    (loop [raw-move (terminal-input)] ;;(read-line)] 
    (println "I just received" raw-move) 
    (if (re-matches #"[A-H][1-8]\s[A-H][1-8]" raw-move) 
     (parse-move raw-move) 
     (do 
     (println "Invalid format! There should be a letter, number, space, letter, and final number.") 
     (print "Try again: ") 
     (recur (read-line)))))) 

記下read-line被註釋掉和terminal-input替代的地方。 read-line是給我一個NullPointerException,因此用於診斷目的:

(defn terminal-input [] 
    (println "input") 
    (let [whatnot (read-line)] 
    (println "received" whatnot) 
    whatnot)) 

然後,當我打電話human-move

... 
+---+---+---+---+---+---+---+---+ 
| P | P | P | P | P | P | P | P | 
+---+---+---+---+---+---+---+---+ 
| R | N | B | Q | K | B | N | R | 
+---+---+---+---+---+---+---+---+ 
Enter your move, like this: 'E7 E5' ...input 
received nil 
I just received nil 

我從來沒有機會鍵入輸入內容。如果是Java,我會開始與垃圾收集器(例如Scanner.next())一起玩小遊戲,但在Clojure中,除了將(flush)放在那裏之外,我不知道該做什麼。

這是SLIME的價值。


我也試過有terminal-input提供虛擬數據,並得知我顯然使用loop/recur不正確。儘管如此,我還沒有調查過它,因爲我一直在分析read-line問題。

在此先感謝。

回答

8

這將自吹,Clojure的1.4.0-SNAPSHOT現在的工作,如果你換行調用read-線swank.core /與讀取線支持這樣

(with-read-line-support (println "a line from Emacs:" (read-line)) 

https://github.com/technomancy/swank-clojure/commit/f4a1eebc4d34f2ff473c4e5350f889ec356f5168

+0

順便說一句,我也添加了從minibuffer和y-or-n-p的支持。 – 2012-01-11 17:32:41

+0

這真的很棒。我期待着有一個理由嘗試這個。 – amalloy 2012-01-11 18:41:42

9

read-line在SLIME中不起作用。我無法找到關於此的討論主題,但這是事實。

+1

+1「但它是真實的」。 – ponzao 2011-05-02 20:25:20

+0

Thud。呃...有一些解決方法嗎?用Java的Scanner類玩遊戲會值得嗎? – tsm 2011-05-02 22:11:53

+0

看看http://stackoverflow.com/questions/3790889/clojure-lein-read-line-stdin-woes - 有點舊,但可能仍然有幫助。 – amalloy 2011-05-02 23:37:46

0

最後這個工作對我來說:

(swank.core/with-read-line-support 
    (read-line))