In: Computer Science
Python Programming
Write a simple implementation of a card deck to deal cards out randomly. Your Deck class will contain a list of card objects. Initially, the deck will contain one instance of each of the 52 possible cards. Your deck should implement a deal() method that chooses a random location from the list and "pops" that card. You should also implement a cardsLeft method that tells how many cards are left in the deck.
Please type code and include screenshots of output of the code. Also code must be well commented.
Thanks for the question, here is the complete code screenshot and comments for this project. Have added detailed comments so that you can follow each line of code precisely.
Let me know in case you find anything unclear.
thanks a lot !
=====================================================================
# need this module to geenerate random number for the card
location
import random
# class Card
class Card():
# contains two variable one rank and one
suit name
def __init__(self, rank,
suit):
self.rank = rank
self.suit = suit
# returns the rank name
def getRank(self):
return self.rank
# returns the suit
def getSuit(self):
return self.suit
# when we print the card object we print the
full description of the card
def __str__(self):
rank_names =
{'2': '2', '3':
'3', '4': '4',
'5': '5', '6':
'6', '7': '7',
'8': '8', '9':
'9', 'T':
'Ten',
'J': 'Jack',
'Q': 'Queen',
'K': 'King',
'A': 'Ace'}
suit_names =
{'D': 'Diamond',
'S': 'Spades',
'C': 'Clubs',
'H': 'Heart'}
return
'{} of {}'.format(rank_names.get(self.rank),
suit_names.get(self.suit))
class Deck():
# class variables
suits = ['D',
'H', 'S',
'C']
ranks = ['2',
'3', '4', '5',
'6', '7', '8',
'9', 'T', 'J',
'Q', 'K',
'A']
def __init__(self):
self.cards = [] #
contains a list that will hold the Card object
# for each suit and for
each rank create an object of Card
# and append that to the
list
for suit in Deck.suits:
for rank in Deck.ranks:
card = Card(rank, suit)
self.cards.append(card)
# deal a random card
def deal(self):
# keep dealing until
we have a card in the list
if
len(self.cards) != 0:
# generate a random number between 0 and last index-1
location = random.randint(0, len(self.cards)-1)
# return the card at that index also removing the card from the
list at the same time
return self.cards.pop(location)
else:# if there are no card return None
return None
def cardsLeft(self):
return
len(self.cards)
# create an object of Deck class
deck = Deck()
# we are running aloop 1o times
for _ in range(10):
# in every iteration we deal one card from
the deck object
print('Card deal:
{}'.format(deck.deal()))
# we print the number of cards left in the
deck
print('Cards left:
{}'.format(deck.cardsLeft()))