📜  在Python中使用 OOPS 洗牌

📅  最后修改于: 2022-05-13 01:54:44.980000             🧑  作者: Mango

在Python中使用 OOPS 洗牌

先决条件: Python类和对象

给定一副牌,任务是在两个玩家之间分配它们。

方法:

  • 要洗牌,我们需要使用shuffle模块。
  • 导入需要的模块
  • 声明一个名为Cards的类,它将具有变量suitesvalues ,现在我们将不使用self.suitesself.values ,而是将它们声明为全局变量。
  • 声明一个类Deck ,它将有一个名为mycardset的空列表,并且套件将附加到mycardset列表中。
  • 声明一个ShuffleCards类以及一个名为shuffle()的方法,该方法将检查卡片的数量然后将它们洗牌。
  • 为了移除一些卡片,我们将在ShuffleCards类中创建一个popCard()方法。

以下是基于上述方法的完整程序:

Python3
# Import required modules
from random import shuffle
  
  
# Define a class to create
# all type of cards
class Cards:
    global suites, values
    suites = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
    values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
  
    def __init__(self):
        pass
  
  
# Define a class to categorize each card
class Deck(Cards):
    def __init__(self):
        Cards.__init__(self)
        self.mycardset = []
        for n in suites:
            for c in values:
                self.mycardset.append((c)+" "+"of"+" "+n)
  
    # Method to remove a card from the deck
    def popCard(self):
        if len(self.mycardset) == 0:
            return "NO CARDS CAN BE POPPED FURTHER"
        else:
            cardpopped = self.mycardset.pop()
            print("Card removed is", cardpopped)
  
  
# Define a class gto shuffle the deck of cards
class ShuffleCards(Deck):
  
    # Constructor
    def __init__(self):
        Deck.__init__(self)
  
    # Method to shuffle cards
    def shuffle(self):
        if len(self.mycardset) < 52:
            print("cannot shuffle the cards")
        else:
            shuffle(self.mycardset)
            return self.mycardset
  
    # Method to remove a card from the deck
    def popCard(self):
        if len(self.mycardset) == 0:
            return "NO CARDS CAN BE POPPED FURTHER"
        else:
            cardpopped = self.mycardset.pop()
            return (cardpopped)
  
  
# Driver Code
# Creating objects
objCards = Cards()
objDeck = Deck()
  
# Player 1
player1Cards = objDeck.mycardset
print('\n Player 1 Cards: \n', player1Cards)
  
# Creating object
objShuffleCards = ShuffleCards()
  
# Player 2
player2Cards = objShuffleCards.shuffle()
print('\n Player 2 Cards: \n', player2Cards)
  
# Remove some cards
print('\n Removing a card from the deck:', objShuffleCards.popCard())
print('\n Removing another card from the deck:', objShuffleCards.popCard())


输出: