Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created January 22, 2013 05:40
Show Gist options
  • Save SegFaultAX/4592392 to your computer and use it in GitHub Desktop.
Save SegFaultAX/4592392 to your computer and use it in GitHub Desktop.
Blackjack Clojure (Incomplete)
(ns blackjack.cards
[:use [clojure.string :only [join capitalize]]])
(def suits [:spades :hearts :clubs :diamonds])
(def ranks (range 1 14))
(def rank-names {1 "ace" 11 "jack" 12 "queen" 13 "king"})
(def new-deck (for [s suits r ranks] [s r]))
(defn shuffle-deck
([] (shuffle-deck new-deck 1))
([n] (shuffle-deck new-deck n))
([deck n] (nth (iterate shuffle deck) n)))
(defn format-card [[suit rank]]
(join \space [(capitalize (rank-names rank rank)) "of"
(capitalize (name suit))]))
(defn format-cards
([cards] (format-cards cards \newline))
([cards del] (join del (map format-card cards))))
(ns blackjack.game
[:use [blackjack.cards :as cards]])
(def scores {1 11, 11 10, 12 10, 13 10})
(defn- create-hands
"Helper function for creating a new set of player hands."
[players]
(into {} (for [p players] [p []])))
(defn new-game
"Initializes a new blackjack game."
[players]
{:dealer [],
:players players,
:hands (create-hands players),
:deck (cards/shuffle-deck 7)})
(defn score-card
"Returns the blackjack score for a single card."
[[suit rank]]
(scores rank rank))
(defn score-hand
"Calculates a score for a given hand based on casino scoring rules."
[hand]
(let [aces (count (filter cards/ace? hand))
score (reduce + (map score-card hand))]
(loop [score score aces aces]
(if (and (> score 21) (> aces 0))
(recur (- score 10) (dec aces))
score))))
(defn hand-type
"Determines if the hand is blackjack, twenty one, busted, or normal."
[hand]
(let [score (score-hand hand)
cnt (count hand)]
(cond (and (= score 21) (= cnt 2)) :blackjack
(= score 21) :twentyone
(> score 21) :busted
:else :normal)))
(defn normalize-hand
"Normalizes hand for sorting purposes."
[hand]
(let [scoring {:blackjack 100, :twentyone 50, :busted 0}
score (score-hand hand)
type (hand-type hand)]
(scoring type score)))
(defn compare-hands
"Compares two blackjack hands."
[a b]
(compare (normalize-hand a) (normalize-hand b)))
(defn- all-hands
"Generate a list of all hands (including dealer) in game."
[game]
(concat (for [p (:players game)] [:hands p]) [[:dealer]]))
(defn deal-card
"Deal a single card to a single hand."
[game hand]
(let [card (first (:deck game))
deck (next (:deck game))]
(merge (update-in game hand conj card) {:deck deck})))
(defn deal-cards
"Deal a fixed number of cards to all players (including dealer) in game."
[game per-player]
(if (> per-player 0)
(deal-cards
(reduce deal-card game (all-hands game))
(dec per-player))
game))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment