2010-10-27 73 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