Как сравнивать пользовательские классы: создание простой карточной игры - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь создать простую карточную игру, в которой каждый игрок, в данном случае пользователь и р c, получают по 20 карт из 54, а первые карты автоматически раздаются и сравниваются. Вот мой текущий код:

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()

Этот код делает то, что должен делать: генерировать колоду карт, но мне трудно работать с этими картами самостоятельно. Я хочу поместить его в список или строку, где я могу хранить как данные о масте, так и данные о стоимости, чтобы я мог сравнивать их, поскольку некоторые значения превосходят другие, и каждая игра по масти будет превосходить другие.

Ответы [ 2 ]

2 голосов
/ 17 апреля 2020

Вы можете улучшить качество своей жизни с помощью этих карт, применяя методы dunder (также известные как маги c методы) для объекта. Используя некоторые свободы, я реализовал один из возможных способов сравнения карт. После того, как вы внедрили методы Dunder, вы можете сравнить Card s, как вы бы str s или int s.

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)
1 голос
/ 17 апреля 2020

Не уверен, как игра должна работать, но было много ошибок. Кроме ошибки отступа. Вы добавили дополнительный «a» в self.hand в def init () класса игрока.

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()
...