Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hand and scoring #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/blackjack/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,15 @@

(defn play-hand [strategy hand opponent-up-card]
(cond (> (total hand) 21)
hand
hand

(strategy hand opponent-up-card) ; Asks 'should I hit?'
(recur strategy
(add-card hand (deal)) ; Recurs, adding a card
opponent-up-card)
(recur strategy
(add-card hand (deal)) ; Recurs, adding a card
opponent-up-card)

:else
hand))
hand))

(defn play-game [player-strategy house-strategy]
(let [house-initial-hand (new-hand)
Expand Down
23 changes: 18 additions & 5 deletions src/blackjack/hand.clj
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,21 @@
(conj hand card))

(defn total [hand]
(reduce + (map (fn [{:keys [rank]}]
(if (number? rank)
rank
10))
hand)))
(defn ace? [card]
(= :A (:rank card)))
(defn score [{rank :rank}]
(if (number? rank)
rank
10))
(let [aces (filter ace? hand)
subtotal
(->> hand
(remove ace?)
(map score)
(reduce + 0))]
(reduce (fn [score _]
(if (> (+ score 11) 21)
(+ score 1)
(+ score 11)))
subtotal
aces)))
4 changes: 2 additions & 2 deletions src/blackjack/simple_hand.clj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
(ns blackjack.simple-hand)

(defn deal []
(inc (rand-int 10)))
{:rank (inc (rand-int 10))})

(defn new-hand [] [(deal)])

Expand All @@ -12,4 +12,4 @@
(conj hand card))

(defn total [hand]
(reduce + hand))
(reduce + (map :rank hand)))
10 changes: 10 additions & 0 deletions test/blackjack/hand_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,13 @@
(testing "is 2 shuffled decks"
(is (= (set two-decks)
(set (concat full-deck full-deck)))))))

(deftest test-hand-total
(testing "sums hand when just number cards"
(is (= 17 (total [{:rank 5} {:rank 2} {:rank 10}]))))
(testing "face cards are 10"
(is (= 30 (total [{:rank :J} {:rank :Q} {:rank :K}]))))
(testing "ace is 11 when hand is small"
(is (= 15 (total [{:rank :A} {:rank 4}]))))
(testing "ace is 1 when hand is large"
(is (= 21 (total [{:rank :K} {:rank :A} {:rank 10}])))))