Problem 1: Simulating Blackjack In this problem we will use classes and functions to simulate a...

50.1K

Verified Solution

Question

Programming

Problem 1: Simulating Blackjack In this problem we will useclasses and functions to simulate a simplified game of Blackjack(21). The game begins with a standard deck of 52 playing cards (nojokers). Each player is dealt two cards to start with. The winnerof a hand of Blackjack is the player whose hand has the highestvalue without going over 21.

When calculating the value of a hand, we add up the rank of eachcard in the player's hand, where the numbered cards have ranks 2through 10. The face cards, Jack, King, and Queen, each add 10 tothe value of a player's hand. The Ace card can be treated as addingeither 1 or 11 to the value of the player's hand, depending uponwhich brings the player closer to winning.

Player's may request additional cards (a \"hit\") in order tobring the value of their hand closer to 21. However, if the valueof a player's hand rises above 21, then the player has \"busted\" andthey automatically lose the game.

In our simulation we are ignoring the distinction between playerand dealer. We are also ignoring betting, and so all the moresophisticated player actions (such as \"splitting\") are also beingignored. The behavior of player's is going to be fixed by a simplealgorithm. Details for writing the simulation program are givenbelow.

The program will consist of 4 classes: Card, Deck, Player,Blackjack. Each class represents objects that are elements of asimulated game of Blackjack. To implement each class you will haveto complete the implementation of the functions inside the body ofthe class definition. The names of the classes, the functions, andthe function parameters have already been given. DO NOT CHANGETHEM.

The Card class is meant to represent a single playing card. Ithas two attributes, suit and rank. Playing cards come in one offour suits: Hearts, Diamonds, Spades, and Clubs. In your program,each suit is represented by a string of a single capital letter:\"H\" for Hearts, \"D\" for Diamonds, \"S\" for Spades, and \"C\" forClubs. I have included a list of the suits as a global variable inyour program. For each suit there is a Card of one of 13 ranks.Each rank is represented by a string: \"2\" through \"10\" for theranks of the numbered cards, and \"J\", \"Q\", \"K\", and \"A\" for theJack, Queen, King, and Ace face Cards.

When a card is constructed the values for suit and rank shouldbe passed to the suit and rank attributes of the Card class. Youmust implement this in the __init__() function. You should checkthat the values passed to the Card constructor represent correctsuit and rank values.

The Deck class represents a standard deck of 52 playing cards.The Deck class should have a single attribute called cards. cardswill be a list of Card objects, one for each playing card thatmakes up a standard deck. In the __init__() function of the Deckclass you should create and add a Card object for each of the 52cards that make up a standard playing card deck. That is, for eachsuit there should be a Card of each rank added to the cards list inthe Deck class.

In addition to the __init__() method, you must also implement adeal_card() function. This function takes a single argument, anobject of the Player class. Inside the function you should removethe card from the top of the Deck (from the cards list of theDeck), and then add that card to the hand attribute inside thePlayer object. I have provided you with a function shuffle_deck()that will randomize the order of the cards inside cards list insidethe Deck object.

The function takes a single positive integer that represents howmany times the deck will be shuffled. The default value is 5. DONOT CHANGE THIS FUNCTION. The Player class represents theindividual players involved in a game of Blackjack. Each player hasthree attributes: name, hand, and status. The name attribute is astring that represents the Player's name. The hand attribute is alist that will contain the Card objects that make up the Player'shand.

The status attribute will hold a Boolean value and representswhether the Player is still playing. When you construct a Playerobject, you should set the Player's name to the string passed in asan argument, the hand attribute should be set to an empty list, andthe status attribute should be set to True. Once a Deck and Playerhave been instantiated, then you can deal cards to the Player fromthe Deck using the Deck's deal_card() function. If the Playerdecides to stay or busts during the game, then status will be setto False. In addition to __init__() function of the Player class,you must implement 2 other functions for Player objects.

The first function is called value(). It is used to calculatethe current value of the Player's hand. Use the rank of each Cardobject in the Player's hand to calculate the sum, by adding theranks together. Remember that the face cards, \"J\", \"Q\", and \"K\"each add 10 to the value of the Player's hand. Be very carefulabout Ace Cards. Remember that the Ace can add either 1 or 11 tothe value of the Player's hand depending upon thecircumstances.

The value() function should return the current total value ofthe Player's hand as an integer. The second function you mustimplement for the Player class is the choose_play() function. Thisfunction will determine whether the Player will hit—take anothercard—or stay—refuse cards if the Player is satisfied with thecurrent total value of their hand. In our simulation all Playerswill follow this strategy.

If the current total value of their hand is less than 17, thenthe Player will hit. Otherwise, the Player will stay. If the Playerdecides to stay, then their status attribute should be set toFalse. The choose_play() function should return the string, \"Hit\",if the Player decides to hit, and return the string, \"Stay\", if thePlayer decides to stay.

The last class you must implement is the Blackjack class. Thisclass represents a simulated game of Blackjack. Each Blackjackobject has two attributes: players and deck. The players attributeis a list of Player objects. This list of Player objects is passedto the __init__() function of the Blackjack class when constructinga new Blackjack object. The deck attribute should be assigned a newDeck object. You must do two other things in the __init__()function of the Blackjack class. You must shuffle the deck. Youmust then deal two cards to each of the Players.

You can assume that the list of Players passed to the Blackjackconstructor will always contain between 1 and 4 Player objects. Inaddition to the __init__() function of the Blackjack class, youmust also implement a function called play_game(). This is thefunction where game play will happen.

Gameplay should occur inside of a loop. The loop continues untilall of the Player's stop taking new cards. During each iteration ofthe loop you should do the following two things. First, for eachPlayer, check the status attribute of the Player. If their statusis True, then call the choose_play() function to determine whatthat Player will do. If choose_play() returns \"Hit\" for thatPlayer, then deal that Player a new card from the Blackjackdeck.

Then, check the value() of that Player's hand. If they have goneabove 21, then report that Player has busted (print a message) andset the Player's status attribute to False. If choose_play()returns \"Stay\" for the Player, then move on to the next Player.Second, for each Player check their status attribute. If statusattribute for all Players is set to False, then the game is doneand you can end the game play loop. Once the loop is complete, thenyou need to determine the winner.

The winner is the Player whose hand has the highest value lessthan or equal to 21. If there is a winner, print a messagereporting the winner of the game. If there is a tie, print amessage reporting the tie.

If there is no winner (if all the Players busted), then print amessage reporting that there is no winner. If you implement each ofthese classes and their functions correctly, then the test codeincluded in the file will run a simulated game of Blackjack withfour players.

Python Code So far

# DON'T CHANGE OR REMOVE THIS IMPORT
from random import shuffle

# DON'T CHANGE OR REMOVE THESE LISTS
# The first is a list of all possible card ranks: 2-10, Jack, King,Queen, Ace
# The second is a list of all posible card suits: Hearts, Diamonds,Clubs, Spades
ranks = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\",\"K\", \"A\"]
suits = [\"H\", \"D\", \"C\", \"S\"]

# This class represents an individual playing card
class Card():
def __init__(self, suit, rank):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

# DON'T CHANGE OR REMOVE THIS
# This function creates a string out of a Card for easyprinting.
def __str__(self):
return \"[\" + self.suit + \", \" + self.rank + \"]\"

# This class represents a deck of playing cards
class Deck():
def __init__(self):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE
  
# DON'T CHANGE OR REMOVE THIS
# This function will shuffle the deck, randomizing the order of thecards
# inside the deck.
# It takes an integer argument, which determine how many times thedeck is
# shuffled.
def shuffle_deck(self, n = 5):
for i in range(n):
shuffle(self.cards)

# This function will deal a card from the deck. The card shouldbe removed
# from the deck and added to the player's hand.
def deal_card(self, player):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

# DON\"T CHANGE OR REMOVE THIS
# This function constructs a string out of a Deck for easyprinting.
def __str__(self):
res = \"[\" + str(self.cards[0])
for i in range(1, len(self.cards)):
res += \", \" + str(self.cards[i])
res += \"]\"
return res

# This class represents a player in a game of Blackjack
class Player():
def __init__(self, name):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

def value(self):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

def choose_play(self):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

# DON'T CHANGE OR REMOVE THIS
# This function creates a string representing a player for easyprinting.
def __str__(self):
res = \"Player: \" + self.name + \"\n\"
res += \"\tHand: \" + str(self.hand[0])
for i in range(1, len(self.hand)):
res += \", \" + str(self.hand[i])
res += \"\n\"
res += \"\tValue: \" + str(self.value())
return res

# This class represents a game of Blackjack
class Blackjack():
def __init__(self, players):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

def play_game(self):
pass # REMOVE THIS AND REPLACE WITH YOUR CODE

# DON'T CHANGE OR REMOVE THIS
# This function creates a string representing the state of aBlackjack game
# for easy printing.
def __str__(self):
res = \"Current Deck:\n\t\" + str(self.deck)
res = \"\n\"
for p in self.players:
res += str(p)
res += \"\n\"
return res

# DO NOT DELETE THE FOLLOWING LINES OF CODE! YOU MAY
# CHANGE THE FUNCTION CALLS TO TEST YOUR WORK WITH
# DIFFERENT INPUT VALUES.
if __name__ == \"__main__\":
# Uncomment each section of test code as you finish implementingeach class
# for this problem. Uncomment means remove the '#' at the front ofthe line
# of code.
  
# Test Code for your Card class
#c1 = Card(\"H\", \"10\")
#c2 = Card(\"C\", \"A\")
#c3 = Card(\"D\", \"7\")

#print(c1)
#print(c2)
#print(c3)

print()

# Test Code for your Deck class
#d1 = Deck()
#d1.shuffle_deck(10)
#print(d1)

print()

# Test Code for your Player class
#p1 = Player(\"Alice\")
#p2 = Player(\"Bob\")
#d1.deal_card(p1)
#d1.deal_card(p2)
#print(p1.value())
#print(p2.value())
#d1.deal_card(p1)
#d1.deal_card(p2)
#print(p1.value())
#print(p2.value())
#d1.deal_card(p1)
#d1.deal_card(p2)
#print(p1.value())
#print(p2.value())
#print(p1)
#print(p2)
#print(p1.choose_play())
#print(p2.choose_play())

print()

# Test Code for your Blackjack class
#players = [Player(\"Summer\"), Player(\"Rick\"), Player(\"Morty\"),Player(\"Jerry\")]
#game = Blackjack(players)
#print(game)
#game.play_game()
#print(game)

Answer & Explanation Solved by verified expert
4.4 Ratings (630 Votes)
Here is the completed working code DONT CHANGE OR REMOVE THIS IMPORT from random import shuffle DONT CHANGE OR REMOVE THESE LISTS The first is a list of all possible card ranks 210 Jack King Queen Ace The second is a list of all posible card suits Hearts Diamonds Clubs Spades ranks 2 3 4 5 6 7 8 9 10 J Q K A suits H D C S This class represents    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students