简体   繁体   English

Python简单的纸牌游戏来学习课程

[英]Python Simple Card Game to Learn Classes

I am trying to create a simple card game to better understand OOP and classes. 我正在尝试创建一个简单的纸牌游戏,以更好地了解OOP和类。

The game is as follows: Two cards are dealt from a deck. 游戏如下:从牌组发出两张牌。 Then a third card is dealt. 然后发出第三张牌。 If the third card is between the first two cards, then the player wins. 如果第三张牌位于前两张牌之间,则玩家获胜。 If the third card is equal to either of the first two cards, or is outside of the set, then the player loses. 如果第三张牌等于前两张牌中的任何一张,或者在该牌组之外,则该牌手输了。

This is what I have so far: 这是我到目前为止:

class Deck(object):
    def __init__(self):
        self.deck = []

    def PopulateDeck(self):
        suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
        for suit in suits:
            for rank in range(2, 15):
                if rank == 11:
                    value = "Jack"
                elif rank == 12:
                    value = "Queen"
                elif rank == 13:
                    value = "King"
                elif rank == 14:
                    value = "Ace"

                self.deck.append(str(value) + " of " + suit)

class Card(object):
    def __init__(self, rank, value):
        self.rank = rank
        self.value = value
        self.card = self.rank + self.value

I am having a difficult time with classes and OOP, and I'm not sure if this is a good start, or where I should go next. 我在课堂和OOP上遇到了困难,我不确定这是一个好的开始,还是我应该去哪里。 Much of this was created by reading other sources and examples. 其中大部分是通过阅读其他来源和示例创建的。 Can anyone please provide advice on what other classes I may want to make to run my game, and how those classes may interact with/inherit from each other? 任何人都可以提供关于我可能想要运行我的游戏的其他课程的建议,以及这些课程如何与彼此互动/继承? Thank you. 谢谢。

This is more of a code/approach review. 这更多的是代码/方法审核。 A card game is a case for composition, not inheritance; 纸牌游戏是一种组合而非继承的案例; the Deck contains Card s, but isn't in itself a type of Card , and vice versa. Deck包含Card ,但本身不是Card ,反之亦然。

I think you are duplicating information in the Card . 我认为你正在复制Card信息。 Just store suit and rank, and use __str__ to create 'x of y' . 只需存储套装和等级,然后使用__str__创建'x of y' You can also implement the rich comparison methods : 您还可以实现丰富的比较方法

class Card(object):

    FACES = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}

    def __init__(self, rank, suit):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        value = self.FACES.get(self.rank, self.rank)
        return "{0} of {1}".format(value, self.suit)

    def __lt__(self, other):
        return self.rank < other.rank

Now eg str(Card(13, 'Clubs')) == "King of Clubs" . 现在例如str(Card(13, 'Clubs')) == "King of Clubs" This way you don't duplicate the rank and value in card . 这样您就不会复制cardrankvalue

Next, I think the Deck should incorporate the population generation in __init__ ; 接下来,我认为Deck应该将人口生成纳入__init__ ; you can provide optional arguments for a non-standard deck. 您可以为非标准套牌提供可选参数。 I have included two implementations; 我已经包含了两个实现; the commented-out version is a list comprehension using itertools to do the same job in one line. 注释掉的版本是一个列表理解,使用itertools在一行中完成相同的工作。 I also provide a function to pick n different random cards from self.deck . 我还提供了一个从self.deck选择n不同随机卡的self.deck

from itertools import product 
import random

class Deck(object):

    def __init__(self, ranks=None, suits=None):
        if ranks is None:
            ranks = range(2, 15)
        if suits is None:
            suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
##        self.deck = [Card(r, s) for r, s in product(ranks, suits)]
        self.deck = []
        for r in ranks:
            for s in suits:
                self.deck.append(Card(r, s))

    def deal(self, n):
        return random.sample(self.deck, n)

Now the game is simple; 现在游戏很简单; you can deal three cards per hand, and compare the cards naturally (using eg < ) because of the comparison methods. 您可以每手处理三张牌,并且由于比较方法,自然地比较牌(使用例如< )。

deck = Deck()
hand = deck.deal(3)
print(" - ".join(map(str, hand)))
if min(hand[0], hand[1]) < hand[2] < max(hand[0], hand[1]):
    print("Winner!")
else:
    print("Loser.")

As @tobias_k have pointed out in the comments + some of my thoughts 正如@tobias_k在评论中指出的那样+我的一些想法

class Deck(object):
    def __init__(self):
        self.deck = []
        self.dealt = [] #Prevents from dealing the same card

    def PopulateDeck(self):
        suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
        for suit in suits:
            for rank in range(2, 15):
                if rank == 11:
                    value = "Jack"
                elif rank == 12:
                    value = "Queen"
                elif rank == 13:
                    value = "King"
                elif rank == 14:
                    value = "Ace"
                else:
                    value = str(rank)

                self.deck.append(Card(value, suit))

    def deal(self):
        #Randomly select card
        remaining_cards = [card for card in self.deck if card not in self.dealt]
        card_index = random.randrange(0, len(remaining_cards)-1)
        card = remaining_cards[card_index]
        self.dealt.append(card)
        return card



    def shuffle(self):
        self.dealt = []

class Card(object):
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
        self.card = str(self.rank) + " " + str(self.suit)
    def __eq__(self, other):
        return self.rank == other.rank and self.suit == other.suit

def play():
    deck = Deck()
    card1 = deck.deal()
    card2 = deck.deal()
    card3 = deck.deal()

#And here you will compare the cards to see if the player wins or not. Not sure 
#what exact criterion you're using.

deck.shuffle() #And leave your deck nicely shuffled for next game

play()

Random documentation 随机文档

I have not run this code, and it likely contains errors. 我没有运行此代码,它可能包含错误。 But it is an illustration of what you can do. 但它说明了你能做些什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM