aboutsummaryrefslogtreecommitdiff
path: root/mathslap-rec/mathslap-rec.clisp
blob: 86d607bd4aec6a5ec568f759a87b93da85c321fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
;;;; MathSlap program written by Larry Heyl - Game developed by Carl Heyl
;;;; To win make an equation with the supplied numbers, in order, adding any symbols you want but one and only one equal sign.
;;;; This version uses a recursive loop instead of LOOP.

;;;; concise instructions
(print "MathSlap")
(print "Hit Enter for another number. q and Enter to quit.")

(setq *random-state* (make-random-state t))

;;;; Generate a random number for our game. Avoid having to write the
;;;; same code several times.
(defun have-number ()
  (+ (random 10) 1))

;;;; append string parameter with a random number 1 through 10 and a space
(defun extend-prompt (o)
  (concatenate 'string o (write-to-string (have-number)) " "))

;;;; Same but with format, possibly more readable?
;; (defun extend-prompt (o)
;;   (format nil "~a~d " o (have-number)))

(defun recloop (o input)
  ;; Only recurse if the input is not "q"
  (unless (string= input "q")
    ;; Deal with the current state: output the prompt
    (print o)
    (finish-output)
    ;; Prepare the next prompt and collect input.
    ;; Use a LET form to use local variables
    (let ((prompt (extend-prompt o))
	  (new-input (read-line *standard-input*)))
      (recloop prompt new-input))))


;;;; Initiate the recursion
;; Use a LET* form for local variables, with defined variables depending on each other.
(let* ((starting-numbers (list (have-number) (have-number)))
       (starting-prompt (format nil "MathSlap ~{~a ~}" starting-numbers)))
  (recloop starting-prompt nil))