Carp/examples/guessing_game.carp

55 lines
1.4 KiB
Plaintext
Raw Permalink 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!)
2020-05-12 19:02:30 +03:00
(match guessed-num
(Maybe.Nothing) (print "Invalid input.\nPlease guess again: ")
(Maybe.Just n)
(cond (< n answer) (guess-again "low")
(> n answer) (guess-again "high")
(correct!))))))))