__str__ python method issue - python

I am making a python blackjack game. I have an error in this code which I can't figure out. In the end when I test out the hit function and print the hand, it does not show me the list. Instead, it says [<main.Card object at 0x02F9F5F0>].
Here is my code.
#Blackjack
import random
suits = ['Clubs', 'Spades', 'Diamonds', 'Hearts']
ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11}
game_on = True
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return(f'{self.rank} of {self.suit}')
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
def __str__(self):
deck_comp = ''
for card in self.deck:
deck_comp += '\n ' + card.__str__()
return deck_comp
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = [] # start with an empty list as we did in the Deck class
self.value = 0 # start with zero value
self.aces = 0 # add an attribute to keep track of aces
def add_card(self, card):
self.cards.append(card)
self.value += values[card.rank]
if card.rank == 'Ace':
self.aces += 1 # add to self.aces
def adjust_for_ace(self):
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
class Chips:
def __init__(self):
self.total = 100
self.bet = 0
def win_bet(self):
self.chips += self.bet
def lose_bet(self):
self.chips -= self.bet
def go_for_bet(chips):
while True:
try:
chips.bet = int(input('Please enter a betting amount: '))
except TypeError:
print('Please enter an integer')
continue
else:
if chips.bet > chips.total:
print(f'You do not have enough chips to bet {chips.bet}')
else:
break
def hit(deck, hand):
hand.add_card(deck.deal())
hand.adjust_for_ace()
def hit_or_stand(deck, hand):
while True:
x = input('Would you like to hit or stand? Say \'h\' or \'s\'')
if x[0].lower() == 'h':
hit(deck, hand)
elif x[0].lower() == 's':
print('You stand.')
else:
print('Try again please')
continue
break
deck = Deck()
hand = Hand()
hit(deck, hand)
print(hand.cards)

Either:
class Card:
def __repr__(self):
return self.__str__()
Or convert your Card objects to string first:
print([str(x) for x in hand.cards])

Just to make the difference between __repr__ and __str__ extra clear (:
class Repr:
def __repr__(self):
return 'Here I am with __repr__'
class Str:
def __str__(self):
return 'Here I am with __str__'
print('Plain:')
print(Repr(), Str())
print('In list:')
print([Repr(), Str()])
>
Plain:
Here I am with __repr__ Here I am with __str__
In list:
[Here I am with __repr__, <__main__.Str object at 0x00000216BC2940F0>]

it's a class list and only have one item in it. you can print items like:
for i in hand.cards:
print(i)

Related

looping error causing and endless scroll in blackjack game

I'm currently working on a blackjack game for my class and I think I've just about wrapped it up but for some reason I get stuck in an endless loop that keeps restarting the game. Can you help me find it?
import random as r
class Card:
def __init__(self, rank, suit, value):
self.rank = rank
self.suit = suit
self.value = value
def __str__(self):
return self.rank + ' of ' + self.suit
class Deck:
def __init__(self):
self.cards = []
self.shuffle()
def shuffle(self):
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
ranks = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
for suit in suits:
for rank in ranks:
value = ranks.index(rank) + 1
if value > 10: value = 10
if value == 1: value = 11
card = Card(rank, suit, value)
self.cards.append(card)
def deal(self):
if len(self.cards) < 1: self.shuffle()
index = r.randint(0, len(self.cards) - 1)
return self.cards.pop(index)
class Hand:
def __init__(self):
self.cards = []
def deal(self, card):
self.cards.append(card)
return self.value()
def value(self):
score = 0
aces = 0
for card in self.cards:
score += card.value
if card.value == 11: aces += 1
while score > 21 and aces > 1:
score -= 10
aces -= 1
return score
class Game:
def __init__(self):
self.deck = Deck()
self.player = Hand()
self.dealer = Hand()
self.wins = 0
self.losses = 0
self.exit = False
while not self.exit:
self.play()
def play(self):
self.deal()
if self.playerphase():
if self.dealerphase():
if self.player.value() > self.dealer.value():
self.outcome('player')
elif self.player.value() < self.dealer.value():
self.outcome('dealer')
else: self.outcome('pushback')
else: self.outcome('player', bust = True)
else: self.outcome('dealer', bust = True)
def deal(self):
self.player = Hand()
self.dealer = Hand()
for x in range(2):
self.player.deal(self.deck.deal())
self.dealer.deal(self.deck.deal())
def playerphase(self):
stand = False
options = ['hit', 'stand']
prompts = ["Enter 'hit or 'stand':"]
while not stand:
call = self.display(options, prompts)
if call == 'hit':
self.player.deal(self.deck.deal())
if self.player.value() > 21:
stand = True
else: stand = True
if self.player.value() > 21: return False
else: return True
def dealerphase(self):
while self.dealer.value() < 17:
self.dealer.deal(self.deal.deal())
if self.dealer.value() > 21: return False
else: return True
def display(self, options, prompts, show=False):
user = ''
while user not in options:
for x in range(30): print()
print('Wins: ' + str(self.wins))
print('Losses: ' + str(self.losses))
print('\nDealer: ')
if show: print(self.dealer.cards[0])
else: print('Face-Down Card')
for x in range (1, len(self.dealer.cards)):
print(self.dealer.cards[x])
print('\nPlayer:')
for card in self.player.cards:
print(card)
for prompt in prompts: print(prompt)
user = ''
return user
def outcome(winner, bust = False):
prompts = []
options = ['play', 'exit']
if winner == 'player':
prompts.append('player wins!')
if bust: prompts.append('dealer busts')
self.wins += 1
elif winner == 'dealer':
prompts.append('Dealer wins :(')
if bust: prompts.append('player busts')
self.losses += 1
else: prompts.append('Pushback!')
call = self.display(options, prompts, show = True)
if call == 'exit': self.exit = True
game = Game()

How to sum a list that contains letters by changing certain letters in a list with integers?

Just started learning Python and I am trying to create a blackjack game. I want to find the sum of the card values in a player's hand. My approach was to change the letters "J", "Q","K" into values of 10 and change "A" to value of 11. I have defined the class Card but when I run the code, I get an error saying "type object 'Card' has no attribute 'value'"
import random
DEFAULT_SUITS = ("Clubs","Hearts","Diamonds","Spades")
DEFAULT_VALUES = ("A",2,3,4,5,6,7,8,9,10,"J","Q","K")
class Card():
def __init__ (self, suit, value):
self.suit = suit
self.value = value
def show(self):
print(self.value, self.suit)
class Shoes():
def __init__(self, decks, suits=DEFAULT_SUITS, values=DEFAULT_VALUES):
self.cards = []
for deck in range(decks):
for suit in suits:
for value in values:
self.cards.append(Card(suit,value))
random.shuffle(self.cards)
def show(self):
for card in self.cards:
card.show()
def drawcard(self):
return self.cards.pop()
class Player():
def __init__ (self, name):
self.name = name
self.hand = []
def drawcard(self, shoes):
self.hand.append(shoes.drawcard())
return self
def totalvalue(self):
for card in self.hand:
if Card.value == "J":
self.hand = [10 if card=="J" else card for card in cards]
if Card.value == "Q":
self.hand = [10 if card=="Q" else card for card in cards]
if Card.value == "K":
self.hand = [10 if card=="K" else card for card in cards]
if Card.value == "A":
self.hand = [11 if card=="A" else card for card in cards]
self.totalvalue = sum(self.hand(Card.value))
def showhand(self):
for card in self.hand:
card.show()
shoe = Shoes(int(input("Enter the number of deck used in a shoes: ")))
bob = Player("bob")
bob.drawcard(shoe)
bob.showhand()
bob.totalvalue()
How can I change the values "J","Q","K","A" in hand and sum it up to get the total value?
you have used Card.value, where Card is a class instace, just change Card to card in totalvalue function.
and next thing, i will suggest to make a dictionary;
and take every value from that even numbers too.
dict = {'A':1, '2':2,.......}
and so on, like this
def totalvalue(self):
self.totalvalue =0;
dict = {'A':1, '2':2,.......};
for card in self.hand:
self.totalvalue = self.totalvalue +dict[card.value]
I see there is some confusion in using the list of Cards. Here what you should be doing
def totalvalue(self):
total = 0
for card in self.hand:
if card.value in ["J", "Q", "K"]:
total = total + 10
elif card.value == "A":
total = total + 11
else:
total = total + card.value
self.totalvalue = total
Code can be further simplified using the list comprehension as follows
def totalvalue(self):
return sum([10 if card.value in ['J', 'Q', 'K'] else 11 if card.value == 'A' else card.value for card in self.hand])

Simple Blackjack game: deck list becomes NoneType [duplicate]

This question already has answers here:
Why does random.shuffle return None?
(5 answers)
Closed 3 years ago.
I tired to make a simple blackjack game in Python. When executing the code, list of cards in deck (self.deck) creates problems - becomes NoneType, when it should be a list.
'''
This is a blackjack game for the project 2
'''
import random
cardsuits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
cardrank = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
cardvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card:
#class card has two attributes: suit and rank. asking for string will result in rank of suit response. There is a value calcluated, using cardvalues dictionary.
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.rank + ' of ' + self.suit
#def value(self):
# self.value = cardvalues[self.rank]
# #think about ace here; it can be worth 10 or 1 depending on hand
class Deck:
def __init__(self):
self.deck = []
for suit in cardsuits:
for rank in cardrank:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = ""
for card in self.deck:
deck_comp = deck_comp + "\n" + card.__str__()
return "Deck contains " + deck_comp
def reroll(self):
self.deck = random.shuffle(self.deck)
def take_a_card(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self, card):
self.cards.append(card)
self.value = self.value + cardvalues[card.rank]
if card.rank == "Ace":
self.aces = self.aces + 1
def ace_adjust(self):
if self.value > 21 and self.aces > 0:
self.value = self.value - 10
self.aces = self.aces -1
class Funds:
def __init__(self):
self.balance= 0
self.bet = 0
def winbet(self):
self.balance = self.balance + self.bet * 2
def losebet(self):
self.bet = 0
def draw(self):
self.balance = self.balance + self.bet
self.bet = 0
def Place_a_Bet():
while True:
placebetamount = int(input(print('Select amount you want to bet.')))
if isinstance(placebetamount, int) == False:
print('Invalid bet type. You have to input a digit.')
continue
elif placebetamount > PlayerFunds.balance:
print('You tried to bet more money than you have available. You cannot bet more than: ' + PlayerFunds.balance)
continue
elif placebetamount <= 0:
print('Invaild Bet. You have to bet a positive number.')
continue
else:
PlayerFunds.balance = PlayerFunds.balance - placebetamount
PlayerFunds.bet = placebetamount
break
def hit(deck,hand):
hand.add_card(CurrentGameDeck.take_a_card())
hand.ace_adjust()
def hit_or_stand(deck, hand):
global playing # to control an upcoming while loop
Decision = input(str(print('Your Turn. Type "Hit" to get another card. Type "Stand" to move onto Dealers move')))
while True:
if Decision == "Hit":
hit(deck,hand)
elif Decision == "Stand":
playing = False
else:
print('just Hit or Stand. Other inputs are invalid')
continue
break
def CardStateGame(PlayerHand, DealerHand):
print('Dealer Shows : ' + DealerHand.cards[0] + ' out of ' + len(DealerHand.cards))
print('Dealer score is :' + DealerHand.value)
print('Your cards are ')
for card in PlayerHand.cards:
print(card)
print('and their value is: ' + PlayerHand.value)
def CardStateEndgame(PlayerHand, DealerHand):
print('Dealer value is ' + DealerHand.value + ' and his cards are: ')
for card in DealerHand.cards:
print(card)
print('Your cards are ')
for card in PlayerHand.cards:
print(card)
print('and their value is: ' + PlayerHand.value)
#end conditions
def player_bust(PlayerHand, PlayerFunds):
print('Value of your cards (' + PlayerHand.value +') exceeds 21. You lose.')
PlayerFunds.losebet()
def player_wins(PlayerFunds):
print('You won.')
PlayerFunds.winbet()
def dealer_bust(DealerHand, PlayerFunds):
print('Dealer loses, because value of his cards (' + DealerHand.value +') exceeds 21')
PlayerFunds.winbet()
def dealer_wins(PlayerFunds):
print('Dealer won.')
PlayerFunds.losebet()
def draw(PlayerFunds):
print('Both participants have same values. Its a draw')
PlayerFunds.draw()
#gameplay
print('This is a game of blackjack. You and the dealer (AI) will try to reach card value of 21, or just higher than your opponent. Scores higher than 21 will lose')
PlayerFunds = Funds()
while True:
startamount = int(input(print('Select the amount of money you enter the game with. Try to keep it plausible')))
if startamount <= 0 or isinstance(startamount, int) == False:
print('You cant play with that amount of money. try again')
continue
else:
PlayerFunds.balance = startamount
break
playing = True
while True:
CurrentGameDeck = Deck()
CurrentGameDeck.reroll()
Place_a_Bet()
DealerHand = Hand()
PlayerHand = Hand()
DealerHand.add_card(CurrentGameDeck.take_a_card())
PlayerHand.add_card(CurrentGameDeck.take_a_card())
DealerHand.add_card(CurrentGameDeck.take_a_card())
PlayerHand.add_card(CurrentGameDeck.take_a_card())
CardStateGame(PlayerHand, DealerHand)
while playing == True:
hit_or_stand(CurrentGameDeck,PlayerHand)
CardStateGame(PlayerHand, DealerHand)
if PlayerHand.value >21:
player_bust(PlayerHand, PlayerFunds)
break
if PlayerHand.value <= 21:
while DealerHand.value <17:
hit(CurrentGameDeck, DealerHand)
CardStateEndgame
if DealerHand.value > 21:
dealer_bust()
elif DealerHand.value > PlayerHand.value:
dealer_wins()
elif PlayerHand.value > DealerHand.value:
player_wins()
elif PlayerHand.value == DealerHand.value:
draw()
newgame = 0
newgame = input(print('Do you want to play again? Type Y or N'))
if newgame.lower() == 'Y' and PlayerFunds.balance >=0:
playing = True
continue
elif newgame.lower() == 'Y' and PlayerFunds.balance < 0:
print('no more funds. GG')
break
else:
print('thanks for playing')
break
I tried to use only
cardsuits = ['Hearts', 'Diamonds', 'Spades', 'Clubs']
cardrank = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace']
cardvalues = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
class Card:
#class card has two attributes: suit and rank. asking for string will result in rank of suit response. There is a value calcluated, using cardvalues dictionary.
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
def __str__(self):
return self.rank + ' of ' + self.suit
#def value(self):
# self.value = cardvalues[self.rank]
# #think about ace here; it can be worth 10 or 1 depending on hand
class Deck:
def __init__(self):
self.deck = []
for suit in cardsuits:
for rank in cardrank:
self.deck.append(Card(suit,rank))
def __str__(self):
deck_comp = ""
for card in self.deck:
deck_comp = deck_comp + "\n" + card.__str__()
return "Deck contains " + deck_comp
def reroll(self):
self.deck = random.shuffle(self.deck)
def take_a_card(self):
single_card = self.deck.pop()
return single_card
and then
test = Deck()
allows me to shuffle the deck, and pop a single card out of it - so other parts of the code may be a problem, but I have no idea which, where and why.
In the future you should try to slim your code down to pinpoint the problem. Since the issue was surrounding the deck you only really needed to post that class. The error you are getting is because of this function below:
def reroll(self):
self.deck = random.shuffle(self.deck)
If you take a look at the docs you will see that this function shuffles in place. Change the function to be this instead:
def reroll(self):
random.shuffle(self.deck)

BlackJack Game Main Script Trouble (Classes Already Done)

For my class project I am to make a BlackJack game that functions properly. It is a water-downed version of the game, (No Betting, Doubling Down , Splitting, etc...). We are to use different classes for the Deck, Hand and Card functions, which I did. The main trouble I am having is how to put it all together in a cohesive program so it can run. Here are my classes
class Card(object):
'''A simple playing card. A Card is characterized by two
components:
rank: an integer value in the range 2-14, inclusive (Two-Ace)
suit: a character in 'cdhs' for clubs, diamonds, hearts, and
spades.'''
#------------------------------------------------------------
SUITS = 'cdhs'
SUIT_NAMES = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
RANKS = range(2,15)
RANK_NAMES = ['Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten',
'Jack', 'Queen', 'King', 'Ace']
RANK_VALUES = [99, 99, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
#------------------------------------------------------------
def __init__(self, rank, suit):
'''Constructor
pre: rank in range(1,14) and suit in 'cdhs'
post: self has the given rank and suit'''
self.rank_num = rank
self.suit_char = suit
#------------------------------------------------------------
def getSuit(self):
'''Card suit
post: Returns the suit of self as a single character'''
return self.suit_char
#------------------------------------------------------------
def getRank(self):
'''Card rank
post: Returns the rank of self as an int'''
return self.rank_num
#------------------------------------------------------------
def getCardValue(self):
value = self.RANK_VALUES[self.rank_num]
return value
#------------------------------------------------------------
def suitName(self):
'''Card suit name
post: Returns one of ('clubs', 'diamonds', 'hearts',
'spades') corrresponding to self's suit.'''
index = self.SUITS.index(self.suit_char)
return self.SUIT_NAMES[index]
#------------------------------------------------------------
def rankName(self):
'''Card rank name
post: Returns one of ('ace', 'two', 'three', ..., 'king')
corresponding to self's rank.'''
index = self.RANKS.index(self.rank_num)
return self.RANK_NAMES[index]
#------------------------------------------------------------
def __str__(self):
'''String representation
post: Returns string representing self, e.g. 'Ace of Spades' '''
return self.rankName() + ' of ' + self.suitName()
#------------------------------------------------------------
from random import randrange
from Card import Card
from Hand import Hand
class Deck(object):
def __init__(self):
'''This creates the deck of cards, un-shuffled.'''
cards = []
for suit in Card.SUITS:
for rank in Card.RANKS:
cards.append(Card(rank,suit))
self.cards = cards
def size(self):
'''How many cards are left.'''
return len(self.cards)
def deal(self):
'''Deals a single card.
Pre: self.size() > 0
Post: Returns the next card in self, and removes it from self.'''
return self.cards.pop()
def shuffle(self):
'''This shuffles the deck so that the cards are in random order.'''
n = self.size()
cards = self.cards
for i,card in enumerate(cards):
pos = randrange(i,n)
cards[i] = cards[pos]
cards[pos] = card
def takeAHit(self, whatHand):
aCard = self.deal()
whatHand.addCard(aCard)
def __str__(self):
if self.size() == 52:
return 'The Deck is Full'
elif self.size() > 0:
return 'The Deck has been Used'
else:
return 'The Deck is Empty'
from Card import Card
class Hand(object):
"""A labeled collection of cards that can be sorted"""
#------------------------------------------------------------
def __init__(self, label=""):
"""Create an empty collection with the given label."""
self.label = label
self.cards = []
#------------------------------------------------------------
def add(self, card):
""" Add card to the hand """
self.cards.append(card)
#------------------------------------------------------------
def totalHand(self):
totalHand = 0
aceAmount = 0
for c in self.cards:
if c.getRank() == 14:
aceAmount += 1
totalHand +=c.getCardValue()
while aceAmount > 0:
if totalHand > 21:
aceAmount -= 1
totalHand -= 10
else:
break
return totalHand
def __str__(self):
if self.cards == []:
return "".join([(self.label), "doesn't have any cards."])
tempStringList = [ self. label, "'s Cards, "]
for c in self.cards:
tempStringList.append(str(c))
tempStringList.append(" , ")
tempStringList.pop()
tempStringList.append(" . ")
return "".join(tempStringList)
Now for the main function I need help on, my professor only helped me a little with part.
from Deck import Deck
from Card import Card
from Hand import Hand
def rules(playerTotal, dealerTotal):
if playerTotal > 21:
print "You busted!"
if dealerTotal == 21:
print 'To make it worse, dealer has 21.'
elif dealerTotal > 21:
print "The Dealer has busted. You win!"
elif playerTotal == 21:
print " You got 21! So you win!"
if dealerTotal == 21:
print "The Dealer also got 21. Tough Break."
elif dealerTotal == 21:
print "The Dealer got 21! Tough Break, you lose!"
else:
if playerTotal > dealerTotal:
print "You beat the Dealer! You got lucky punk."
if playerTotal == dealerTotal:
print "It is a push, no one wins!"
else:
print "Dealer wins! Better luck next time loser."
So I know I have to use the totalHand function from Hand to determine what the values are for playerTotal and dealerTotal, but everytime I try something I get this error.
Player1 = raw_input("What is your name?")
Dealer = "Dealer"
twoCards = Hand(Player1)
print twoCards.totalHand()
which prints out "none" and thats it..
If anyone can help me I would appreciated it, I'm kinda regretting my major choice as of now..
In no particular order:
Your shuffle is biased. Just use Python's random.shuffle(), it's correct and fast.
totalHand is wrong (never adds non-aces to the value), and is way too complicated because you chose to use 11 as the value of aces, and doesn't report whether a total is hard or soft (which you need for proper play). Change the value of aces to 1, and simplify:
*
def totalHand(self):
aceFound, isSoft = false, false
total = 0
for c in self.cards:
total += c.getCardValue()
if c.getCardValue() == 1:
aceFound = true
if aceFound and total < 12:
total += 10
isSoft = true
return total, isSoft
You can't base your results on just card totals. You have to play the hand in proper order:
If dealer has natural, play is over. Players with natural push,
all others lose.
Each player in turn plays his hand. Naturals are paid off and
removed, busts lose and are removed.
Dealer plays his hand. If he busts, all remaining players win,
otherwise players win/lose based on total.

BEGINNER: Python Value error: invalid literal for int()

Im making a simple blackjack program in python, but im getting a "ValueError: invalid literal for int() with base 10: ..." In order to get the total value of the player hands, after creating the card object, i try to get the rank of the card:
rank1 = Card.Card.getRank(card1)
heres the classs method:
def getRank(self):
if self.__rank == ('J'):
self.__rank = 10
return self.__rank
elif self.__rank == ('Q'):
self.__rank = 10
return self.__rank
elif self.__rank == ('K'):
self.__rank = 10
return self.__rank
elif self.__rank == ('A'):
self.__rank = 11
return self.__rank
else:
self.__rank = self.__rank
return int(self.__rank)`
the only time it returns the ValueError: invalid literal for int() with base 10 is if the rank is a 'Q' or 'K', it returns 10 for the 'J' and 11 for 'A'. I'm not getting why it returns an error for the 'Q' or 'K' since the code is the same for 'J' and 'A'... any help would be appreciated... if it helps, before that i had
heres the whole class
#Card class
#Class card holds ranks and suits of deck
#
TEN = 10
FOUR = 4
class Card():
#Create rank list
RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR
#Create list with rank names
rankNames=[None, 'Ace', 'Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
#Create suit list
suitNames = ['CLUBS','DIAMONDS', 'HEARTS', 'SPADES']
#Takes in rank, suit to create a deck of cards
def __init__(self, rank, suit):
self.__rank = rank
self.__suit = suit
#Returns the rank of card
def getRank(self):
if self.__rank == ('J'):
print (repr(self.__rank))
self.__rank = 10
return self.__rank
elif self.__rank == ('Q'):
self.__rank = 10
print (repr(self.__rank))
return self.__rank
elif self.__rank == ('K'):
print (repr(self.__rank))
self.__rank = 10
return self.__rank
elif self.__rank == ('A'):
print (repr(self.__rank))
self.__rank = 11
return self.__rank
else:
self.rank = self.__rank
print (repr(self.__rank))
return int(self.__rank)
#Returns suit of card
def getSuit(self):
return self.__suit
#Returns number of points the card is worth
def BJVaue(self):
if self.rank < 10:
return self.rank
else:
return TEN
def __str__(self):
return "%s of %s" % ([self.__rank], [self.__suit])
Heres where i create the card objects
#Create a player hand
player = []
#Draw two cards for player add append
player.append(drawCard())
player.append(drawCard())
#Display players cards
print ("You currently have:\n" , player)
#Get the rank of the card
card1 = player[0]
card2 = player[1]
#Update players card status
print (card1)
print (card2)
#Get the total of the hand
rank1 = Card.Card.getRank(card1)
rank2 = Card.Card.getRank(card2)
#Get the ranks of players cards
playerRank = [rank1 , rank2]
#Get total of players hand
totalPlayer = getTotal(playerRank)
#Display players total
print ("Your current total is: ", totalPlayer)
the getTotal function
def getTotal(rank):
#Create and set accumulator to 0
total = 0
#for each value in the rank
for value in rank:
#add to total
total += value
#Return total
return total
hope this helps
This line isn't right:
if self.__rank == ('J' or 'Q' or 'K'):
('J' or 'Q' or 'K') evaluates to 'J', so this line just checks whether self.__rank == 'J'.
You actually want:
if self.__rank in ('J', 'Q', 'K'):
I think your first code example should work. Are you sure that you're actually running the new code? If you try to import the same module into a running Python instance it won't pick up the changes. Also, if you redefine a class, existing instances will still have the old method implementations.
You've got fairly stinky code here - bad indentation, unnecessary brackets (are those strings or tuples?), nasty mix of functional and OO, static calls to non-static methods, etc.
The initial problem, "ValueError: invalid literal for int() with base 10: ..." means you are passing int() a value which it doesn't know how to translate into an integer. The question, then, is: what is that value, and where is it coming from?
Try substituting
VALUE = {
'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10,
'J':10, 'Q':10, 'K':10, 'A':11
}
def getValue(self):
try:
return Card.VALUE[self.__rank]
except KeyError:
print "%s is not a valid rank" % (self.__rank)
and see what you get. My guess would be that drawCard is generating rank values that Card.getValue doesn't know what to do with.
Other problems with your code:
TEN = 10
FOUR = 4
The whole point of using defined values is to provide semantic meaning and allow a single point of change; yet FOUR is no more contextually meaningful than 4, and I see no case in which changing the value of FOUR or TEN would make sense (indeed, if FOUR were ever to equal 3, it would be actively unhelpful in understanding your code). Try renaming them FACECARD_VALUE and NUMBER_OF_SUITS.
You are using "rank" to mean multiple different things: the character denoting a card and the value of a card to your hand. This will also increase confusion; try using face for one and value for the other!
You seem to be using drawCard() as a stand-alone function; how are you keeping track of what cards have already been dealt? Does it ever make sense to have, for example, two Ace of Spades cards dealt? I would suggest creating a Deck object which initializes 52 canonical cards, shuffles them, and then deck.getCard() returns a card from the list instead of creating it randomly.
See what you think of the following:
import random
class Deck():
def __init__(self):
self.cards = [Card(f,s) for f in Card.FACE for s in Card.SUIT]
self.shuffle()
def shuffle(self):
random.shuffle(self.cards)
def getCard(self):
return self.cards.pop()
class Card():
# Class static data
FACE = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')
NAME = ('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King')
RANK = (11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10)
SUIT = ('Clubs','Diamonds', 'Hearts', 'Spades')
def __init__(self, face, suit):
ind = Card.FACE.index(face)
self.__face = Card.FACE[ind] # the long way around, but keeps it consistent
self.__name = Card.NAME[ind]
self.__rank = Card.RANK[ind]
ind = Card.SUIT.index(suit)
self.__suit = Card.SUIT[ind]
def getFace(self):
return self.__face
def getName(self):
return self.__name
def getRank(self):
return self.__rank
def getSuit(self):
return self.__suit
def __str__(self):
return "%s of %s" % (self.__name, self.__suit)
def __repr__(self):
return "%s%s" % (self.__face, self.__suit[:1])
class Player():
def __init__(self):
self.cards = []
def drawCard(self, deck):
self.cards.append(deck.getCard())
def drawCards(self, deck, num=2):
for i in range(num):
self.drawCard(deck)
def getRank(self):
return sum( c.getRank() for c in self.cards )
def __str__(self):
cards = ', '.join(str(c) for c in self.cards)
return "%s: %d" % (cards, self.getRank())
def __repr__(self):
return ' '.join([repr(c) for c in self.cards])
class Game():
def __init__(self):
self.deck = Deck()
self.player1 = Player()
self.player2 = Player()
def test(self):
self.player1.drawCards(self.deck, 2)
print "Player 1:", self.player1
self.player2.drawCards(self.deck, 2)
print "Player 2:", self.player2
def main():
g = Game()
g.test()
if __name__=="__main__":
main()
rank1 = Card.Card.getRank(card1)
This looks like you're trying to call the getRank as a static method. getRank is expecting an instance of itself as the first parameter. This usually means you have a Card object, but the way you call it above, you don't have an object to pass it. I'ms urprised it even lets you call it like that. That should give you an incorrect number of arguments error.
Post more code, but it seems like you have serious fundamental problems with your design.
Update:
What's this?
RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR
Why do you need a list of 4 duplicates of your ranks?
Here is another approach to make a deck of cards
from itertools import product
card_values = (
("1", "1", 1),
("2", "2", 2),
("3", "3", 3),
("4", "4", 4),
("5", "5", 5),
("6", "6", 6),
("7", "7", 7),
("8", "8", 8),
("9", "9", 9),
("10" ,"10", 10),
("Jack", "J", 10),
("Queen", "Q", 10),
("King", "K", 10),
("Ace", "A", 11))
card_suits = ("Spades", "Clubs", "Hearts", "Diamonds")
class Card(object):
def __init__(self, name, short_name, rank, suit):
self.name = name
self.short_name = short_name
self.rank = rank
self.suit = suit
cards = []
for (name, short_name, rank), suit in product(card_values, card_suits):
cards.append(Card(name, short_name, rank, suit))
You could reduce the amount and complexity of your code by using a Python dictionary. If you did this, your getRank() function could look something like the following:
class Card(object):
RANK = {"A":1, "2":2, "3": 3, "4":4, "5": 5, "6": 6, "7":7,
"8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}
def __init__(self, draw): # just for example
self.__rank = draw
def getRank(self):
self.__rank = Card.RANK[self.__rank]
return self.__rank
# ...
print Card('A').getRank()
# 1
print Card('4').getRank()
# 4
print Card('J').getRank()
# 10
print Card('K').getRank()
# 10

Categories