Question

In: Computer Science

PYTHON A Class for a Deck of Cards We will create a class called Card whose...

PYTHON

A Class for a Deck of Cards

We will create a class called Card whose objects we will imagine to be representations of playing cards. Each object of the class will be a particular card such as the '3' of clubs or 'A' of spades. For the private data of the class we will need a card value ('A', '2', '3', ... 'Q', 'K') and a suit (spades, hearts, diamond, clubs).

Before we design this class, let's see a very simple main() (also called the client, since it uses, or employs, our class) that instantiates a few Card objects and displays their values on the screen. We want to do a lot of fun things with our Card, but not yet. We start very carefully and slowly.

from enum import Enum


def main():
    card1 = Card()
    card2 = Card('5')
    card3 = Card('9', Suit.HEARTS)
    card4 = Card('j', Suit.CLUBS)
    card5 = Card('1', Suit.DIAMONDS)

    if not card2.set(2, Suit.CLUBS):
        print("GOOD: incorrect value (2 (int), CLUBS) passed to Card's set()\n")
    if not card2.set('2', Suit.CLUBS):
        print("BAD: incorrect value ('2', CLUBS) passed to Card's set()\n")

    print(str(card1) + "\n" + str(card2) + "\n" +
          str(card3) + "\n" + str(card4) + "\n"
          + str(card5) + "\n")

    card1 = card4

    # test assignment operator for objects
    print("after assigning card4 to card1:")
    print(str(card1) + "\n" + str(card4)
          + "\n")

We can't run this main() without embedding it into a full program that has the Card class definition, but let's look at a copy of the run anyhow, so we can see what the correct output for this program should be:

GOOD: incorrect value (2 (int), CLUBS) passed to Card's set()

(A of Spades)
(2 of Clubs)
(9 of Hearts)
(J of Clubs)
(A of Spades)

after assigning card4 to card1:
(J of Clubs)
(J of Clubs)

We can learn a lot about what class Card must be and do by looking at main() and the run. Let's make a list of things that we can surmise just by looking at the client.

  • We are instantiating several Card objects and sending a varying number of arguments to the constructor. For example, look at this code fragment:
   card1 = Card()
   card2 = Card('5')
   card3 = Card('9', Suit.HEARTS)
   card4 = Card('j', Suit.CLUBS)
   card5 = Card('1', Suit.DIAMONDS)

We see that card1 is instantiated with no arguments. This tells us that the class has a constructor (always __init__()) that does not require any arguments. Do you remember how that's done? Right! Either a default constructor (no formal parameters) or a constructor with all default parameters. So it must be one of those types.

However, we also see that card2 is providing the constructor with one argument and card3, card4 and card5 with two arguments. So, we must also have at least a 2-parameter constructor, and whatever number of parameters it has, they must all be default parameters (not counting the self parameter).  

  • Looking again at that same fragment, we see that those Card objects which are being instantiated with two arguments are supplying both a value and a suit:
       card3 = Card('9', Suit.HEARTS)
    The first argument, the value, is passed to the constructor as what data type? It is surrounded by quotes '5', '9', 'j', so it must be a string. (See Note On String Delimiters, below.) But the suit is a little odd. It is a construct like Suit.CLUBS or Suit.DIAMONDS with no quotes around it. Words without quotes in Python usually refer to variable names, but in this case, that's not what they are. Here we are using enumerated or enum types. You may not have had enums in your first course, so you will learn about them this week.
  • A set() method is used to assign values to a Card object, e.g., card1.set(2, clubs). Such instance methods are called mutators. This works the same way as a 2-parameter constructor but is used after, not during, the birth (construction) of the object. Furthermore, the set() method seems to be returning a bool value because we are treating the return value as if it were either True or False, e.g., if not card2.set(2, Suit.CLUBS)... . Apparently, this mutator method is returning a True if the assignment was successful and a False, otherwise.
  • By looking at the error message printed in the run, we can see that most ints (like 2) are not allowed to be passed to the constructor as the Card value. We have to pass a string, like '2', to represent the "deuce" (card with value '2'), for instance. The mutator method must be checking to make sure that the character passed in is between an ASCII '2' and an ASCII '9', or is one of the picture or ten Card characters 'A', 'K', 'Q', 'J', 'T'.  
  • It looks like a picture or 10 Card value passed in as a lower case char ('a','k', 'q', 'j', 't') is being up-cased (converted to upper case) by the mutator or constructor.
  • The assignment operator works as it should:  card1 = card4 assigns the object to which the reference card4 points to the reference card1, so that both references then point to the same object — a technique called aliasing. We'll prove this in a later version of the client today.
  • Finally, there is a __str__() instance method. In CS 3A, we learned that this is a special instance method that we write for most of our classes to help our clients use objects sometimes like strings(print( my_object)), and sometimes like primitive (immutable) types (print( "My object is" + str(my_object)) .

Solutions

Expert Solution

CODE IN PYTHON:

#importing enum
import enum
#creating enum using class
class Suit:
SPADES = "spades"
HEARTS = "hearts"
CLUBS = "clubs"
DIAMONDS = "diamonds"
#creating Card class
class Card:
#constructor with default values A of spades
def __init__(self,value="A",suit="spades"):
if(value=="1"):
self.__value = "A"
else:
self.__value = value
self.__suit = suit
#set method
def set(self,value,suit):
value = str(value)
flag = False
if(value == "A"):
falg = True
elif(value == "2"):
flag = True
elif(value == "3"):
flag = True
elif(value == "4"):
flag = True
elif(value == "5"):
flag = True
elif(value == "6"):
flag = True
elif(value == "7"):
flag = True
elif(value == "8"):
flag = True
elif(value == "9"):
flag = True
elif(value == "10"):
flag = True
elif(value == "J"):
flag = True
elif(value == "Q"):
flag = True
elif(value == "K"):
flag = True
if(flag):
self.value = value;
flag = False
if(suit == "spades"):
flag = True
elif(suit == "hearts"):
flag = True
elif(suit == "diamonds"):
flag = True
elif(suit == "clubs"):
flag = True
if(flag):
self.suit = suit
return True
else:
print("invalid suit input....")
return False
else:
print("invalid value input....")
return False
def getValue(self):
return self.value
def getSuit(self):
return self.suit
def __str__(self):
return self.__value + " of " + self.__suit

card1 = Card()
card2 = Card('5')
card3 = Card('9', Suit.HEARTS)
card4 = Card('j', Suit.CLUBS)
card5 = Card('1', Suit.DIAMONDS)
if not card2.set(2, Suit.CLUBS):
print("GOOD: incorrect value (2 (int), CLUBS) passed to Card's set()\n")
if not card2.set('2', Suit.CLUBS):
print("BAD: incorrect value ('2', CLUBS) passed to Card's set()\n")

print(str(card1) + "\n" + str(card2) + "\n" +str(card3) + "\n" + str(card4) + "\n"+ str(card5) + "\n")

card1 = card4

# test assignment operator for objects
print("after assigning card4 to card1:")
print(str(card1) + "\n" + str(card4)+ "\n")

INDENTATION:

OUTPUT:


Related Solutions

C++ Question Create a class for a card in a deck of playing cards. The object...
C++ Question Create a class for a card in a deck of playing cards. The object must contain methods for setting and retrieving the suit and the type of card (type of card meaning 2,3,4,5,6,7,8,9,10,J,Q,K,A). Separate the declaration of the class from its implementation by using the declaration in a header file and the implementation in a .cpp file. Also create a driver program and a makefile which complies the code and makes it able to run. This is more...
Write a class whose instances represent a single playing card from a deck of cards. Playing...
Write a class whose instances represent a single playing card from a deck of cards. Playing cards have two distinguishing properties: rank and suit. Use an enum type to represent rank and another enum type to represent suit. Write another class whose instances represent a full deck of cards. Both these classes should have toString methods. Write a small program to test your deck and card classes. The program can be as simple as creating a deck of cards and...
A five-card poker hand dealt from a standard 52-card deck of playing cards is called a...
A five-card poker hand dealt from a standard 52-card deck of playing cards is called a three-of-a-kind hand if it contains exactly three cards of the same rank (e.g. 3 aces and 2 other cards). How many distinct three-of-a-kind hands can be dealt with? Calculate a numeric answer.
C++ In this assignment you will use your Card class to simulate a deck of cards....
C++ In this assignment you will use your Card class to simulate a deck of cards. You will create a Deck class as follows: The constructor will create a full 52-card deck of cards. 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace for each suit: Clubs, Diamonds, Hearts, Spades Each card will be created on the heap and the deck will be stored using an STL vector of Card pointers. The destructor will free the...
Python Programming Write a simple implementation of a card deck to deal cards out randomly. Your...
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...
. If 2 cards are selected from a standard deck of cards. The first card is...
. If 2 cards are selected from a standard deck of cards. The first card is not replaced in the deck before the second card is drawn. Find the following probabilities: a) P(2 Aces) b) P(Queen of hearts and a King) c) P(Q of Hearts and Q of hearts )
We draw 6 cards from a 52 card deck and let X = the number of...
We draw 6 cards from a 52 card deck and let X = the number of heart cards drawn. a. What is the expected value of X? b. What is the variance of X? What is the standard deviation of X?
We have a poker deck of 52 cards. Abby randomly shuffles the card, and divides it...
We have a poker deck of 52 cards. Abby randomly shuffles the card, and divides it into 13 piles of 4 cards each. Use Hall marriage theorem to show that it is possible to pick a card from each pile, so that you get all 13 numbers from A to K.
Write a console application called PlayingCards that has 4 classes: PlayingCards, Deck, Cards, Card. This application...
Write a console application called PlayingCards that has 4 classes: PlayingCards, Deck, Cards, Card. This application will be able to create a deck of cards, shuffle it, sort it and print it. Use the following class diagrams to code your application. Use the following code for the PlayingCards class public class PlayingCards{ public static void main(String[] args){                 System.out.println("Playings Cards");                 Deck deck = new Deck();                 deck.create();                 System.out.println("Sorted cards");                 deck.sort();                 deck.showCards();                 System.out.println("Shuffled cards");                 deck.shuffle();...
A card is drawn at random from a deck of cards so that the chance of...
A card is drawn at random from a deck of cards so that the chance of getting any card is equally likely. Given that the card was either an A; 2; 3; 4; 5 or 6, what is the chance that either the card was red or that the card was a number card (2-10)?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT