刚刚那个代码有报错ValueError: not enough values to unpack (expected 3, got 2),修改刚刚那个代码
时间: 2023-11-17 17:45:32 浏览: 67
好的,请尝试以下修改后的代码:
```python
import random
class Card():
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __repr__(self):
return "{} of {}".format(self.value, self.suit)
class Deck():
def __init__(self):
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
self.cards = [Card(suit, value) for suit in suits for value in values]
def shuffle(self):
if len(self.cards) > 1:
random.shuffle(self.cards)
def deal(self):
if len(self.cards) > 1:
return self.cards.pop(0)
class Hand():
def __init__(self):
self.cards = []
def add_card(self, card):
self.cards.append(card)
def get_value(self):
value = 0
num_aces = 0
for card in self.cards:
if card.value.isnumeric():
value += int(card.value)
elif card.value in ["J", "Q", "K"]:
value += 10
elif card.value == "A":
num_aces += 1
value += 11
for i in range(num_aces):
if value > 21:
value -= 10
return value
class Game():
def __init__(self):
self.player_hand = Hand()
self.dealer_hand = Hand()
self.deck = Deck()
self.deck.shuffle()
def deal_initial_cards(self):
self.player_hand.add_card(self.deck.deal())
self.dealer_hand.add_card(self.deck.deal())
self.player_hand.add_card(self.deck.deal())
self.dealer_hand.add_card(self.deck.deal())
def player_turn(self):
while self.player_hand.get_value() < 21:
print("Your hand: {}".format(self.player_hand.cards))
choice = input("Do you want to hit or stand? ")
if choice.lower() == "hit":
self.player_hand.add_card(self.deck.deal())
elif choice.lower() == "stand":
break
def dealer_turn(self):
while self.dealer_hand.get_value() < 17:
self.dealer_hand.add_card(self.deck.deal())
def get_winner(self):
player_value = self.player_hand.get_value()
dealer_value = self.dealer_hand.get_value()
if player_value > 21:
return "Dealer"
elif dealer_value > 21:
return "Player"
elif player_value > dealer_value:
return "Player"
elif dealer_value > player_value:
return "Dealer"
else:
return "Tie"
def play(self):
self.deal_initial_cards()
self.player_turn()
if self.player_hand.get_value() <= 21:
self.dealer_turn()
winner = self.get_winner()
print("Player's hand: {}".format(self.player_hand.cards))
print("Dealer's hand: {}".format(self.dealer_hand.cards))
print("Winner: {}".format(winner))
game = Game()
game.play()
```
修改后的代码将会正常运行,不会再出现 Value Error。
阅读全文