import random ranks = [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K' ] suits = [ 'Spades', 'Clubs', 'Hearts', 'Diamonds' ] d = [ ( rank, suit ) for rank in ranks for suit in suits ] random.shuffle( d ) def d_c ( d ) : return d.pop( 0 ) def d_i_c( d, ph, dh ) : for _ in range( 2 ) : ph.append(d_c(d)) dh.append(d_c(d)) def c_h_v( h ) : v = 0 na = 0 for c in h : rank = c[0] if rank in ["J", "Q", "K" ] : v += 10 elif rank == "A" : na += 1 v += 11 else: v += int(rank) while v > 21 and na > 0 : v -= 10 na -= 1 return v def dis_h(h, hidden=False) : if hidden : print( "Hidden Card" ) for c in h[1:] : print(c) else : for c in h : print(c) print( "Total value:", c_h_v(h) ) def p_t( d, ph, dh ) : while True: dis_h( ph ) c = input( "Do you want to stand? (H/S) " ).lower() if c == "h" : ph.append( d_c( d ) ) if c_h_v( ph ) > 21 : dh( ph ) print( "You bust! Dealer wins." ) return 'bust' elif c == "s" : return 'stand' else : print( "Invalid choice. Please enter 'h' or's'.") def d_t( d, dh ) : while c_h_v( dh ) <17 : dh.append( d_c( d ) ) if c_h_v( dh ) > 21 : return "Bust" return "stand" def d_w( ph, dh ) : pv = c_h_v( ph ) dv = c_h_v( dh ) if pv > 21: return 'dealer' elif dv > 21 : return 'player' elif pv > dv : return 'player' elif pv < dv : return 'dealer' else : return 'tie' def p_bj() : print( "Welcome to blackjack!" ) while True : d = [ ( rank, suit ) for rank in ranks for suit in suits ] random.shuffle( d ) ph = [] dh = [] d_i_c( d, ph, dh ) pr = p_t( d, ph, dh ) if pr == "Bust" : continue dr = d_t( d, dh ) if dr == "Bust" : print( "Dealer busts! Player wins." ) continue w = d_w( ph, dh ) if w == 'player' : print( "Player wins!" ) elif w == 'dealer' : print( "Dealer wins!" ) else : print( "Its a tie!" ) pa = input( "Do you want to play again? (y/n): " ).lower() if pa != 'y' : print( "Thanks for playing!" ) break p_bj()