抱歉,我是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() 行中),说明该卡不在列表中。不过我可以通过手动使用它的索引来访问它。因此我不知道为什么这不起作用。您知道这背后的原因是什么吗?提前致谢。
最佳答案
.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
[]
...
关于python - 从Python中的列表(玩家的手)中删除用户定义的对象(一张牌),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60026437/