15

さて、最後の質問です。CommonLispでの数字推測ゲームを終了します。: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)))

したがって、おそらく、プレーヤーがゲームを開始するたびに、*target*1〜100の新しいランダムな整数に設定する必要があります。ただし、毎回、デフォルトで82になります。ランダムに行動*target*させるにはどうすればよいですか?(random)

4

2 に答える 2

30

プログラムの開始時にランダムな状態をシードする必要があります。

(setf *random-state* (make-random-state t))
;; # this initializes the global random state by
;;   "some means" (e.g. current time.)
于 2010-10-27T14:04:12.780 に答える
0

乱数を使って関数を定義すると、関数を呼び出したときに呼び出されないのではないかと思います。実際には、ファイルを読み込んだときに決定され、この定義を実行するとその値に固定されます。次に、毎回関数を呼び出すと、番号は常に同じになります。呼び出されるたびにランダムに変数を関数に渡したとき、それは毎回ランダムでした。少なくとも、それは私のプログラムで経験したことです

于 2018-04-16T02:51:03.687 に答える