我对Python比较了解,但我决定使用类创建一个高低卡游戏。我已经把所有的课程都设置好了,但是我唯一的问题是,当我试着看playerHand
的卡片是比nextCard
的卡片大还是小的时候playerHand
和nextCard
都绑定到类,我得到的错误是:TypeError: '>' not supported between instances of 'Person' and 'NextCard'
有100%更好的方法可以做到这一点,但这是我迄今为止得到的:
import random
class Card(object):
def __init__(self, suit, value):
self.suit = suit
self.value = value
def show(self):
print ("{} of {}".format(self.value, self.suit))
class Deck(object):
def __init__(self):
self.cards = []
self.build()
def build(self):
for suit in ["Spades", "Clubs", "Diamonds", "Hearts"]:
for value in ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]:
self.cards.append(Card(suit, value))
def show(self):
for card in self.cards:
card.show()
def shuffle(self):
for n in range(len(self.cards)-1,0,-1):
r = random.randint(0, n)
self.cards[n], self.cards[r] = self.cards[r], self.cards[n]
def drawCard(self):
return self.cards.pop()
class Person(object):
def __init__(self):
self.hand = []
def draw(self, deck):
self.hand.append(deck.drawCard())
return self
def show(self):
for card in self.hand:
card.show()
class NextCard(object):
def __init__(self):
self.nextcard = []
def draw(self, deck):
self.nextcard.append(deck.drawCard())
return self
def show(self):
for card1 in self.nextcard:
card1.show()
deck = Deck()
deck.shuffle()
human = Person()
playerHand = human.draw(deck)
newcard = NextCard()
nextCard = newcard.draw(deck)
play = input("Do you want to play High/Low? Y or N? ")
while play.lower()== "y":
card = playerHand
print("The current card is: ", str(card.show()))
guess = input("Guess H for high or L for low." )
if guess.lower()=="h":
if card > nextCard:
print("Congratulations! You guessed correctly! The next card was ", card)
play = input("Play again? Y or N? ")
if card < nextCard:
print("You lost! The next card was ", nextCard)
play = input("Play again? Y or N? ")
if guess.lower()=="l":
if card > nextCard:
print("You lost! The next card was ", nextCard)
play = input("Play again? Y or N? ")
if card < nextCard:
print("Congratulations! You guessed correctly! The next card was ", nextCard)
else:
print("The game is over.")
对于类间比较问题的任何解决方案或解决方法,我们将不胜感激。这是用python 3编写的
这些是playerHand和nextCard课程吗
使用<;运算符您需要执行运算符重载
但这是高级python
您只是在给playerHand类添加别名
使它成为一个对象
但它无法解决问题(可能)
请给我一个课堂的内部视图(简要编辑你的问题)
对于<;在类中添加
__lt__()
方法对于>;在类中添加
__gt__()
方法那些
__lt__()
和__gt__()
将执行运算符的重载**(重载是指自定义使用的编程运算符)**
还有一节课
这是比较类的最后一个片段
这是一个非常深刻的主题(如果很难理解的话)和中间的python内容。你可以尝试一些网上的东西来简单了解一下
尝试以下“极客换极客”教程:
https://www.geeksforgeeks.org/operator-overloading-in-python/
相关问题 更多 >
编程相关推荐