【发布时间】:2019-02-21 15:56:55
【问题描述】:
所以当我尝试形成一个 Pile 类时,我正在开发一个纸牌游戏,我在其中构建了一个函数来打印卡片类中的卡片和堆类中的卡片列表。当我尝试在桩类中使用卡片类(在其他类中工作)中的函数时,我没有得到预期的结果。我该如何解决这个问题?
卡类:
import random
from Enums import *
class Card:
def __init__(self):
self.suit = Suit.find(random.randint(1, 4))
self.rank = Rank.find(random.randint(1, 14))
def show(self):
print (self.rank.value[1], "of", self.suit.value[1])
桩类:
from Enums import *
from Card import *
from Hand import *
class Pile:
def __init__(self):
self.cards = []
self.cards.append(Card())
def discard(self, hand, card):
self.cards.append(card)
if (not searchCard(self, hand, card)):
print ("The card was not found, please select another one or cheat")
return True
else:
return False
def takePile(self, hand):
for x in self.cards:
hand.cards.append(self.cards[x])
def clearPile(self):
while len(self.cards) > 0:
self.cards.pop()
def searchCard(self, hand, card):
flag = False
for x in hand.cards and not flag:
if (hand.cards[x].rank.value[0] == card.rank.value[0]):
if (hand.cards[x].suit.value[0] == card.suit.value[0]):
hand.cards[x].pop()
flag = True
return flag
def showCurrent(self):
for x in self.cards:
x.show()
我指的是 Card 类中的 show 函数和 Pile 类中的 showCurrent 和 init
当我运行游戏和线路时
print ("It's your turn now, the pile presents a", pile.showCurrent())
我从 Card 类的 show 函数中得到一个 None 而不是 print,如下所示:
现在轮到你了,一堆没有
【问题讨论】:
-
嗯,您正在打印
showCurrent()的结果,即None。只需在print之后调用showCurrent,然后它应该可以按预期工作。 -
你能用 str 函数代替显示答案吗?
-
另外,从打印的消息来看,
showCurrent似乎应该只打印最上面的卡片,但它会打印所有卡片。 -
但我也使用 show 功能,所以它必须使用它并打印那里的内容
-
一般来说,保持 I/O 尽可能靠近程序的“边缘”。如果您可以在现在打印某些内容和返回一个字符串以供 else 打印之间做出选择,请选择后者。
标签: python list function oop printing