这是我第一次遇到堆栈溢出,所以如果格式不适合该网站,我很抱歉。我最近才开始学习编程,从那时起已经过去了将近 2 周。我正在从http://openbookproject.net/thinkcs/python/english3e/index.html学习 python, 直到现在一切都很好,我只是被困了几个小时。我用谷歌搜索了很多,但找不到合适的解决方案来解决我的问题,所以我在这里。
我试图让 OldMaidGame() 运行没有问题,如 CH17 中所述。http://openbookproject.net/thinkcs/python/english3e/ch17.html - 大部分代码也来自上一章。
我发现我无法让 Deck.remove、Hand.remove_matches 或任何其他类型的移除功能工作。经过一些调试后,我发现当程序检查给定卡是否存在于甲板/手/等中时会出现问题。它永远无法匹配。然后在回顾了这一章之后,(在第 16 章中),我发现 'if card in deck/hand/etc: remove(card)' 等查找 . cmp () 来判断卡片是否真的存在于deck/hand/etc中。这是我在电子书的给定代码上添加 'ace' 后的cmp版本。
def __cmp__(self, other):
""" Compares cards, returns 1 if greater, -1 if lesser, 0 if equal """
# check the suits
if self.suit > other.suit: return 1
if self.suit < other.suit: return -1
# suits are the same... check ranks
# check for aces first.
if self.rank == 1 and other.rank == 1: return 0
if self.rank == 1 and other.rank != 1: return 1
if self.rank != 1 and other.rank == 1: return -1
# check for non-aces.
if self.rank > other.rank: return 1
if self.rank < other.rank: return -1
# ranks are the same... it's a tie
return 0
cmp本身似乎很好 afaik,我可以使用一些技巧来使其更好(例如使用 ace 检查)。所以我不知道为什么牌组/手牌检查中的牌总是返回假。这是给定的删除功能:
class Deck:
...
def remove(self, card):
if card in self.cards:
self.cards.remove(card)
return True
else:
return False
拼命想让它工作,我想出了这个:
class Deck:
...
def remove(self, card):
""" Removes the card from the deck, returns true if successful """
for lol in self.cards:
if lol.__cmp__(card) == 0:
self.cards.remove(lol)
return True
return False
似乎工作正常,直到我转向其他非工作删除功能:
class OldMaidHand(Hand):
def remove_matches(self):
count = 0
original_cards = self.cards[:]
for card in original_cards:
match = Card(3 - card.suit, card.rank)
if match in self.cards:
self.cards.remove(card)
self.cards.remove(match)
print("Hand {0}: {1} matches {2}".format(self.name, card, match))
count = count + 1
return count
我又做了一些调整:
class OldMaidHand(Hand):
def remove_matches(self):
count = 0
original_cards = self.cards[:]
for card in original_cards:
match = Card(3 - card.suit, card.rank)
for lol in self.cards:
if lol.__cmp__(match) == 0:
self.cards.remove(card)
self.cards.remove(match)
print("Hand {0}: {1} matches {2}".format(self.name, card, match))
count = count + 1
return count
卡的删除工作正常,但是当我尝试删除匹配时它会给出错误(x 不在列表中)。另一个我们的左右,我可能也能做到这一点,但是因为我已经感觉我走错了路,因为我无法修复原来的“卡牌/手牌/等”等,我来这里寻找一些答案/提示。
感谢您的阅读,非常感谢您提供的任何帮助:)
--------------------- 编辑 1 * >
这是我当前的代码: http: //pastebin.com/g77Y4Tjr
--------------------- 编辑 2 * >
我已经尝试了这里建议的每一个cmp,但我仍然无法找到带有“in”的卡。
>>> a = Card(0, 5)
>>> b = Card(0, 1)
>>> c = Card(3, 1)
>>> hand = Hand('Baris')
>>> hand.add(a)
>>> hand.add(b)
>>> hand.add(c)
>>> d = Card(3, 1)
>>> print(hand)
Hand Baris contains
5 of Clubs
Ace of Clubs
Ace of Spades
>>> d in hand.cards
False
>>>
我也试过 card.py @DSM 已经成功使用,我也有错误,比如在 sort 函数中它说它不能比较两个卡片对象。
所以我想知道,也许是 Python 3.2 的问题,或者语法在某个地方发生了变化?