Berke Şentürk
Berke Şentürk

Reputation: 119

How to get value of key in Python Blackjack game

I just started a blackjack game project. So far, i've created cards and hand creator funtion. As you can see from my code down below, i pick my hand through pick() function and i get the keys of the rank dictionary.

rank={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,
   'K':10,'Q':10,'A':1}
your_hand=[]
opponent_hand=[]
def pick():    
    your_hand =  random.sample(list(rank),2) 
    opponent_hand = random.sample(list(rank),2) 
    print(your_hand[values])
    print(opponent_hand)
def count():
    pass

I was wondering is this code getting their values and if not, how can i get their values? Also is this a good approach for coding a blackjack game.

Upvotes: 0

Views: 318

Answers (2)

SimonR
SimonR

Reputation: 1824

Passing a dict to list() returns a list of the keys. So your_hand is a list, containing keys to the rank dictionary. To get the corresponding values:

your_hand_values = [rank[card] for card in your_hand]

You might consider storing both the card and it's value in the your_hand list from the beginning, like this :

your_hand =  [(card, value) for card, value in random.sample(rank.items(), 2)]

(As a side note, this is a project crying out for an OOP approach. Just my 2 cents.)

Upvotes: 0

Samwise
Samwise

Reputation: 71512

The variable values isn't connected to anything, so you'll get a NameError when you try to reference it.

The lists your_hand and opponent_hand contain lists of strings (keys in rank). To convert those into the values from rank, you need to use the keys to do lookups, e.g.:

your_hand_values = [rank[card] for card in your_hand]

which will give you a list of ints. If you want to get the sum, you could use sum:

your_hand_total = sum(rank[card] for card in your_hand)

On to the larger question, one problem with this approach is that it's not possible for a hand to have more than one card with the same rank, where a real deck of cards has 4 suits.

Since building a blackjack game is a pretty common beginner coding problem I keep this post bookmarked for when someone asks how I'd do it. :) https://codereview.stackexchange.com/questions/234880/blackjack-21-in-python3/234890#234890

Upvotes: 1

Related Questions