I am working on a Blackjack project.
I want to be able to use the letter "A" in a list of integers 2-10.
I am getting lost in the passing of the value of a string, in this case 'A' into the sum() function for the cards then returning that value but showing the 'A' in the cards is where I am getting lost.
For instance: cards = ['A',2,3,4,5,6,7,8,9,10]
The list will randomly return 2 values ranging from A-10 Then if A is returned with another number I want to calculate the value of the letter A the integer
It would print to the user something like "Your hand is: [A,7] Total = 18"
This is what I have been experimenting with so far.
import random
A = ord("A") - 64
def deal():
cards = [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player = []
dealer = []
while len(player) < 2:
player.append(random.choice(cards))
dealer.append(random.choice(cards))
return player, dealer
#this is ITERABLE UNPACK it separates the returned values from the deal() function and assigns them to their respective variables.
player, dealer = deal()
#sum the value of the cards
player_cards = sum(player)
dealer_cards = sum(dealer)
print(f"Your cards are {player}. Total = {player_cards}")
print(f"The dealer shows [{dealer[0]}, *]. Total = {dealer_cards}")
CodePudding user response:
Try:
player = ['A', 7]
def get_sum(cards):
return sum(card if not card == 'A' else 11 for card in cards)
print(get_sum(player))
Output:
18
If you have King, Queen and Jack, you can use this version:
player = ['A', 'K']
def get_sum(cards):
vals = {'A': 11, 'K': 10, 'Q': 10, 'J': 10}
return sum(vals.get(card, card) for card in cards)
print(get_sum(player))
Output:
21
CodePudding user response:
When dealing with cards, I would rather prefer to use random.sample(cards, len(cards))
because this is like to arbitrarily mix the cards.
def random_select(cards, k=2):
new_order = random.sample(cards, len(cards))
return new_order[:k], new_order[k:]
# and you can choose first 2 by:
two_cards, rest_deck = random_select(cards, k=2)
# and for next player you do:
two_next_cards, rest_deck = random_select(rest_deck, k=2)
# in this way, the already selected cards are removed from the original deck (rest_deck).
card_values = {'A': 11, 'K': 10, 'Q': 10, 'J': 10}
card_values.update({k: k for k in range(2, 11)})
# because I am too lazy to write all card values by hand
def card_sums(cards):
return sum([card_values[x] for x in cards])
def deal(players, cards, k=2):
result = {}
rest_cards = cards
for player in players:
chosen, rest_cards = random_select(rest_cards, k = k)
result[player] = chosen
return result, rest_cards
players = {'player': [], 'dealer': []}
selected_cards, rest_cards = deal(players, cards, k=2)
print(f"Your cards are {selected_cards[player]}. Total = {card_sums(selected_cards[player])}")
print(f"The dealer shows {selected_cards[dealer]}. Total = {card_sums(selected_cards[dealer])}")