Created
January 26, 2013 21:27
-
-
Save manudatta/4644737 to your computer and use it in GitHub Desktop.
Chapter 5 keyboard exercise Craps game in clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;pg 151 | |
(defn throw-die [] (+ 1 (rand-int 6))) | |
(defn throw-dice [] (list (throw-die) (throw-die))) | |
(throw-dice) | |
(defn snake-eyes? [dice-throw] (= '(1 1) dice-throw)) | |
(snake-eyes? '(3 1)) | |
(defn boxcar? [dice-throw] (= '(6 6) dice-throw)) | |
(boxcar? '(6 6)) | |
; intro of let | |
(defn instant-win? [dice-throw] (let [dice-throw-sum (reduce + dice-throw)] (or (= 7 dice-throw-sum) (= 11 dice-throw-sum)))) | |
(instant-win? '(6 5)) | |
(instant-win? '(1 6)) | |
(instant-win? '(6 4)) | |
(defn instant-loss? [dice-throw] | |
(let [dice-throw-sum (reduce + dice-throw)] | |
(or (= 2 dice-throw-sum) (= 3 dice-throw-sum) (= 12 dice-throw-sum)))) | |
(instant-loss? '(1 1)) | |
(defn say-throw [dice-throw] | |
(cond | |
(snakeeyes? dice-throw) 'SNAKEEYES | |
(boxcar? dice-throw) 'BOXCAR | |
:else (reduce + dice-throw))) ; :else instead of (t ) lisp style | |
(say-throw (throw-dice)) | |
(defn craps [] | |
(let [dice-throw (throw-dice) val (say-throw dice-throw)] | |
(list 'Throw (first dice-throw) 'AND (second dice-throw) | |
'-- val '-- | |
(cond | |
(instant-win? dice-throw) "You win" | |
(instant-loss? dice-throw) "You lose" | |
:else (format "Your point is %d" val ))))) | |
(craps) | |
(defn try-for-point [n] | |
(let [dice-throw ( throw-dice) sum-dice (reduce + dice-throw)] | |
(list 'Throw (first dice-throw) 'AND (second dice-throw) | |
'-- sum-dice '-- | |
(cond | |
(= n sum-dice) "You win" | |
(= 7 sum-dice) "You lose" | |
:else "Throw again" | |
)))) | |
(try-for-point 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment