我正在尝试使用OOP创建一个二十一点游戏,每当我调用二十一点或半身像功能时,它都会重新打印玩家和经销商的手牌价值。我认为它与Hand类被初始化有关,但我不确定那里的工作是什么。
Hand Class +变量的代码如下:
class Hand(object):
def __init__(self):
self.hand = []
def add_card(self, card):
self.hand.append(card)
return self.hand
def __str__(self):
hand = [str(card) for card in self.hand]
print 'Current hand is: ',hand
def get_value(self):
value = 0
for card in self.hand:
print(card)
value += card.value
for card in self.hand:
if card.card == 'Ace' and value > 21:
value -= 10
return value
def bust(self):
if self.get_value() > 21:
print ('Busted!')
else:
pass
def hit_or_stand(self):
self.hit = 'Hit'
self.stand = 'Stand'
self.prompter = raw_input('Would you like to hit or stand? ').lower()
return self.prompter
def show_hand(self):
for card in self.hand:
print(str(card))
def show_dealerHand(self):
print('Dealers Hand: '+ str(self.hand[0]) + ' ' + '[X]')
def blackjack(self):
self.bj = False
if self.get_value() == 21:
self.bj = True
print ('Blackjack!')
else:
pass
def dealerHit(self):
if self.get_value < 17:
self.add_card(card)
else:
pass
以下是运行游戏的主要功能:
def runGame():
player1 = Player()
deck1 = Deck()
playerHand = Hand()
dealerHand = Hand()
# deal out cards to player
i = 0
while i < 2:
playerHand.add_card(deck1.drawCard())
dealerHand.add_card(deck1.drawCard())
i += 1
playerHand.__str__()
dealerHand.show_dealerHand()
player_move = playerHand.hit_or_stand()
if player_move == playerHand.hit.lower():
playerHand.add_card(deck1.drawCard())
while dealerHand.get_value() < 17:
dealerHand.add_card(deck1.drawCard())
if playerHand.bust():
print('Dealer wins!')
elif dealerHand.bust():
print('Player wins!')
if playerHand.blackjack() and dealerHand.blackjack():
print('Both the Player and the Dealer have a blackjack!')
player1.winnings += player1.amount
elif playerHand.get_value() > dealerHand.get_value():
print('Player wins')
player1.winnings += player1.amount * 2
elif playerHand.get_value() < dealerHand.get_value():
print('Dealer wins')
player1.winnings -= player1.amount
答案 0 :(得分:1)
请注意bust
函数不返回任何内容:
def bust(self):
if self.get_value() > 21:
print ('Busted!')
else:
pass
但是,在主要内容中,您“获得”其返回值:
if playerHand.bust():
print('Dealer wins!')
elif dealerHand.bust():
print('Player wins!')
在这种情况下,你得到的是None
。所以这里发生的是playerHand.bust()
返回None,其值为False
。因此,elif dealerHand.bust()
也正在执行,这也是经销商的手也被打印的原因。
为了解决此问题,您必须根据需要返回True
或False
。