我自学Python 2并且我目前正在开发OOP Blackjack游戏。我想在类中正确引用一个变量,以便在另一个类中使用。到目前为止,我已经分配了d = Deck()
,p = PlayerHand()
,并使用d.deal()
处理了一张卡片,但我似乎无法执行p.hit()
。例外是告诉我变量single_card
未定义。
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
class PlayerHand(object):
def __init__(self):
self.value = []
def hit(self):
self.hit = self.value.append(single_card)
答案 0 :(得分:0)
在Blackjack的情况下,您可以定义一个持有Deck的经销商类和一个玩家列表
然后,在Deck课程中,或者最好在Dealer课程中,您可以处理PlayersHand
def deal(self, hand):
single_card = self.cards.pop() # or self.deck.deal()
if hand: # pass None to this function to draw without dealing
hand.value.append(single_card)
return single_card
d = Deck()
p = PlayerHand()
d.deal(hand)
或者,将牌组赋予Player类函数以使其绘制
答案 1 :(得分:0)
根据您当前的设计,您可以从Deck实例中获取单张卡片,并将该卡片传递给玩家的手动击打方法。
deck = Deck()
card = deck.deal()
hand = PlayerHand()
hand.hit(card)
并将PlayerHand.hit
更改为:
class PlayerHand(object):
...
def hit(self, card):
self.value.append(card)