# something close to blackjack

import random

cards = {'ace':1,'two':2,'three':3,'four':4,'five':5,'six':6,
         'seven':7,'eight':8,'nine':9,'ten':10,'jack':10,
         'queen':10,'king':10}

# example: the_hand = ['king','two']
def handvalue(the_hand):
    total = 0
    for cardname in the_hand:
        total += cards[cardname]

    if 'ace' in the_hand:
        if total <= 11:
            total += 10   # we are counting the ace as 11 not 1 here
        
    return total
    
# example: the_hand = ['king','two']
def display_hand(the_hand, name_of_hand='Player'):
    print(f'{name_of_hand} Hand is: {the_hand}')
    hv = handvalue(the_hand)
    print(f'Value of {name_of_hand} hand is: {hv}')


def deal_a_hand():
    cardnames = list(cards.keys())
    dealer_hand = []
    dealer_hand.append(random.choice(cardnames))
    dealer_hand.append(random.choice(cardnames))
    print('--------------------------')
    print('Dealer up card is ' + dealer_hand[1])
    
    player_hand = []
    player_hand.append(random.choice(cardnames))
    player_hand.append(random.choice(cardnames))
    # player_hand has 2 cards
    display_hand(player_hand)
    finish_dealer_hand = False
    while True:
        hv = handvalue(player_hand)
        if hv == 21:
            print('Congratulations your hand is 21.')
            finish_dealer_hand = True
            break
        elif hv > 21:
            print('Bust')
            break
        userchoice = input('Hit or Stay')
        print()
        if userchoice == 'Hit' or userchoice == 'hit':
            player_hand.append(random.choice(cardnames))
            display_hand(player_hand)
        else:
            # assume they typed Stay
            print('OK, your final hand is:')
            display_hand(player_hand)
            print()
            finish_dealer_hand = True
            break

    if finish_dealer_hand:
        # implement the rules that dealer must hit on <= 16 and stay on 17 or higher
        # dealer_hand currently contains 2 cards
        dealer_hv = handvalue(dealer_hand)
        while dealer_hv <= 16:
            # hit
            dealer_hand.append(random.choice(cardnames))
            # recompute dealer_hv
            dealer_hv = handvalue(dealer_hand)

        
        display_hand(dealer_hand, name_of_hand='Dealer')
        
        # we get here when? dealer_hv > 16
        if dealer_hv > 21:
            print('Dealer busts')
        elif dealer_hv > hv:
            print(f'Dealer wins with {dealer_hv} against player\'s {hv}.')
        elif dealer_hv == hv:
            print('Tie')
        else:
            print(f'Player wins with {hv} against dealer\'s {dealer_hv}.')
        
            
        
user_choice = ''
while user_choice != 'q':
    deal_a_hand()
    user_choice = input('Enter q to quit or anything else to continue')
    
