Question

In: Computer Science

2. Implement a drawing card game:using python 2.1 Build a class Card() that contains 2 variables:...

2. Implement a drawing card game:using python
2.1 Build a class Card() that contains 2 variables: rank and suits (10 points)

2.2 Build a Deck that contains 52 cards with ranks and suits. (20 points)
2.3 Two players will take turn to draw two cards from a shuffle decks. (30 points)
 You must implement a function call playerTurn(deck) to handle a player turn.
 playerTurn(deck) should include these features:


2.3.1 Draw 2 cards from the Deck created in 2.2
 2.3.2 Display ranks and suits of these cards


2.3.3 Return the sum of ranks of these cards. Notice that: ‘J’ = 11, ‘Q’ = 12, ‘K’ = 13, and ‘A’ = 1

2.4 The sum results will be compared between 2 players and who gets the larger in total will win that round. Notice that the game needs to keep track total number of player’s win round. (10 points)

2.5 Players have option to repeat as many times as they want. If the users choose ‘Y’, they will continue to draw from the original deck. (The deck will not be shuffled or added during the whole game. In other word, a card cannot be drawn twice during a game). (10 points)

Solutions

Expert Solution

'''

Python version : 2.7

Python program to simulate the game with standard deck of cards

'''

import random

# card class

class Card:

              

               # constructor

               def __init__(self, rank,suit):

                              self._rank = rank

                              self._suit = suit

              

               # returns the string representation of the card

               def __str__(self):

                              return 'Rank : '+str(self._rank)+' Suit : '+self._suit

              

               # returns the rank of the card

               def get_rank(self):

                              return self._rank

                             

               # returns the suit of the card       

               def get_suit(self):

                              return self._suit

# function to create and return shuffled deck of 52 cards                

def create_shuffled_deck():

              

               # define the valid suits and ranks

               suits = ['C','D','S','H']

               ranks = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']

              

               # create an empty deck

               deck = []

              

               # loop to populate the cards in the deck

               for i in range(len(suits)):

                              for j in range(len(ranks)):

                                             deck.append(Card(ranks[j],suits[i]))

              

               # shuffle the deck

               random.shuffle(deck)

               # return the deck

               return deck

                             

# function to return the points of a card

def getCardPoints(card):

              

               try:

                              rank = int(card.get_rank())

                              return rank

               except ValueError:

                             

                              if card.get_rank() == 'A':

                                             return 1

                              elif card.get_rank() == 'J':

                                             return 11

                              elif card.get_rank() == 'Q':

                                             return 12

                              else:

                                             return 13

# function to draw 2 cards from the deck, print the cards drawn and return the sum of the 2 cards                                

def playerTurn(deck):

              

               # draw 2 cards

               card1 = deck.pop(0)

               card2 = deck.pop(1)

              

               # print the cards

               print(card1)

               print(card2)

              

               # calculate the sum

               sum = getCardPoints(card1) + getCardPoints(card2)

              

               # return the sum

               return sum                        

# main function to simulate the game      

def main():

              

               # create a shuffled deck

               deck = create_shuffled_deck()

              

               # variables to store the wins of player1 and player2

               winsPlayer1 = 0

               winsPlayer2 = 0

              

               cont = 'y'

               # loop that will continue till the user wants or till deck is empty

               while(cont.lower() == 'y'):

                             

                              # check if deck is empty, then exit the game

                              if(deck != None and len(deck) == 0):

                                             print('Deck empty. Please start the program again')

                                             break

                              # draw cards for player 1

                              print('Player 1 cards: ')

                              player1 = playerTurn(deck)

                              # draw cards for player 2

                              print('Player 2 cards: ')

                              player2 = playerTurn(deck)

                             

                              # determine who won

                              if player1 > player2:

                                             print('Player 1 wins')

                                             winsPlayer1 += 1

                              elif player1 < player2:

                                             print('Player 2 wins')

                                             winsPlayer2 += 1

                              else:

                                             print("It's a tie")

                             

                              # prompt the user if he/she wants to play again

                              cont = raw_input('Do you want to play another round (y/n) ? ')

                              print('')

               # print the winnings of player 1 and player 2          

               print('Player1 won %d rounds' %(winsPlayer1))

               print('Player2 won %d rounds' %(winsPlayer2))

               print('Thank you for playing the game')

#call the main function  

main()   

#end of program

Code Screenshot:

Output:


Related Solutions

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...
For this assignment you will implement a dynamic array. You are to build a class called...
For this assignment you will implement a dynamic array. You are to build a class called MyDynamicArray. Your dynamic array class should manage the storage of an array that can grow and shrink. The public methods of your class should be the following: MyDynamicArray(); Default Constructor. The array should be of size 2. MyDynamicArray(int s); For this constructor the array should be of size s. ~MyDynamicArray(); Destructor for the class. int& operator[](int i); Traditional [] operator. Should print a message...
1. Implement the Vehicle class.  Add the following private instance variables to the Accoun class:...
1. Implement the Vehicle class.  Add the following private instance variables to the Accoun class: • An instance variable called wheelsCount of type int • An instance variable called vType of type String • An instance variable called isTruck of type boolean .  Add getters and setters for the three instance variables  Add the following methods to the Account class: • A void method called initialize that takes a parameter of type int, a String,and one double...
*in Java 1.Create a card class with two attributes, suit and rank. 2.In the card class,...
*in Java 1.Create a card class with two attributes, suit and rank. 2.In the card class, create several methods: a. createDeck – input what type of deck (bridge or pinochle) is to be created and output an array of either 52 or 48 cards. b.shuffleDeck – input an unshuffled deck array and return a shuffled one. + Create a swap method to help shuffle the deck c. countBridgePoints – inputs a 13-card bridge ‘hand’-array and returns the number of high-card...
Study the file polygon.h. It contains the header file for a class of regular polygons. Implement...
Study the file polygon.h. It contains the header file for a class of regular polygons. Implement the methods, and provide a driver to test it. It should be in C++ polygon.h file- #ifndef POLY_RVC_H #define POLY_RVC_H #include <iostream> using namespace std; class Polygon { public:    Polygon();    Polygon(int n, double l);    //accessors - all accessors should be declared "const"    // usually, accessors are also inline functions    int getSides() const { return sides; }    double getLength()...
Study the file polygon.h. It contains the header file for a class of regular polygons. Implement...
Study the file polygon.h. It contains the header file for a class of regular polygons. Implement the methods, and provide a driver to test it. It should be in C++ Write a polygon.h file with given instructions for the polygon.cpp file #include <iostream> #include <math.h> using namespace std; #ifndef M_PI # define M_PI 3.14159265358979323846 #endif int main() {    float areaP, length, sides;    cout << "\n\n Polygon area program.\n";    cout << "---------------------------------\n";    cout << " Enter the...
Working with arrays in our class, reinforce constructors and setters and getters and implement dynamic variables....
Working with arrays in our class, reinforce constructors and setters and getters and implement dynamic variables. Create a class called Movie that contains information about a movie. The class has the following attributes (you choose the data type for the member variables): ■ The movie name ■ The MPAA rating (for example, G, PG, PG-13, R) ■ Array of size 5 called Ratings, each index will hold the following. [0] The number of people that have rated this movie as...
Write a code to implement a python queue class using a linked list. use these operations...
Write a code to implement a python queue class using a linked list. use these operations isEmpty • enqueue. • dequeue    • size Time and compare the performances of the operations ( this is optional but I would appreciate it)
Create a UEmployee class that contains member variables for the university employee name and salary. The...
Create a UEmployee class that contains member variables for the university employee name and salary. The UEmployee class should contain member methods for returning the employee name and salary. Create Faculty and Staff classes that inherit the UEmployee class. The Faculty class should include members for storing and returning the department name. The Staff class should include members for storing and returning the job title. Write a runner program that creates one instance of each class and prints all of...
write the code in python Design a class named PersonData with the following member variables: lastName...
write the code in python Design a class named PersonData with the following member variables: lastName firstName address city state zip phone Write the appropriate accessor and mutator functions for these member variables. Next, design a class named CustomerData , which is derived from the PersonData class. The CustomerData class should have the following member variables: customerNumber mailingList The customerNumber variable will be used to hold a unique integer for each customer. The mailingList variable should be a bool ....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT