In this homework you are asked to create a simple game that is played as follows. The player is dealt cards one at a time from a shuffled standard deck of 52 cards. The sum of the card values is calculated at each round. Ace has value of 1, number cards have a value equal to the number on them (regardless of the suit) and face cards have a value of 10 each. The game goes on until the sum of player’s card values falls between 18 and 21 (inclusive) in which case the player wins, or exceeds 21, in which case the player loses.

You should write two classes for this homework.

The first one is called card. A card object represents a card and has two attributes: a number and a suit. We suggest the following attributes. The card number is an integer in the range [1, 2, ...., 13] (Ace=1, Jack=11, Queen=12, King=13) and the suit which is a number in the range [1, 2, 3, 4] (Spades=1,Hearts=2,Diamonds=3,Clubs=4). You could use a di↵erent set of attributes than these two integers, but using integers to designate different characteristics of an object is pretty standard. The card class should have a nice __str__ method, so when you create a card object and you print it you should get a nicely written description of the card.

The second class is called Game. The attributes of a Game object include two lists (and perhaps other attributes you deem necessary). Call the first attribute shuffled_deck; this is a list of card objects randomly created in a way that each of the cards appears exactly once. See below for one way to accomplish this. You can easily create an unshuffled deck of cards using two nested loops, especially if you use our suggestion for how to represent each individual card. The second attribute you need is a list that represents the player’s hand; you might call this attribute hand. Initially hand would be the empty list, indicating that when you create a game object you would want the player’s hand to be initially empty.

Then you should write a deal_card method for the Game class. The deal_card method gets one of the cards from shuffled_deck (maybe the first or last item in the list shuffled_deck), removes it and adds it to hand. So every time the deal_card method is called the game object is mutated: shuffled_deck loses a card and hand gets that very same card.

You will also need a status method for the game class. This function is used to determine the status of the game: has the player won, lost, or neither? One way to do this is to have status return an integer code for each possibility—e.g., −1 means the play has lost, 1 means the player has won, and 0 means the game is not over.

Finally there is the “driver” part of the code. In this part you define a method, called play. The play method interacts with the user to show the progress of the game. Remember that this game is very simple: the player does not get to choose whether or not to take a card, but rather cards are dealt to the user until s/he wins or loses. But to “slow down” the interaction a little, the driver should prompt the user (using raw_input) before dealing each card. The driver should also show the user her/his hand after each card. Once the game is over, the driver should ask the user whether s/he wants to play another game and either start a new game or end, as appropriate. Here is a session from a sample solution to this problem:

Hit to start playing the game.
Hit for another card.
Your hand: [’3-Diamonds’].
Your current score is 3.
Hit for another card.
Your hand: [’3-Diamonds’, ’2-Hearts’].
Your current score is 5.
Hit for another card.
Your hand: [’3-Diamonds’, ’2-Hearts’, ’6-Hearts’].
Your current score is 11.
Hit for another card.
Your hand: [’3-Diamonds’, ’2-Hearts’, ’6-Hearts’, ’10-Clubs’].
Your current score is 21.
You win!
Play again? y
Hit for another card.
Your hand: [’5-Clubs’].
Your current score is 5.
Hit for another card.
Your hand: [’5-Clubs’, ’6-Hearts’].
Your current score is 11.
Hit for another card.
Your hand: [’5-Clubs’, ’6-Hearts’, ’10-Spades’].
Your current score is 21.
You win!
Play again? y
Hit for another card.
Your hand: [’K-Spades’].
Your current score is 10.
Hit for another card.
Your hand: [’K-Spades’, ’5-Spades’].
Your current score is 15.
Hit for another card.
Your hand: [’K-Spades’, ’5-Spades’, ’2-Clubs’].
Your current score is 17.
Hit for another card.
Your hand: [’K-Spades’, ’5-Spades’, ’2-Clubs’, ’5-Diamonds’].
Your current score is 22.
You lose!
Play again? n

Additional thoughts
The __str__ method of Card. This method should print out a “nice” representation of the card, regardless of how you represent it. Even if you use our suggested fields (which are both numeric), then if c represents the Jack of Spades, str(c) should be something like Jack- Spades, or maybe Jack of Spades, or at least J-S. It should not be something like [11, 1], which is meaningless to the user. The code will probably be a little bit complicated, with some conditionals. However, there is a clever way to do this by making a couple of lists of strings; one is the list of strings corresponding to the card number, and the other is a list of strings corresponding to the suits.

the __init__ method of Game. The most straightforward way to implement the game class is for the __init__ method to create and shuffled deck and initialize the player’s hand to the empty list. If you do this, then your driver will have to create a new game object each time the player starts a new game.

However, there is an alternative. We usually think of there being one “game,” not many.

Think of a Game object as representing the table at which you are playing in the casino. When you want to play again, you don’t get a new table and dealer, you stay at the table, and the dealer just collects the cards, shuffles, and starts over. From this perspective, the Game class should have a method (maybe called start) that creates a deck, shuffles it, and sets the player’s hand to the empty list. Now when the player wants a new game, the driver program does not create a new Game object, but just calls the self.start method on the Game object it already has.

If you implement this approach, you will discover an oddity: your __init__ and start methods are identical! In this case, you really just want to have one method. The way to do this is to just implement the start method, which creates the shuffled deck and sets the player’s hand to empty. The __init__ method does nothing but call start. It doesn’t create any fields or initialize any of them. In other words, your __init__ method just invokes the start method on self.

Your Game class should have an __str__ method that returns a string looking llike this:

Your hand: ['K-Clubs', '7-Diamonds'].Your current score is 17.

But instead you may find that when you print a list of cards, you get ’[<__main__.Card instance at 0x7f536b40f5a8>,...]’

The problem is that even if you have a nice __str__ function for card, when you apply str to a list of cards, str is not applied to the cards themselves! Here is a bit of magic that will construct a string by applying str to each card in the hand: map(str, self.hand). For example, in our sample solution, whereas str(self.hand) produced the mess above, map(str, self.hand) returns the string [’K-Diamonds’, ’4-Clubs’, ’5-Spades’]

Randomly shuffling a list. For shuffling a list (of cards), you will find the random module very helpful. You can import the random module by adding import random

As always, we suggest you do this at the very top of the file. You will likely find the following extremely helpful: random.shuffle(lst) shuffles the list lst in place randomly; that is, after calling random.shuffle(lst), the elements of lst will be rearranged in a randomly-chosen order. Every time you call random.shuffle on the same list the list is reshuffled randomly. NOTE: random.shuffle is does not return a value! Noting this could save you valuable time and a lot of headache. Going further on randomization. The following IS NOT NEEDED for this homework.

Read only if you have the time and are interested in a little challenge. If you are curious how the random.shuffle works you might be able to implement it yourself! The basic idea is as follows. To shufflee a list lst, you can perform the following steps:

(1) Choose a random number i such that 0 <= i < len(lst), and swap lst[0] and lst[i].

(2) Choose a random number i such that 1 <= i < len(lst), and swap lst[1] and lst[i].

(3) Etc. That is, swap lst[j] with lst[i] for each j = 0, 1, . . . , len(lst) and randomly chosen i such that j ≤ i < len(lst).

Of course to do this, you need to be able to produce a randomly-chosen number in a given range. random.randint(m,n) returns a random number between m and n (including m and n). Note that this works differently from range(m,n) which does not include n.

Another way to shuffle a list is to remove a random member and put it in a new list, and keep on doing this until the original list is empty. Then return the new list. This is not a mutator. So you would have to reassign self.shuffled_deck to equal that output.

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

Classes, objects, and methods.

Problem 0: a card game (see the PDF file)
You may start with this skeleton. Remember that pass is just a do-nothing
instruction; it is present just so Python thinks you have a
syntactically-correct function definition for each method.

import random

class Card(object):

    def __init__(self, rank, suit):
       Create a card with the given rank and suit.
       self.rank = rank
       self.suit = suit
    def __str__(self):
       # You need to write a good __str__ function.
       rankNames = {1: 'A', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: 'J', 12: 'Q', 13: 'K'}
       suitNames = {1: 'Spades', 2: 'Hearts', 3: 'Diamonds', 4: 'Clubs'}
       return rankNames[self.rank] + '-' + suitNames[self.suit]

class Game(object):

    def __init__(self):
       Initialize a game with a shuffled 52-card deck and empy hand
       for the player.

    def start(self):
       #initialize the game the way you would usually do with init. The point
       #is to be able to call this method if the user wants to play again
       #in youe 'play' method below.
       self.shuffled_deck = []
       for rank in range(1,14):
            for suit in range(1,5):
                self.shuffled_deck.append(Card(rank, suit))
       self.hand = []

    def __str__(self):
       return str(map(str, self.hand))

    def deal_card(self):
       Move a card from the shuffled deck to the player's hand.
       if len(self.shuffled_deck) > 0:

    def score(self):
       The score of the player's hand is the sum of the ranks of the cards
       in the hand, where Ace = 1 and Jack = Queen = King = 10.
       handScore = 0
       for c in self.hand:
            if c.rank <= 10:
                handScore += c.rank
                handScore += 10
       return handScore

    def status(self):
          -1: player has lost (game over).
          0: player has neither won nor lost (game not over).
          1: player has won (game over).
       if self.score() < 18:
            return 0
       elif self.score() <= 21:
            return 1
            return -1

    def play(self):
       Play the game, reporting on its progress to the user and allowing the user
       to play another game for as long as s/he wishes.
       while True:
            raw_input("Hit <Enter> to start playing the game.")
            while self.status() == 0:
                raw_input("Hit <Enter> for another card.")
                print("Your hand: " + str(self))
                print("Your current score is " + str(self.score()) + ".")
            if self.status() == 1:
                print("You win!")
                print("You lose!")
            while True:
                again = raw_input("Play again? ").lower()
                if len(again) > 0:
                   if again[0] == 'n':
                   elif again[0] == 'y':

#To play a game uncomment the following:

g = Game()

# problem 1: class Car

Define a class called Car that
creates objects with
-- an x-position
-- a y position
-- an orientation (a float denoting an angle
   let the angle be in radians (but if you really want degrees
   use math.degrees(x) to convert x radians to degrees)
-- a speed (float) in miles per hour
Then define methods:
-- move(self,x,y): that moves the car to the point (x,y)
-- accel(self,factor): that adds factor to the speed (this accelerating or decelerating)
-- go(self,hrs): that moves the car where it would go in hrs hours. It has a speed and an orientation.
    so it knows where to go!
-- __str__ should give a nice string that informs of the speed and orientation and location
-- rotate(self,ang) which adds ang to current angle

class Car:

    def __init__(self, x, y, angle, speed):
       self.x = x
       self.y = y
       self.angle = angle
       self.speed = speed...

By purchasing this solution you'll be able to access the following files:

50% discount

$45.00 $22.50
for this solution

or FREE if you
register a new account!

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Python Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Upload a file
Continue without uploading

We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats