簡體   English   中英

使用Python類創建紙牌游戲

[英]Creating a card game with Python classes

我正在嘗試通過創建一個紙牌游戲來練習Python中的編程類。 現在我想要實現的是讓玩家從套牌中抽出一張牌。 我的代碼如下:

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

和播放器類:

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

在Player類的draw_card()方法中,我從Deck類中調用了pickup方法。 我認為這是錯誤的做法,但是我不確定如何從Deck對象中拾取卡。

此外, draw_card方法顯然不能按照預期的方式工作,因為它每次都會創建一個新的牌組,然后從新牌組中獲取(至少我認為它正在做的事情)。 這讓我回到原來的問題,如何讓玩家從同一個Deck中取出一張卡片,這樣我每次都不需要創建新的Deck?

嘗試類似的東西

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM