Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Random) in Common Lisp Not So Random?

Okay, final question and I'll have finished my number guessing game in Common Lisp! :D Whenever the game starts (or a new game begins after the first game), the following function is called.

;;; 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)))

So supposedly, each time the player starts a game, *target* should be set to a new random integer between 1-100. However, each time, *target* defaults to 82. How do I make (random) act... randomly?

like image 307
Oso Avatar asked Oct 27 '10 13:10

Oso


1 Answers

You need to seed the random state at the start of the program.

(setf *random-state* (make-random-state t))
;; # this initializes the global random state by
;;   "some means" (e.g. current time.)
like image 54
kennytm Avatar answered Nov 10 '22 15:11

kennytm