0

We are supposed to use the code below to print out the parameters listed in it, currently however we are unable to do so and are using a round about method. This is supposed to print out things instead of what we print out in the Game class in the playturn function

 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)

Here is our actual code, if you also see any other issues your input would be greatly appreciated

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()
Tammy Logger
  • 61
  • 1
  • 10

2 Answers2

1

The problem is that, in at least some places, you're trying to print a list.

While printing anything, including a list, calls str on it, the list.__str__ method calls repr on its elements. (If you don't know the difference between str and rep, see Difference between __str__ and __repr__ in Python.)

If you want to print the str of every element in a list, you have to do it explicitly, with a map or list comprehension.

For example, instead of this:

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

… do this:

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

But this is still probably not what you want. You will get ['8', '9'] instead of [<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>], but you probably wanted something more like `8H 9C'. To do that, you'd want something like:

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

You already have similar (although more verbose) code inside Player.__str__:

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

This code could be improved in a few ways.

First, it's going to raise an AttributeError because you're using face instead of number. But really, you shouldn't need to do this at all—the whole reason you created a Card.__str__ method is so you can just use str(Card), right?

Second, you almost never want to loop over range(len(foo)), especially if you do foo[y] inside the loop. Just loop over foo directly.

Putting that together:

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

At any rate, you need to do the same thing in both places.

The version that uses the join method and a generator expression is a little simpler than the explicit loop, but does require a bit more Python knowledge to understand. Here's how you'd use it here:

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

Your next problem is that Card.__str__ doesn't include the suit. So, instead of 8H 9C, you're going to get 8 9. That should be an easy fix to do on your own.


Meanwhile, if you find yourself writing the same code more than once, you probably want to abstract it out. You could just write a function that takes a hand list and turns it into a string:

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

But it might be even better to create a Hand class that wraps up a list of cards, and pass that around, instead of using a list directly.

Community
  • 1
  • 1
abarnert
  • 354,177
  • 51
  • 601
  • 671
0

You are not running the functionality you want because you are referencing player.hand. Try changing

str(self.player.hand)

to

str(self.player)
John
  • 13,197
  • 7
  • 51
  • 101
  • So you want to say "your has has: " and then print out a `Player` object, which shows the player's name, his hand, and his money? – abarnert May 09 '13 at 19:09
  • @abarnert `We are supposed to use the code below to print out the parameters listed in it`, yes that's what I was aiming for. – John May 09 '13 at 19:15
  • @abarnert this is what we are trying to accomplish. – Tammy Logger May 09 '13 at 19:15
  • @johnthexiii: The OP is trying to print out hand. You're instead printing out the entire Player object, which includes more than just the hand. "Print something that works, even if it's the wrong thing" is probably not the actual assignment. There may also be places where she's printing the wrong thing, but there are definitely places where she should be trying to print a `hand`, and is, so she needs to know how to make it work. – abarnert May 09 '13 at 19:20
  • we want the cards and if it is not the dealer we also want to print out the amount of money that player has – Tammy Logger May 09 '13 at 19:24