(随机)Common Lisp不是随机的吗?

And*_*ndy 14 lisp random sbcl common-lisp

好的,最后的问题,我将在Common Lisp完成我的猜数游戏!:D无论何时游戏开始(或者在第一场比赛后开始新游戏),都会调用以下函数.

;;; 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)))
Run Code Online (Sandbox Code Playgroud)

所以据说,每次玩家开始游戏时,*target*都应该设置为1-100之间的新随机整数.但是,每次都*target*默认为82.我如何(random)随机行动?

ken*_*ytm 26

您需要在程序开始时播种随机状态.

(setf *random-state* (make-random-state t))
;; # this initializes the global random state by
;;   "some means" (e.g. current time.)
Run Code Online (Sandbox Code Playgroud)

  • 评论不一定正确.CL规范并未强制要求使用当前时间,它只是说"通过某种方式随机初始化". (3认同)