我正在尝试通过创建纸牌游戏来练习Python中的编程类。现在我想要实现的是让玩家从套牌中抽出一张牌。我的代码如下:
--allow-roo
播放器类:
class Deck():
def __init__(self):
#create the deck
self.deck = []
self.discard_pile = []
def create_deck(self):
#assign the number of cards for each type to a card (dict)
deck_stats = {"A":4, "B":6, "C":5, "D":5, "E":5, "F":5, "G":5, "H":5, "I":5, 'J':5}
for card in deck_stats.keys():
for i in range(0,deck_stats[card]):
self.deck.append(card)
return self.deck
def shuffle(self):
#randomise the deck or for when the shuffle card is played
random.shuffle(self.deck)
return self.deck
def pickup(self):
#picks up the first card on the draw pile
picked_up = self.deck.pop(0)
print(picked_up)
return picked_up
在Player类的class Player(Deck):
def __init__(self):
self.player_hand = ["defuse"]
for i in range(6):
self.draw_card()
def draw_card(self):
#draw pile reduces by one
deck = Deck()
deck.create_deck()
deck.shuffle()
self.player_hand.append(deck.pickup())
return self.player_hand
方法中,我从Deck类调用了draw_card()
方法。我认为这是错误的做法,但我不确定如何从Deck对象中提取卡。
此外,pickup
方法显然无法按预期的方式工作,因为它每次都会创建一个新的牌组,然后从新的牌组中拾取(至少我认为这是对的)现在)。这使我回到最初的问题,我如何让玩家从同一卡座中拾取一张纸牌,而不必每次都创建一个新卡座?
答案 0 :(得分:0)
尝试类似
class Deck():
def __init__(self):
# create the deck
self.discard_pile = []
self.deck = self.create_deck()
self.shuffle()
def create_deck(self):
deck = []
# assign the number of cards for each type to a card (dict)
deck_stats = {"A": 4, "B": 6, "C": 5, "D": 5, "E": 5, "F": 5, "G": 5, "H": 5, "I": 5, 'J': 5}
for card in deck_stats.keys():
for i in range(0, deck_stats[card]):
deck.append(card)
return deck
def shuffle(self):
# randomise the deck or for when the shuffle card is played
random.shuffle(self.deck)
return self.deck
def pickup(self):
# picks up the first card on the draw pile
picked_up = self.deck.pop(0)
print(picked_up)
return picked_up
class Player:
def __init__(self):
self.player_hand = ["defuse"]
self.deck = Deck()
for i in range(6):
self.draw_card()
def draw_card(self):
# draw pile reduces by one
self.player_hand.append(deck.pickup())
return self.player_hand