2010-10-27 109 views
12

好吧,最後一個問題,我會用Common Lisp完成我的猜數字遊戲! :D每當遊戲開始時(或者第一次遊戲後開始新遊戲),就會調用以下函數。(Random)in Common Lisp Not So Random?

;;; Play the game 
(defun play() 
    ;; If it's their first time playing this session, 
    ;; make sure to greet the user. 
    (unless (> *number-of-guesses* 0) 
     (welcome-user)) 
    ;; Reset their remaining guesses 
    (setq *number-of-guesses* 0) 
    ;; Set the target value 
    (setq *target* 
     ;; Random can return float values, 
     ;; so we must round the result to get 
     ;; an integer value. 
     (round 
      ;; Add one to the result, because 
      ;; (random 100) yields a number between 
      ;; 0 and 99, whereas we want a number 
      ;; from 1 to 100 inclusive. 
      (+ (random 100) 1))) 
    (if (eql (prompt-for-guess) t) 
     (play) 
     (quit))) 

所以按說,每個玩家開始遊戲時,*target*應設置爲1-100之間的一個新的隨機整數。但是,每次,*target*默認爲82.我如何使(random)行爲......隨機?

回答

24

您需要在程序開始時播種隨機狀態。

(setf *random-state* (make-random-state t)) 
;; # this initializes the global random state by 
;; "some means" (e.g. current time.) 
+3

該評論不一定正確。 CL規範沒有規定使用當前時間,它只是說「通過某種方式隨機初始化」。 – Svante 2010-10-27 17:29:41

+0

@Svante:是的,你說得對。更新。 – kennytm 2010-10-27 17:33:26