Pulling a Card from the Deck
Now that we have the deck created, we can create a method to pull a card from the deck. We’ll use the pop method so that we can get an item and remove it from the deck at the same time:
16| self.deck.append( (value, suit) )
# ex: (7, "Hearts") ◽◽◽
18| # method to pop a card from deck using a random index value 19| def pullCard(self):
20| return self.deck.pop( randint(0, len(self.deck) – 1) )
22| game = Blackjack( )
23| game.makeDeck( )
25| print( game.pullCard( ), len(game.deck) ) # remove this line after
it prints out correctly
Go ahead and run the cell. You should get an output like “(7, ‘Hearts’) 51”. The tuple is our card that we printed out, while the 51 is proving to us that it’s removing a card from the deck. We set up the pullCard method so that it would pop a random card from the deck. It chooses randomly because of the arguments we passed into randint. The max number we want to allow is always one less than the size of the deck because indexing starts at zero. If the deck has 45 cards left in it, we want the random integer to be from 0 to 44. It then pops the item in that random index, removes it from the deck, and returns it back to where the method was called. Currently, we’re just printing it out, but later we’ll add it to a player’s hand. Be sure to remove the last line when you’re done, as the print statement is only being used for debugging purposes.
Creating a Player Class
With the game class working properly, we turn our focus to the player class. Let’s begin by creating the class definition to accept a name and set the hand to an empty list:
20| return self.deck.pop( randint(0, len(self.deck) – 1) ) ◽◽◽ 22| # create a class for the dealer and player objects 23| class Player( ):
24| def __init__(self, name):
25| self.name = name
26| self.hand = [ ]
28| game = Blackjack( )
29| game.makeDeck( )
31| name = input("What is your name?")
32| player = Player(name)
33| dealer = Player("Dealer")
34| print(player.name, dealer.name) # remove after working correctly
Go ahead and run the cell. We’ll get a printed statement of the name that was input, as well as “Dealer”. We define the player class to be initialized with the name and hand attribute. The name attribute is taken in as an argument, while hand is set directly inside of the class. After we instantiate the game object, we ask the user for their name and create an instance of the Player class with their input. The dealer object will always be known as “Dealer”, which is why we create the instance with that value being passed in during the instantiation.
Do'stlaringiz bilan baham: |