0

I'm learning Python 2 and I'm trying to create a blackjack game using OOP. Can someone please let me know why I can't do hand.hit() twice after running the code below? It only works once. Why?

Also, can someone please let me know how I can calculate the actual value of a player's hand?

Thanks!

import random

rank = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
suit = ['Diamonds', 'Clubs', 'Hearts', 'Spade']

card_val = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':1}

class Card(object):

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        return str(self.rank) + ' of ' + str(self.suit)

    def grab_suit(self):
        return self.suit

    def grab_rank(self):
        return self.rank

    def draw(self):
        print(self.suit + self.rank)

class Deck(object):

    def __init__(self):
        self.cards = []    
        for i in rank:
            for j in suit:
                self.cards.append(Card(i,j))

    def __str__(self):
        return str([str(card) for card in self.cards])

    def shuffle(self):
        random.shuffle(self.cards)

    def deal(self):
        single_card = self.cards.pop()
        return single_card

deck = Deck()

class PlayerHand(object):

    def __init__(self):
        self.value = []

    def __str__(self):
        return str([str(card) for card in self.value])


    def hit(self):
        self.hit = self.value.append(deck.deal())
        return self.value

hand = PlayerHand()
paulnsn
  • 107
  • 2
  • 11

1 Answers1

0

Well the answer to the first question is pretty easy: You are overwriting your method with "None" (since self.value.append does not return anything).

So you need to change the line:

self.hit = self.value.append(deck.deal())  

To

self.value.append(deck.deal())

Calculating the actual value of the hand has been asked already on stackoverflow, therefore I will only answer the first part of the question.

Mathias Mamsch
  • 323
  • 1
  • 15
  • Thanks @Mathias. I don't understand why it is returning "None" when deck.deal() is something. Can you please elaborate? It is confusing because it worked the first time but not the second. Thanks! – paulnsn Sep 02 '17 at 23:07
  • In python you do not return a value from a function by assigning it to the function name (like for example in VB). You have a method "def self.hit():" and when you now do self.hit = 123 you will overwrite the method by the constant 123. So what your line is doing, is effectively removing the "hit" method from your class, that is why the second time you get an error. – Mathias Mamsch Sep 05 '17 at 06:09