PlayingCards 0.2.0.0 → 0.3.0.0
raw patch · 2 files changed
+54/−5 lines, 2 filesdep +MonadRandomdep +random-shuffle
Dependencies added: MonadRandom, random-shuffle
Files
- PlayingCards.cabal +2/−2
- src/PlayingCards/Deck.hs +52/−3
PlayingCards.cabal view
@@ -2,7 +2,7 @@ -- documentation, see http://haskell.org/cabal/users-guide/ name: PlayingCards-version: 0.2.0.0+version: 0.3.0.0 synopsis: Playing cards api -- description: license: BSD3@@ -17,5 +17,5 @@ library exposed-modules: PlayingCards.Deck -- other-modules: - build-depends: base ==4.6.*, HUnit ==1.2.*, QuickCheck+ build-depends: base ==4.6.*, HUnit ==1.2.*, QuickCheck, random-shuffle, MonadRandom hs-source-dirs: src
src/PlayingCards/Deck.hs view
@@ -4,27 +4,43 @@ ace, king, queen, jack, ten, nine, eight, seven, six, five, four, three, two, dealCard,+ dealHands, containsCard, newDeck,+ shuffleDeck, cardsLeft) where +import Control.Monad+import Control.Monad.Random import Data.List+import System.Random.Shuffle import Test.QuickCheck data Deck = Deck [Card] deriving (Eq, Ord, Show) +type Hand = [Card]+ data Card = Flat Rank Suit- deriving (Eq, Ord, Show)+ deriving (Eq, Ord) +instance Show Card where+ show (Flat r s) = show r ++ show s+ card = Flat data Suit = Spades | Hearts | Diamonds | Clubs- deriving (Enum, Eq, Ord, Bounded, Show)+ deriving (Enum, Eq, Ord, Bounded) +instance Show Suit where+ show Spades = "s"+ show Hearts = "h"+ show Diamonds = "d"+ show Clubs = "c"+ spades = Spades hearts = Hearts diamonds = Diamonds@@ -43,8 +59,23 @@ | Four | Three | Two- deriving (Enum, Eq, Ord, Bounded, Show)+ deriving (Enum, Eq, Ord, Bounded) +instance Show Rank where+ show Ace = "A"+ show King = "K"+ show Queen = "Q"+ show Jack = "J"+ show Ten = "10"+ show Nine = "9"+ show Eight = "8"+ show Seven = "7"+ show Six = "6"+ show Five = "5"+ show Four = "4"+ show Three = "3"+ show Two = "2"+ ace = Ace king = King queen = Queen@@ -65,12 +96,30 @@ newDeck :: Deck newDeck = Deck newDeckCards +shuffleDeck :: (MonadRandom m) => Deck -> m Deck+shuffleDeck (Deck d) = liftM Deck (shuffleM d)+ cardsLeft :: Deck -> Int cardsLeft (Deck d) = length d dealCard :: Deck -> (Card, Deck) dealCard (Deck []) = error "Attempt to deal from empty deck" dealCard (Deck (c:rest)) = (c, Deck rest)++dealHands :: Int -> Int -> Deck -> ([Hand], Deck)+dealHands numHands cardsPerHand (Deck d) = case notEnoughCards of+ False -> (hands, remainingDeck)+ True -> error "Not enough cards to deal"+ where+ totalCardsInHands = numHands * cardsPerHand+ totalCards = cardsLeft (Deck d)+ notEnoughCards = (numHands > totalCards && cardsPerHand > 0) ||+ (cardsPerHand > totalCards && numHands > 0) ||+ totalCardsInHands > totalCards+ handCardsAndLeftovers = splitAt totalCardsInHands d+ remainingDeck = Deck $ snd handCardsAndLeftovers+ handCards = fst handCardsAndLeftovers+ hands = map (take cardsPerHand) $ take numHands $ iterate (drop cardsPerHand) handCards containsCard :: Card -> Deck -> Bool containsCard c (Deck d) = elem c d