this is the Deck class that works with the Card class we created earlier.
#Import the Card and the Random #classes from CardClass import Card import random class Deck: def __init__(self): #initialize the suits self.suits=["d","h","c","s"] #initialize the card list self.cards=[] #call the initializeDeck method self.initializeDeck() def initializeDeck(self): #this method populates the cards List #with cards #loop through the suits for i in range(1,4): suit=self.suits[i] #loop through the ranks for x in range(1,13): rank=x #create a card c=Card(rank,suit) #add to list of cards self.cards.append(c) def getDeck(self): #return a deck return self.cards def shuffleDeck(self): #suffle the deck randDeck=self.getDeck() random.shuffle(randDeck) return randDeck def deal(self,number): #get a shuffled deck self.newDeck=self.shuffleDeck() #create an empty list for the hand self.hand=[] #if there are more cards in the deck #than the number requestd if number < len(self.newDeck): #get that number of cards #and put them in the hand list for i in range(number): self.hand.append(self.newDeck[i]) #remove those cards from the #suffled deck for c in self.hand: self.newDeck.remove(c) #return the hand return self.hand
here is the code to test the deck:
from Deckclass import Deck d=Deck() numberOfHands = 3 for i in range(1, numberOfHands +1): hand=d.deal(5) for c in hand: print("hand " + str(i),c)
Here are the results
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ====== RESTART: C:/Users/sconger/Documents/Python Programs/TestDeck.py ====== hand 1 3 of spades hand 1 3 of clubs hand 1 8 of spades hand 1 the ace of clubs hand 1 the queen of spades hand 2 4 of clubs hand 2 8 of clubs hand 2 8 of hearts hand 2 the jack of spades hand 2 the ace of spades hand 3 7 of clubs hand 3 10 of spades hand 3 9 of spades hand 3 5 of clubs hand 3 10 of hearts >>>
No comments:
Post a Comment