Carp/examples/guessing.carp

52 lines
1.3 KiB
Plaintext
Raw Normal View History

2017-06-26 12:15:03 +03:00
;; The number guessing game
2017-09-06 11:05:19 +03:00
(use IO)
(use Int)
(use String)
2017-06-26 12:15:03 +03:00
(Project.config "title" "Guessing")
2017-12-24 07:05:33 +03:00
(def guessing true)
(def answer 0)
2018-01-03 23:52:34 +03:00
(defn start-new-game! []
(do (println "~ The Number Guessing Game ~")
(println "(Enter q to quit.)\n")
2017-12-24 07:05:33 +03:00
(set! guessing true)
(set! answer (random-between 1 100))
2017-12-24 07:05:33 +03:00
(print "Please enter a number between 1 - 99: ")))
(defn exit! []
(do (println "Good bye...")
(set! guessing false)))
2017-12-24 07:05:33 +03:00
(defn play-again? [user-input]
(if (= user-input "y\n") true false))
(defn correct! []
2018-01-03 23:52:34 +03:00
(do (println "Correct!\n")
2017-12-24 07:05:33 +03:00
(print "Play again? (y/n): ")
(let [user-input (get-line)]
(if (play-again? &user-input)
2018-01-03 23:52:34 +03:00
(start-new-game!)
2017-12-24 07:05:33 +03:00
(exit!)))))
(defn guess-again [low-or-high]
(do (println &(str* @"Too " @low-or-high @"."))
2017-12-24 07:05:33 +03:00
(print "\nPlease guess again: ")))
2017-06-26 12:15:03 +03:00
(defn main []
2018-01-03 23:52:34 +03:00
(do (println "Seeding random number generator...\n")
(Random.seed-from (Double.from-int (System.time)))
2018-01-03 23:52:34 +03:00
(start-new-game!)
2017-12-24 07:05:33 +03:00
(while guessing
(let [user-input (get-line)
guessed-num (from-string &user-input)]
(if (= &user-input "q\n")
(exit!)
(cond (< guessed-num answer) (guess-again "low")
(> guessed-num answer) (guess-again "high")
(correct!)))))))