Last active
December 22, 2015 13:28
-
-
Save virtualdogbert/6478813 to your computer and use it in GitHub Desktop.
This is for my SE GEEK video tutorials on YouTube: www.youtube.com/channel/UCHRADKRXZkPB6QVee0Q3GSQ
This file contains 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
/* | |
* A link to the SE GEEK video tutorial that references this code: | |
* http://www.youtube.com/watch?v=U07O3IsRvDI&feature=share&list=SPzerMl1XZ0X1KwRPzJwXMCUjtuzX2KkGr | |
* | |
* This is an expressive example of what you can do with groovy to get similar functionality to a post I saw in Java, which | |
* builds a deck and deals it out: | |
* http://www.nobigo.com/design-a-deck-of-playing-cards-deck-shuffling/#.UiuCbFGkiP- | |
* | |
* Now I know this design is not really reusable, but with some minor changes you can get it there, and still have few lines of | |
* code than the java example | |
* | |
* Java Example : 135(191 with comments) lines of code, Groovy Example 1: 19 lines of code, Groovy Example 2: 39 lines of code | |
*/ | |
//Groovy Example 1 | |
def suits = ["HEARTS","SPADES","DIMONDS", "CLUBS"] | |
def faceCards = ["Jack" ,"Quean", "King", "Ace"] | |
def cards = [] | |
suits.eachWithIndex{suit, value -> | |
def numberCards = 2..10 | |
numberCards.each{card -> | |
cards << [value:card, display:card, suit:suit, suitValue:value] | |
} | |
faceCards.eachWithIndex{card, suitValue -> | |
cards << [value:suitValue+11, display:card, suit:suit, suitValue:value] | |
} | |
} | |
Collections.shuffle(cards) | |
(1..52).each{ | |
println cards.pop() | |
} | |
//Groovy Example 2 | |
class Deck{ | |
def suits = ["HEARTS","SPADES","DIMONDS", "CLUBS"] | |
def faceCards = ["Jack" ,"Quean", "King", "Ace"] | |
def cards = [] | |
def discard = [] | |
Deck(){ | |
suits.eachWithIndex{suit, value -> | |
def numberCards = 2..10 | |
numberCards.each{card -> | |
cards << [value:card, display:card, suit:suit, suitValue:value] | |
} | |
faceCards.eachWithIndex{card, suitValue -> | |
cards << [value:suitValue+11, display:card, suit:suit, suitValue:value] | |
} | |
} | |
} | |
def shuffle(){ | |
Collections.shuffle(cards) | |
} | |
def resuffle(){ | |
cards.addAll(discard) | |
shuffle() | |
} | |
def dealCard(){ | |
discard << cards[-1] | |
cards.pop() | |
} | |
} | |
def deckOfCards = new Deck() | |
deckOfCards.shuffle() | |
(1..52).each{ | |
println deckOfCards.dealCard() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment