我正在学习Python作为我的第一语言,并且正在研究如何像计算机科学家那样思考的老女佣游戏。我的代码进入了一个无限循环,我无法弄清楚为什么我发布了堆栈溢出。我被要求隔离问题并发布我现在做的更少的代码(好建议)。
问题:最初,remove_matches
会正确检测并删除所有卡片对象的匹配项,但Aces除外。既然我已经在较小的规模上复制了问题,那么它似乎并没有删除任何卡级别的匹配。在下面的示例中,我使用了匹配的Aces和匹配的Kings。两者都没有被检测到。
class Card:
suite_list = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_list = ["narf", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
# "narf" is being used as a placeholder for the zeroith item, to allow
# card#'s to match the index #'s
def __init__(self, suite = 0, rank = 0):
self.suite = suite
self.rank = rank
def __str__(self):
return self.rank_list[self.rank]+" of "+self.suite_list[self.suite]
class Deck:
def __init__ (self):
self.cards = []
for suite in range (4):
for rank in range (1, 14):
self.cards.append(Card(suite, rank))
def __str__ (self):
s = " "
for i in range (len(self.cards)):
s = s + " "*i + str(self.cards[i]) + "\n"
return s
def remove_card(self,card):
if card in self.cards:
self.cards.remove(card)
return True
else:
return False
class Hand(Deck):
def __init__ (self, name = " "):
self.cards = []
self.name = name
def __str__(self):
s = "Hand "+ self.name
return s+ " contains\n" + Deck.__str__(self)
def remove_matches(self):
count = 0
for card in self.cards:
match = Card(3 - card.suite, card.rank)
print card, " matches ", match
if match in self.cards:
self.cards.remove(card)
self.cards.remove(match)
print "Hand %s: %s matches %s" % (self.name, card, match)
count = 1
return count
Joes_hand = Hand("Joe")
Joes_hand.cards = [Card(1,1), Card(2,1), Card(1,13), Card(2,13)]
print Joes_hand
Joes_hand.remove_matches()
print
print Joes_hand
Joes_hand = Hand()
首先,我创建了一个名为Joe的玩家,他手中还没有卡片对象。
Joes_hand.cards = [Card(1,1), Card(2,1), Card(1,13), Card(2,13)]
现在我已经为Joe分配了4张牌。
print Joes_hand
然后我打印了Joe的手,这样我们就可以看到他的牌了。
Hand Joe contains
Ace of Diamonds
Ace of Hearts
King of Diamonds
King of Hearts
Joes_hand.remove_matches()
这是我遇到问题的地方。 remove_matches
应该删除按等级和颜色匹配的卡片。这是可能的,因为排名和套件是在我的Card
对象的属性中构建的。我在remove_matches
方法中添加了一个print语句:
print card, " matches ", match
,目的是证明代码能够识别匹配是什么。但由于某种原因,它无法检测到匹配,即使它知道要寻找什么。因此,if语句后面没有任何语句:if match in self.cards:
正在执行。
输出:
Ace of Diamonds matches Ace of Hearts
Ace of Hearts matches Ace of Diamonds
King of Diamonds matches King of Hearts
King of Hearts matches King of Diamonds
最后,我再次打印Joe的手,表明没有一张牌被删除。
print
print Joes_hand
Hand Joe contains
Ace of Diamonds
Ace of Hearts
King of Diamonds
King of Hearts
以下是remove_matches
的另一种看法:
def remove_matches(self):
count = 0
for card in self.cards:
match = Card(3 - card.suite, card.rank)
print card, " matches ", match
if match in self.cards:
self.cards.remove(card)
self.cards.remove(match)
print "Hand %s: %s matches %s" % (self.name, card, match)
count = 1
return count
对不起,我的帖子很长,我倾向于过度解释,但我想确保我分享所有信息。我错过了一些明显的东西吗我好几天都在苦苦挣扎。任何想法都会有所帮助。
谢谢!