在python中从列表(玩家的手)中删除用户定义的对象(卡)

2024-09-27 09:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,我是python新手,抱歉,如果问题太简单的话。我正在尝试为一款名为pishti或bastra的纸牌游戏编写代码。很快,两个玩家(在我的例子中是一个用户和一台计算机)每个手都有4张牌,中间有一些卡在上面,玩家可以看到(其他人是封闭的)。很快,我就可以用四个卡片对象的列表为用户处理卡片。但是,在用户玩完他/她的一张卡后,我无法从列表中删除该卡,因为找不到该卡。(我尝试使用.remove()和del)但是,我可以使用list[index]访问卡 这是我的代码(简称为与此问题相关的部分):

import random
class Card:
    def __init__(self,value,suit):
        self.value = value
        self.suit = suit
    def __repr__(self):
        return f"{self.suit} {self.value}"
    def execute(self):
        return None
class Deck:
    def __init__(self):
        suits = ["Hearts","Spades","Clubs","Diamonds"]
        values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
        self.cards = [Card(value,suit) for value in values for suit in suits]
    def __repr__(self):
        return f"Deck of {self.count()}"
    def count(self):
        return len(self.cards)
    def shuffle(self):
        if self.count() < 52:
            raise ValueError ("Sorry only complete decks can be shuffled.")
        random.shuffle(self.cards)
        return self
    def _deal(self,num_of_cards_to_be_dealt):
        if self.count() == 0:
            raise ValueError ("Sorry, all of the cards have been dealt.")
        actual = min(self.count(),num_of_cards_to_be_dealt)
        dealt_cards = self.cards[-actual:]
        self.cards = self.cards[:-actual]
        return dealt_cards
    def deal_hand(self,hand_size = 4):
        return self._deal(hand_size)

deste = Deck()
kar_deste = deste.shuffle()


orta = (kar_deste.deal_hand())

print(f"The card in the middle: {orta[-1]}")
user_score = 0
comp_score = 0
while kar_deste.count() != 0:
    computer_hand = kar_deste.deal_hand()
    user = kar_deste.deal_hand()
    print(f"Your cards: {user}")
    while len(user) != 0:
        card_suit = input("Choose a suit: ")
        card_val = input("Choose a value: ")
        print(str(Card(card_val,card_suit)))
        user_turn = Card(card_val,card_suit)
        card_index = user.index(user_turn)
        del user[card_index]
        print(user)

当我运行此代码时,我遇到一个值错误(在user.index()行中),表示该卡不在列表中。但是,我可以通过手动使用它的索引来访问它。因此,我不知道为什么这不起作用。你知道这背后的原因吗?提前谢谢


Tags: selfindexreturnvaluedefcountcardcards
1条回答
网友
1楼 · 发布于 2024-09-27 09:34:02

.index调用对象的__eq__方法,因此必须在Card中实现它。否则,将根据对象的内存地址对其进行比较

可能的实施:

def __eq__(self, other):
    return all((isinstance(other, self.__class__),
                self.suit == other.suit,
                self.value == other.value))

然后

The card in the middle: Clubs 4
Your cards: [Diamonds 10, Hearts K, Clubs 10, Hearts 5]
Choose a suit: Hearts
Choose a value: 5
Hearts 5
[Diamonds 10, Hearts K, Clubs 10]
Choose a suit: Diamonds
Choose a value: 10
Diamonds 10
[Hearts K, Clubs 10]
Choose a suit: Hearts
Choose a value: K
Hearts K
[Clubs 10]
Choose a suit: Clubs
Choose a value: 10
Clubs 10
[]
...

相关问题 更多 >

    热门问题