简体   繁体   English

如何比较自定义类:创建一个简单的纸牌游戏

[英]How to compare custom classes: Creating a simple card game

I'm trying to create a simple card game, where each player, in this case the user and the pc, each get 20 cards out of 54, and the first cards are automaticly put out and compared.我正在尝试创建一个简单的纸牌游戏,其中每个玩家,在这种情况下是用户和电脑,每个人从 54 张牌中得到 20 张牌,第一张牌被自动放出并进行比较。 Hers is my current code:她的是我当前的代码:

import random
tolvuspil=[]
notandaspil=[]
stokkur= []


class Card:
def __init__(self, suit, val):
    self.suit = suit
    self.value = val

def show(self):
    print("{} {}".format(self.suit, self.value))


class deck:
def __init__(self):
    self.cards = []
    self.build()

def build(self):
    for s in ['Hjarta', 'Spaða', 'Tígul', 'Laufa']:
        for v in range(1, 14):
            if v == 11:
                v = "Jock"
            elif v == 1:
                v = "ace"
            elif v == 12:
                v = "Quenn"
            elif v == 13:
                v = "King"
            self.cards.append(Card(s, v))


def show(self):
    for c in self.cards:
        c.show()

def shuffle(self):
    for i in range(len(self.cards) -1 , 0, -1):
        r= random.randint(0, i)
        self.cards[i], self.cards[r] = self.cards[r], self.cards[i]


def drawcard(self):
    return self.cards.pop()


class player:
def __init__(self, name):
    self.name = name
    self.hand = []a

def draw(self, deck):
    self.hand.append(deck.drawcard())
    return self

def showhand(self):
    for card in self.hand:
        card.show()

 boblisti = []
 xyz = deck()
 xyz.shuffle()
 xyz.show()

This code does what it is supposed to do, which is generating a deck of cards, but i am having a hard time working with the cards them self.这段代码完成了它应该做的事情,即生成一副卡片,但我很难自己处理卡片。 I want to put the in a list or string, where i can store both the suit and value data, so i can compere them, as some values beat other and every game on suit will be superior to others.我想把它放在一个列表或字符串中,我可以在其中存储花色和价值数据,这样我就可以对它们进行比较,因为一些价值击败了其他价值,每场比赛都将优于其他比赛。

You can improve your quality of life with these cards by implementing the dunder methods (aka magic methods) for the object.您可以通过为 object 实施dunder 方法(又名魔术方法)来提高这些卡的生活质量。 Using some liberties, I've implemented one possible way that you could compare the cards.使用一些自由,我实现了一种比较卡片的可能方式。 Once you've implemented the dunder methods, you can compare Card s just like you would str s or int s.一旦实现了 dunder 方法,就可以像比较strint一样比较Card

import random
tolvuspil = []
notandaspil = []
stokkur = []
boblisti = []


class Card:

    values = ["ace", "2", "3", "4", "5", "6", "7", "8", "9", "10" ,"Jock", "Quenn", "King"] # in order, least valuable to most.
    suits = ['Tígul', 'Laufa', 'Hjarta', 'Spaða'] # in order, least valuable to most.

    def __init__(self, suit, val):
        suit = str(suit) # input normalization
        val = str(val) # input normalization
        assert suit in self.suits, "Suit [found %s] must be in suits: %s" % (suit, ", ".join(self.suits))
        assert val in self.values, "Value [found %s] must be in values: %s" % (val, ", ".join(self.values))
        self.suit = suit 
        self.value = val

    def show(self):
        print(self)

    def __eq__(self, other): # == operator
        return other.suit == self.suit and other.value == self.value

    def __ne__(self, other): # != operator
        return not (self == other)

    def __lt__(self, other): # < operator
        if self.value == other.value: # first, compare the face value
            # if they have the same face value, compare their suits
            return self.suits.index(self.suit) < self.suits.index(other.suit)
        return self.values.index(self.value) < self.values.index(other.value)

    def __le__(self, other): # <= operator
        return self == other or self < other

    def __gt__(self, other): # > operator
        if self.value == other.value: # first, compare the face value
            # if they have the same face value, compare their suits
            return self.suits.index(self.suit) > self.suits.index(other.suit)
        return self.values.index(self.value) > self.values.index(other.value)

    def __ge__(self, other): # >= operator
        return self == other or self > other

    def __str__(self): # str() implementation
        return "{} {}".format(self.suit, self.value)

class deck:

    def __init__(self):
        self.cards = []
        self.build()

    def build(self):
        for s in ['Hjarta', 'Spaða', 'Tígul', 'Laufa']:
            for v in range(1, 14):
                if v == 11:
                    v = "Jock"
                elif v == 1:
                    v = "ace"
                elif v == 12:
                    v = "Quenn"
                elif v == 13:
                    v = "King"
                self.cards.append(Card(s, v))

    def show(self):
        for c in self.cards:
            print(c)

    def shuffle(self):
        for i in range(len(self.cards) - 1, 0, -1):
            r = random.randint(0, i)
            self.cards[i], self.cards[r] = self.cards[r], self.cards[i]

    def drawcard(self):
        return self.cards.pop()


class player:

    def __init__(self, name):
        self.name = name
        self.hand = []

    def draw(self, deck):
        self.hand.append(deck.drawcard())
        return self

    def showhand(self):
        for card in self.hand:
            card.show()


xyz = deck()
xyz.shuffle()
xyz.show()

a = xyz.drawcard()
b = xyz.drawcard()

print(a, b)

print("a < b:", a < b)
print("a <= b:", a <= b)
print("a > b:", a > b)
print("a >= b:", a >= b)
print("a == b:", a == b)
print("a != b:", a != b)

Not sure how the game should work but there were a lot of errors.不知道游戏应该如何工作,但有很多错误。 Other than the indentation error.除了缩进错误。 You added an extra "a" in the self.hand in def init () of the player class.您在播放器 class 的 def init () 中的 self.hand 中添加了一个额外的“a”。

import random
tolvuspil = []
notandaspil = []
stokkur = []
boblisti = []


class Card:

    def __init__(self, suit, val):
        self.suit = suit
        self.value = val

    def show(self):
        print("{} {}".format(self.suit, self.value))


class deck:

    def __init__(self):
        self.cards = []
        self.build()

    def build(self):
        for s in ['Hjarta', 'Spaða', 'Tígul', 'Laufa']:
            for v in range(1, 14):
                if v == 11:
                    v = "Jock"
                elif v == 1:
                    v = "ace"
                elif v == 12:
                    v = "Quenn"
                elif v == 13:
                    v = "King"
                self.cards.append(Card(s, v))

    def show(self):
        for c in self.cards:
            c.show()

    def shuffle(self):
        for i in range(len(self.cards) - 1, 0, -1):
            r = random.randint(0, i)
            self.cards[i], self.cards[r] = self.cards[r], self.cards[i]

    def drawcard(self):
        return self.cards.pop()


class player:

    def __init__(self, name):
        self.name = name
        self.hand = []

    def draw(self, deck):
        self.hand.append(deck.drawcard())
        return self

    def showhand(self):
        for card in self.hand:
            card.show()


xyz = deck()
xyz.shuffle()
xyz.show()

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

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