我正在尝试制作一个石头剪刀布游戏来帮助自己学习GNU Guile。我遇到了一个障碍,我得到了用户输入,玩家在游戏中的选择。如果我将其设置为字符串,则游戏可以正常工作。如果我使用(read)
我会从查找中返回 #f 作为类型。我尝试格式化读取以尝试使其成为字符串,但没有奏效。
(define (print a)
(display a)
(newline))
(define choices (make-hash-table 3))
(hashq-set! choices "r" "s")
(hashq-set! choices "s" "p")
(hashq-set! choices "p" "r")
(define (cpu-choice) (list-ref (list "r" "p" "s") (random 3)))
(print "You are playing rock paper scissors.")
(print "Type r for rock, p for paper, and s for scissors.")
(define draw
;; "s" ; This works as a test.
(read (open-input-string (read))) ; Can't get user in as string, so the hashq-ref will work.
)
(define cpu-draw (cpu-choice))
;; debug
(print (format #f "Player enterd ~a" draw))
(print (format #f "Player needs to with ~a" (hashq-ref choices draw))) ; Keeps coming back as #f
(print (format #f "CPU has entered ~a" cpu-draw))
;; norm
(newline)
(when (eq? draw cpu-draw)
(print "There was a tie")
(exit))
(when (eq? (hashq-ref choices draw) cpu-draw)
(print "You have won.")
(exit))
(print "You have failed. The computer won.")
如何从用户那里获取字符串?也许像(str (read))
或(read-string)
(读作字符串(。
$ guile --version
guile (GNU Guile) 2.0.13
更新
我只想提一下,虽然批准的答案是正确的,但我不明白 Guile/Scheme 在写这篇文章时是如何做字符串和符号的。我让程序工作的唯一方法是将choices
和cpu-choice
列表中的所有字符串更改为符号。前任:
(hashq-set! choices 'r 's)
(list 'r 'p 's)
谢谢奥斯卡·洛佩斯的帮助。
除非用双引号将输入括起来,否则键入的值将被解释为符号。试试这个:
(define str (read))
> "hello"
或者这个:
(define str (symbol->string (read)))
> hello
无论哪种方式,str
现在都将保存一个实际的字符串:
str
=> "hello"