繁体   English   中英

使用Python打印出类时出现问题

[英]Trouble with printing out of Classes in Python

我们应该使用下面的代码来打印出其中列出的参数,但是目前我们无法这样做,并且正在使用一种方法。 这应该打印出来的东西,而不是我们在playturn函数的Game类中打印出来的东西

 def __str__(self):
        x = self.name + ":\t"
        x += "Card(s):"
        for y in range(len(self.hand)):
            x +=self.hand[y].face + self.hand[y].suit + " "
        if (self.name != "dealer"):
            x += "\t Money: $" + str(self.money)
        return(x)

这是我们的实际代码,如果您还发现任何其他问题,将不胜感激

from random import*
#do we need to address anywhere that all face cards are worth 10?
class Card(object):
    def __init__(self,suit,number):
        self.number=number
        self.suit=suit
    def __str__(self):
        return '%s'%(self.number)

class DeckofCards(object):
    def __init__(self,deck):
        self.deck=deck
        self.shuffledeck=self.shuffle()

    def shuffle(self):
        b=[]
        count=0
        while count<len(self.deck):
            a=randrange(0,len(self.deck))
            if a not in b:
                b.append(self.deck[a])
                count+=1
        return(b)

    def deal(self):
        if len(self.shuffledeck)>0:
            return(self.shuffledeck.pop(0))
        else:
            shuffle(self)
            return(self.shuffledeck.pop(0))
class Player(object):
    def __init__(self,name,hand,inout,money,score,bid):
        self.name=name
        self.hand=hand
        self.inout=inout
        self.money=money
        self.score=score
        self.bid=bid

    def __str__(self):
        x = self.name + ":\t"
        x += "Card(s):"
        for y in range(len(self.hand)):
            x +=self.hand[y].face + self.hand[y].suit + " "
        if (self.name != "dealer"):
            x += "\t Money: $" + str(self.money)
        return(x)

class Game(object):
    def __init__(self,deck, player):
        self.player=Player(player,[],True,100,0,0)
        self.dealer=Player("Dealer",[],True,100,0,0)
        self.deck=DeckofCards(deck)
        self.blackjack= False
    def blackjacksearch(self):
        if Game.gettot(self.player.hand)==21:#changed
            return True
        else:
            return False    
    def firstround(self):
        #self.player.inout=True#do we need this since this is above
        #self.player.hand=[]#do wee need this....
        #self.dealer.hand=[]#do we need this ....
        self.player.hand.append(DeckofCards.deal(self.deck))
        for card in self.player.hand:
            a=card
        print(self.player.name + ' ,you were dealt a '+str(a))
        self.dealer.hand.append(DeckofCards.deal(self.deck))
        for card in self.dealer.hand:
            a=card
        print('The Dealer has '+str(a))
        playerbid=int(input(self.player.name + ' how much would you like to bet? '))
        self.player.money-=playerbid
        self.player.bid=playerbid
    def playturn(self): #should this be changed to inout instead of hit.....we never use inout
        #for player in self.player:
        #    a=player
        #print(str(a))
        hit=input('Would you like to hit? ') #should input be in loop?
        while self.player.inout==True: #and self.blackjack!=True:#changed
            print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets
            self.player.hand.append(DeckofCards.deal(self.deck))
            for card in self.player.hand:
                a=card
            print('The card that you just drew is: ' + str(a))
            #print(Game.gettot(self.player.hand)) 
            hit=input('Would you like to hit? ')
            if hit=='yes':
                (self.player.hand.append(DeckofCards.deal(self.deck)))#changed
                self.player.inout==True#
            else:
                (self.player.hand) #changed
                self.player.inout==False #changed
        if self.player.blackjack==True:
            print(self.player.name + " has blackjack ")
        if hit=='no':
            print (self.player.hand.gettot())
    def playdealer(self):
        while Game.gettot(self.dealer.hand)<17:#changed
            self.dealer.hand.append(DeckofCards.deal(self.deck))
            dealerhand=Game.gettot(self.dealer.hand) #changed
            print(dealerhand)
        if Game.gettot(self.dealer.hand)==21:#changed
            self.dealer.blackhjack=True
        dealerhand1=Game.gettot(self.dealer.hand)#changed
        print(dealerhand1)

    def gettot(self,hand):
        total=0
        for x in self.hand:
            if x==Card('H','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('D','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('S','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('C','A'):
                b=total+x #changed
                if b>21:
                    total+=1
                else:
                    total+=11
            else:
                total+=x
        return(total)

    def playgame(self):
        play = "yes"
        while (play.lower() == "yes"):
            self.firstround()
            self.playturn()
            if self.player.blackjack == True:
                print(self.player.name + " got BLACKJACK! ")
                self.player.money += self.player.bid * 1.5
                print (self.player.name + " now has " + str(self.player.money))
                print("\n")
                self.player.inout = False
            if self.player.score > 21:
                print(self.player.name + " lost with a tot of " + str(self.player.score))
                self.player.money -= self.player.bid
                print (self.player.name + " now has " + str(self.player.money))
                print ("\n\n")
                self.player.inout = False
            self.playdealer()
            if self.dealer.blackjack == True:
                print("Dealer got blackjack, dealer wins\n")
                self.player.money -= self.player.bid
                print("Round\n")
                print("\t",self.dealer)
                print("\t",self.player)
                print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
            elif self.player.inout == True:
                print("Round\n")
                print("\t",self.dealer)
                print("\t",self.player)
                print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
                if self.dealer.score > 21:
                    print("\t Dealer lost with a total of " + str(self.dealer.score))
                    self.player.money += self.player.bid
                    print(self.player.name + " now has " + str(self.player.money))
                elif self.player.score > self.dealer.score:
                    print("\t" +self.player.name + " won with a total of " + str(self.player.score))
                    self.player.money += self.player.bid
                    print("\t"+self.player.name + " now has " + str(self.player.money))
                else:
                    print("\t Dealer won with a total of " + str(self.dealer.score))
                    self.player.money -= self.player.bid
                    print("\t"+self.player.name + " now has " + str(self.player.money))
            else:
                print("Round")
                print("\t",self.dealer)
                print("\t",self.player)
                if self.player.blackjack == False:
                    print("\t "+ self.player.name + " lost" )
                else:
                    print("\t "+self.player.name + " Won!")

            if self.player.money <= 0:
                print(self.player.name + " out of money - out of game ")
                play = "no"
            else:
                play = input("\nAnother round? ")
                print("\n\n")
        print("\nGame over. ")
        print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n")
        print("Thanks for playing.  Come back soon!")



ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'),
Card('H','J'),Card('H','Q'),Card('H','K'),
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'),
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'),
Card('S','J'),Card('S','Q'),Card('S','K'),
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'),
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'),
Card('C','J'),Card('C','Q'),Card('C','K'),
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'),
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'),
Card('D','J'),Card('D','Q'),Card('D','K')]


def main():
    x = input("Player's name? ")
    blackjack = Game(ls,x)
    blackjack.playgame()
main()

问题是,至少在某些地方,您正在尝试打印list

在打印任何内容(包括list ,在其上调用strlist.__str__方法在其元素上调用repr (如果您不知道strrep之间的区别,请参阅Python中__str____repr__之间的__str__ 。)

如果要打印列表中每个元素的str ,则必须使用map或列表理解来显式地进行打印。

例如,代替此:

print(self.player.name + ' , your hand has:' + str(self.player.hand))

… 做这个:

print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand])

但这可能仍然不是您想要的。 您将得到['8', '9']而不是[<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>] ,但是您可能想要的更像是'8H 9C'。 为此,您需要类似:

print(self.player.name + ' , your hand has:' + 
      ' '.join(str(card) for card in self.player.hand))

Player.__str__您已经有类似(尽管更冗长)的代码:

for y in range(len(self.hand)):
    x +=self.hand[y].face + self.hand[y].suit + " "

该代码可以通过几种方式进行改进。

首先,它将引发AttributeError因为您使用的是face而不是number 但实际上,您根本不需要执行此操作-创建Card.__str__方法的全部原因是,您可以仅使用str(Card) ,对吗?

其次,您几乎永远不会想要遍历range(len(foo)) ,尤其是如果您在循环内执行foo[y] 只需直接遍历foo

放在一起:

for card in self.hand:
    x += str(card) + " "

无论如何,您需要在两个地方都做相同的事情。

使用join方法和生成器表达式的版本比显式循环要简单一些,但是需要更多的Python知识来理解。 这是您在此处的使用方式:

x += " ".join(str(card) for card in self.hand) + " "

您的下一个问题是Card.__str__不包括西装。 因此,您将获得8 9而不是8H 9C 这应该是一个简单的修复程序。


同时,如果您发现自己多次编写相同的代码,则可能希望将其抽象出来。 可以编写一个函数,该函数需要一个手list并将其转换为字符串:

def str_hand(hand):
    return " ".join(str(card) for card in self.hand)

但是,最好创建一个包裹卡片列表并将其传递的Hand类,而不是直接使用list

您没有运行所需的功能,因为您正在引用player.hand 尝试改变

str(self.player.hand)

str(self.player)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM