Reputation: 19
I am trying to make a game of blackjack in python.Like a 7s value is a 7 but, a jacks value is a 10 so:
cards = ['ace','king','queen'....'3','2'
firstCard = random.choice(cards)
secondCard = random.choice(cards); remove.cards(firstCard)
print(int(firstCard) + int(secondCard))
how could I do it for kings or aces...
Upvotes: 1
Views: 757
Reputation: 31885
You can use a dictionary, keys are 'ace'
, 'king'
, 'queen'
, and values are corresponding numeric values. Based on the rule of your game, you can mapping the keys and values as you intend to.
mydict = {"ace": 1, "king": 13, "queen": 12}
num_of_queen = mydict["queen"] # gets the numeric value
Upvotes: 6
Reputation: 78650
I propose to wrap a regular dictionary in a class to make it a little easier to use:
class BlackJackDeck:
class NoSuchCard(Exception):
pass
values = {'king': 10,
'jack': 10,
'queen': 10,
'ace-high': 11,
'ace-low': 1}
values.update(zip(range(2, 11), range(2, 11)))
def __getitem__(self, item):
try:
item = int(item)
except (ValueError, TypeError):
item = item.lower()
try:
return self.values[item]
except KeyError:
raise self.NoSuchCard
Demo:
>>> d = BlackJackDeck()
>>> d[2]
2
>>> d['7']
7
>>> d['KING']
10
>>> d['ace-high']
11
>>> d[100]
[...]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "...", line 21, in __getitem__
raise self.NoSuchCard
d.NoSuchCard
This allows you to look up cards by integer- or by string-key, does not care about capitalization and throws a meaningful exception when a card does not exist.
Upvotes: 0
Reputation: 1616
Using a dictionary can help !
cards = {1:"ace": 1, 13:"king", 12:"queen"}
firstCard = random.choice(cards.keys())
secondCard = random.choice(cards.keys());
remove.cards(firstCard)
print(firstCard + secondCard)
To get the name of the card, you can:
cards[firstCard]
Upvotes: 0