I'm trying to simulate the dealer of a game of blackjack, and I'm really confused.
Basically, I'm using a deck of cards that only consists of J, Q, K, A, and 2-10 to simplify this stuff, rather than using an ordinary card deck setup.
I realize all of this is pretty messy, I've been working with classes for all of 3 hours.
class Deck:
'''Simulates a deck of cards.'''
def __init__(self):
'''Deck() -> Deck
Creates a deck of cards'''
self.Deck = ['J', 'J', 'J', 'J', 'Q', 'Q', 'Q', 'Q', 'K', 'K', 'K', 'K', 'A', 'A', 'A', 'A', '2', '2', '2', '2', '3', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '6', '6', '6', '6', '7', '7', '7', '7', '8', '8', '8', '8', '9', '9', '9', '9', '10', '10', '10', '10']
def __str__(self):
'''str(Deck) -> str
Returns string showing number of cards left'''
output = str(len(self.Deck)) + ' cards'
return(output)
def shuffle(self):
'''shuffle(self) -> Deck
Shuffles deck.'''
import random
random.shuffle(self.Deck)
def draw(self):
if len(self.Deck) > 0:
return(self.Deck.pop(0))
else:
return(-1)
def add(self, card):
self.Deck.append(str(card))
class BlackJackPlayer(Deck):
'''Represents someone playing blackjack.'''
def __init__(self, Deck):
self.BlackJackPlayer = Deck
self.hand = ''
self.value = 0
def __str__(self):
return self.hand
def clean_up(self):
self.BlackJackPlayer = Deck
self.hand = ''
self.value = 0
def get_value(self):
for x in self.hand:
if x != ',':
if x not in range(1, 11):
if x != 'A':
self.value += 10
else:
if (self.value + 11) > 17:
self.value += 1
else:
self.value += 11
else:
self.value += x
return(self.value)
def hit(self):
Deck.shuffle(self.BlackJackPlayer)
card = Deck.draw(self.BlackJackPlayer)
return(card)
def play_dealer(self):
while BlackJackPlayer.get_value(self) < 17:
self.hand += BlackJackPlayer.hit(self)
print(self.hand)
if BlackJackPlayer.get_value(self) < 17:
self.hand += ','
if BlackJackPlayer.get_value(self) > 21:
return('BUST')
else:
return
For some reason, whenever I call jack.play_dealer(), it'll stop too early because it thinks the hand is already over 21.
For example:
>>> deck = Deck()
>>> jack = BlackJackPlayer(deck)
>>> jack.play_dealer()
7
'BUST'
>>> jack.get_value()
40
I'm guessing something's wrong with my get_value(), but I can't figure it out.
Thanks in advance!
BlackJackPlayer.get_value(self)instead of the more usualself.get_value()? e.g. why use unbound methods instead bound methods on the instance? - Martijn PietersDeckinstances aDeckattribute, and theBlackJackPlayerinstances aBlackJackPlayerattribute, the latter being aDeckinstance. - Martijn Pieters