1

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))

Works perfectly for number

how could I do it for kings or aces...

2

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.