'How to add a Value to Each Card in a Deck of Cards
So I have been stuck on this for a few days I have the deck of cards created and it works but I don't know how I would make each card have a value without using 52 if/elif statements for a BlackJack game. How would i make 10 of spades = 10, 9 of clubs = 9 etc.
import random
#card class to take suit and value self
class Card:
def __init__(self, suit, val):
self.suit = suit
self.value = val
def show(self):
print (f"{self.value} of {self.suit}")
#creates the deck class
class Deck:
def __init__(self):
self.cards = []
self.build()
#appends each suit and each val of the card to give us 52 cards (4 * 13 = 52)
def build(self):
for s in ["Spades", "Clubs", "Diamonds", "Hearts"]:
for v in range (1,14):
if v == 1:
self.cards.append(Card(s,"Ace")) #code that turns 1s into aces
elif v == 11:
self.cards.append(Card(s,"Queen")) #code that turns 11 into queens
elif v == 12:
self.cards.append(Card(s, "King")) #code that turns 12 into kings
elif v == 13:
self.cards.append(Card(s,"Jack")) #code that turns 13 into Jacks
else:
self.cards.append(Card(s,v))
def show(self):
for c in self.cards:
c.show()
#shuffle method using the Fisher Yates Shuffle Algorithm
def shuffle(self):
for i in range(len(self.cards) - 1, 0, -1):
r = random.randint(0, i)
self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
def drawCard(self):
return self.cards.pop()
#dealer class
class Dealer:
global currentCard
def __init__(self, name):
self.name = name
self.hand = []
def draw(self,deck):
self.hand.append(deck.drawCard())
return self
def showHand(self):
for card in self.hand:
currentCard = card.show()
deck = Deck()
deck.shuffle()
dealer = Dealer("Dealer")
dealer.draw(deck)
dealer.showHand()
Solution 1:[1]
In term of the value you should first figure out where you want to handle that functionality. In terms of generally naming the cards you could assume them to be ordered in a pattern so that they are defined by their number and use modulo to get the suit and value. For example:
for i in range(0,52)
Card(suit=i//13,val=i%13)
The modulo operator % just gives you "the rest" of a division, so if you operate with whole numbers (no decimal fractions) then 10//3 is 3 and a rest of 1 because 3*3+1 = 10. So if you use modulo 13 (cards in a suit), that should give you a number between 0 and 12 (or 1 and 13 if you add 1) while i//13 rounds down to the nearest whole number which would give you a number between 0 and 3 (or 1 and 4) which can be used for the suits.
And once you have that you can use a dictionary or just a list with suits and card names that translate the numbers to names. Now in terms of values you could either derive them from the card names in a similar fashion but I'd rather deal with them on the level of the game logic as for example and ace could be both a 1 and an 11 (right?) so dealing with that when it's necessary would make more sense than to assign a value at initialization.
Solution 2:[2]
Every card needs two attributes - a suit and a value. The value will depend on the type of card game you're "playing". A common approach would be to assign values in the range 2->14
Consider this and note the absence of cumbersome if/else constructs:
import random
class CARD:
suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
names = {2: 'Two',
3: 'Three',
4: 'Four',
5: 'Five',
6: 'Six',
7: 'Seven',
8: 'Eight',
9: 'Nine',
10: 'Ten',
11: 'Jack',
12: 'Queen',
13: 'King',
14: 'Ace'}
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __str__(self):
return f'{CARD.names[self.value]} of {self.suit} has a value of {self.value}'
class DECK:
def __init__(self):
self.cards = None
def get_cards(self):
if self.cards is None:
self.cards = [CARD(CARD.suits[n % 4], n % 13 + 2) for n in range(52)]
return self.cards
def get_random_card(self):
return random.choice(self.get_cards())
D = DECK()
# pick some cards at random
for _ in range(5):
print(D.get_random_card())
Output (similar to):
Queen of Spades has a value of 12
Five of Diamonds has a value of 5
Nine of Diamonds has a value of 9
Four of Clubs has a value of 4
Three of Clubs has a value of 3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | haxor789 |
| Solution 2 | Albert Winestein |
