from random import shuffle
from time import sleep
import os
# SET PLAYERS AND DEALERS WORKING VARIABLES
players_wallet = 500
dealers_wallet = 500
players_bid = 0
dealers_bid = 0
players_hand = []
dealers_hand = []
dealers_shown_hand = []
players_hand_value = 0
dealers_hand_value = 0
dealers_shown_hand_value = 0
players_turn = True
dealers_turn = False
last_chance = False
# SET CONSTANT VALUES OF CARD SUITS AND FACES TO CREATE DECK
# card_numbers = ["A", "2", "3", 'Q', 'K'] # SHORTENED VERSION FOR TESTING
card_numbers = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
suits = ["hearts", "clubs", "spades", "diamonds"]
suits_abbreviated = ["H", "C", "S", "D"]
full_deck = [f'{card_num}-{suit}' for suit in suits_abbreviated for card_num in card_numbers] # FULL DECK SORTED LIST
# CREATE COPY OF DECK AND SHUFFLE IT. THIS WILL BE THE DECK TO PLAY FROM
shuffled_deck = full_deck.copy()
shuffle(shuffled_deck)
# OPEN BANNER FILE AND SAVE STRING
with open('bj_banner.txt', 'r') as f:
blackjack_banner_file_string = f.read()
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX F U N C T I O N S XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
def clear_screen():
# Check if the operating system is Windows
if os.name == 'nt':
os.system('cls') # For Windows
else:
os.system('clear') # For other platforms like macOS and Linux
def play_blackjack():
global players_hand_value, dealers_hand_value, dealers_shown_hand_value, players_turn, dealers_turn, \
dealers_shown_hand, last_chance
# SET DEFAULT NUMBER OF CARDS TO DRAW TO 1
number_of_cards_to_draw = 1
# INITIALIZE GAME BY GIVING EACHI PLAYER 2 CARDS
initialize_game()
# PLAYERS TURN
while players_turn:
# PRINT SCOREBOARD AND MENU AND PROMPT USER FOR SELECTION
clear_screen()
print_scoreboard()
# CHECK IF PLAYERS WALLET IS TOO LOW
if players_wallet < 10:
last_chance = True
clear_screen()
print(blackjack_banner_file_string)
print('\n')
print('''
Look atch ya. Ya done wiped yourself out. Now yer scrapin the bottom of the barrel.
If you ask me, we outta kick ya on out with the rest of the horse manure right now!
But I recon we'll let you get on with one more game. But remember. If you lose this one.
You're out!. I don't wanna see yer face here no more!!!\n''')
input('''
Fair warning. Now go on press ENTER and continue: ''')
# check_for_winners(players_hand_value, dealers_hand_value)
print_selection_menu()
user_input = input('\n\t\tEnter a selection: ')
# CHECK USER INPUT
if user_input.lower() in ['x', '3']: # USER SELECTS QUIT
main_menu()
elif user_input.lower() in ['s', '2']: # USER SELECTS STAY
players_turn = False
dealers_turn = True
elif user_input.lower() == 'h' or not user_input: # USER SELECTS HIT
card_drawn = draw_card_from_deck(number_of_cards_to_draw) # DRAW CARD
players_hand_value += calculate_cards_value(card_drawn, 'p') # CALCULATE AND ADD TO HAND VALUE
players_hand.append(card_drawn) # APPEND TO HAND
# DEALERS TURN
while dealers_turn:
clear_screen()
# UPDATE DEALERS SHOWN HAND VALUES WHILE ITS HIS TURN
dealers_shown_hand = dealers_hand.copy()
dealers_shown_hand_value = dealers_hand_value
# PRINT SCOREBOARD AND MENU AND PROMPT USER FOR SELECTION
print_scoreboard()
print('\n\n\n', ' ' * 60, 'Dealers turn.', '\n', ' ' * 55, end='')
for _ in range(5):
sleep(.5)
print('* ', end='', flush=True)
# IMPLEMENT LOGIC FOR DEALERS DECISION TO HIT OR STAY.
# HIT: IF DEALERS HAND IS < 18
if dealers_hand_value < 18:
card_drawn = draw_card_from_deck(number_of_cards_to_draw) # DRAW CARD
dealers_hand_value += calculate_cards_value(card_drawn, 'd')
dealers_hand.append(card_drawn) # APPEND TO HAND
dealers_shown_hand = dealers_hand.copy()
dealers_shown_hand_value = dealers_hand_value
else: # STAY:
dealers_turn = False
# AFTER EVERYBODY HAS USED THEIR TURN, DECIDE THE WINNER
check_for_winners(players_hand_value, dealers_hand_value)
def round_reset():
global shuffled_deck, dealers_hand, dealers_hand_value, dealers_shown_hand_value, dealers_bid, players_hand, \
players_hand_value, players_bid, players_turn, dealers_turn, dealers_shown_hand
# CREATE COPY OF DECK AND SHUFFLE IT. THIS WILL BE THE DECK TO PLAY FROM
shuffled_deck = full_deck.copy()
shuffle(shuffled_deck)
# RESET DYNAMIC VARIABLES
players_bid = 0
dealers_bid = 0
players_hand = []
dealers_hand = []
dealers_shown_hand = []
players_hand_value = 0
dealers_hand_value = 0
dealers_shown_hand_value = 0
players_turn = True
dealers_turn = False
def initialize_game():
global players_hand_value, dealers_hand_value, dealers_shown_hand_value, dealers_wallet, players_wallet, \
players_bid, dealers_bid, dealers_shown_hand
round_reset()
# PRINT SCOREBOARD AND ASK USER FOR A BID (LOOP UNTIL BID CONDITIONS MET)
while True:
print(blackjack_banner_file_string)
print(f'\n\nYour wallet: ${players_wallet}')
print(f'Dealers Wallet: ${dealers_wallet}\n\n')
bid = input('Enter your bid amound: $')
# CHECK THAT ALL BID CONDITIONS WORK
if bid.isnumeric(): # CHECK THAT USER ENTERED ONLY A NUMBER ELSE: PRINT MESSAGE AND LOOP BACK
bid = int(bid)
if bid ==0:
print('\n\nNow just you listen up here feller! We dont take kindly to vagrants round here!\n'
'You best come up with sum\'n better than that or your outa here! Ye\' hear!\n\n')
input('Now go on and press ENTER to continue boy: ')
elif bid * 1.5 <= players_wallet: # CHECK THAT PLAYER CAN SUPPORT 1.5 x THE BID ELSE: PRINT MESSAGE AND LOOP BACK
if bid * 1.5 < dealers_wallet: # CHECK THAT DEALER CAN SUPPORT 1.5 x THE BID ELSE...
players_bid = bid
dealers_bid = bid
break
else:
print('\n\nThe Dealer cannot match your bid. Must be able to support 1.5 x the bid')
input('Press ENTER to enter a lower bid')
else:
print('\n\nYour wallet is too low. You must be able to support 1.5 x your bid')
input('Press ENTER to enter a lower bid')
else:
print('\n\nEnter only a number ya dick!')
input('Press ENTER to try again')
# START PLAYER AND DEALER WITH 2 CARDS EACH
for i in range(2):
drawn_card = draw_card_from_deck(1)
players_hand_value += calculate_cards_value(drawn_card, 'p')
players_hand.append(drawn_card)
drawn_card = draw_card_from_deck(1)
dealers_shown_hand = dealers_hand.copy()
dealers_shown_hand.append('X')
dealers_shown_hand_value = dealers_hand_value
dealers_hand_value += calculate_cards_value(drawn_card, 'd')
dealers_hand.append(drawn_card)
# ---------------- AFTER CARDS ARE DEALT, CHECK IF... ------------------
# MAKE A SEPERATE FUNCTION FOR THIS
# IF BOTH PARTIES GET A BLACKJACK
if players_hand_value == 21 and dealers_hand_value == 21:
clear_screen()
print(blackjack_banner_file_string)
print('\n\nThis is a double BLACKJACK must attend to this next')
ans = input('\nPress ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
play_blackjack()
# IF THE PLAYER GETS A BLACKJACK
elif players_hand_value == 21:
# AWARD THE PLAYER 1.5 x THE DEALERS BID AND SUBTRACT FROM DEALERS WALLET
players_wallet += dealers_bid * 1.5
dealers_wallet -= dealers_bid * 1.5
# NOTIFY USER THEN RESTART GAME
clear_screen()
print(blackjack_banner_file_string)
print_scoreboard()
print(f'\n\n{' ' * 20}You got a BLACKJACK. You win ${dealers_bid * 1.5}\n\n')
ans = input(f'\n{' ' * 22}Press ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
play_blackjack()
# IF THE DEALER GETS A BLACKJACK
elif dealers_hand_value == 21:
# AWARD THE DEALER 1.5 x THE PLAYERS BID AND SUBTRACT FROM THE PLAYERS WALLET
dealers_wallet += players_bid * 1.5
players_wallet -= players_bid * 1.5
clear_screen()
print(blackjack_banner_file_string)
print_scoreboard()
print(f'\n\n{' ' * 20}The dealer got a BLACKJACK. He wins ${players_bid * 1.5}')
ans = input(f'\n{' ' * 22}Press ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
play_blackjack()
def print_scoreboard():
# CLEAR SCREEN THEN DISPLAY BLACK JACK BANNER
clear_screen()
print(blackjack_banner_file_string)
# RESET SCOREBOARD STRINGS
your_lines = []
dealers_lines = []
# PRINT SCOREBOARD
your_lines.append(' ' * 25 + 'Your hand: ' + str(players_hand))
your_lines.append(' ' * 25 + 'Your hand value:' + str(players_hand_value))
your_lines.append(' ' * 25 + 'Your wallet: $' + str(players_wallet))
your_lines.append('')
your_lines.append(' ' * 25 + 'Your bid: $' + str(players_bid))
dealers_lines.append('Dealers shown hand: ' + str(dealers_shown_hand))
dealers_lines.append('Dealers shown hand value:' + str(dealers_shown_hand_value))
dealers_lines.append('Dealers wallet: $' + str(dealers_wallet))
dealers_lines.append('')
dealers_lines.append(' Dealers Bid: $' + str(dealers_bid))
print(' ' * 30 + 'Your stats:' + ' ' * 65 + 'Dealer stats:')
for i, line in enumerate(your_lines):
print(line + ' ' * (100 - len(line)) + dealers_lines[i])
# XXXXXXXXXXXXXXXXXXXXXX CODE DOESN'T WORK IN TERMINAL XXXXXXXXXXXXXXXXXXXXXXXXXXX
# your_lines = []
# dealers_lines = []
# your_lines.append(f'{' ' * 25}Your hand: {players_hand}')
# your_lines.append(f'{' ' * 25}Your hand value: {players_hand_value}')
# your_lines.append(f'{' ' * 25}Your wallet: ${players_wallet}')
# your_lines.append(f'\n{' ' * 25}Your bid: ${players_bid}')
# dealers_lines.append(f'Dealers hand: {dealers_hand[0:len(dealers_hand) - 1]}')
# dealers_lines.append(f'Dealers hand value: {dealers_hand_value}')
# dealers_lines.append(f'Dealers wallet: ${dealers_wallet}')
# dealers_lines.append(f' Dealers Bid: ${dealers_bid}')
#
# print(f'{' ' * 30}Your stats:{' ' * 65}Dealer stats:')
# for i, line in enumerate(your_lines):
# print(line + ' ' * (100 - len(line)) + dealers_lines[i])
def print_selection_menu():
# PRINT PLAYER INFORMATION AND STATS IN COORDINATED SPACE
print_scoreboard()
print("""\n\n
\tActions: (Press key)
\t1.) ENTER to Hit
\t2.) 'S' to Stay
\t3.) 'X' to QUIT
""")
def check_for_winners(players_score, dealers_score):
global players_wallet, players_bid, dealers_wallet, dealers_bid, dealers_shown_hand, dealers_shown_hand_value, \
last_chance
# CHECK IF BOTH LOST
if players_score > 21 and dealers_score > 21:
print('\n\nNobody won this round')
ans = input('\nPress ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
# CHECK IF BOTH HAD THE SAME SCORE
elif players_score == dealers_score:
print('\n\nNobody won this round')
ans = input('\nPress ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
# CHECK IF PLAYER WON
elif dealers_score > 21 or (21 - players_score) < (21 - dealers_score) and players_score <= 21:
players_wallet += dealers_bid
dealers_wallet -= dealers_bid
print(f'\n\nYou win this match.\nYou win ${dealers_bid}')
if last_chance:
last_chance = False
print('You lucky son of a gun you. Your back in the game... For now...')
ans = input('\nPress ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
# CHECK IF DEALER WON
elif players_score > 21 or (21 - dealers_score) < (21 - players_score) and dealers_score <= 21:
dealers_wallet += players_bid
players_wallet -= players_bid
print(f'\n\nThe dealer won this match.\nHe won ${dealers_bid}')
ans = input('\nPress ENTER to continue or x to QUIT: ')
if ans.lower() == 'x':
main_menu()
if last_chance:
clear_screen()
print(blackjack_banner_file_string)
print(f"""
Now I told you boy. You were on your last leg and now you ain't got a single leg to stand on.
That's it you're done. Take your last ${players_wallet} and go on. Get!""")
input('Press ENTER: ')
players_wallet = 500
dealers_wallet = 500
last_chance = False
round_reset()
main_menu()
# START NEW ROUND
play_blackjack()
def draw_card_from_deck(amount=1):
picked_cards = []
# IF THE DECK HAS NOT BEEN SHUFFLED, NOTIFY THE USER THEN RETURN TO THE MAIN MENU
if not shuffled_deck:
print('\nYou must shuffle the deck to start!')
return
# CHECK IF THERE ARE ENOUGH CARDS IN THE DECK
if len(shuffled_deck) < amount:
print('Not enough cards in the deck.')
# POP CARD FROM TOP OF DECK AND RETURN IT
for i in range(amount):
picked_cards.append(shuffled_deck.pop())
if amount > 1:
return picked_cards
else:
return picked_cards[0]
def calculate_cards_value(card, calculating_for):
global players_hand_value, dealers_hand_value
add_value = 0
# CHECK PLAYERS CARDS
if card[0] in ['J', 'Q', 'K']:
add_value = 10
elif card[0].isnumeric():
if card[0] == '1':
add_value = 10
else:
add_value = int(card[0])
elif card[0] == 'A':
add_value = aces_high_low_desicion(calculating_for, card)
return add_value
def aces_high_low_desicion(assign_aces_for, the_card):
aces_value = 11
if 'p' in assign_aces_for.lower():
while True:
print(f'\n\nYou have an ACE of {suits[suits_abbreviated.index(the_card[-1])].title()}. Your current hand is'
f' at {players_hand_value}.')
ace = input("Do you want ace's high or ace's low? Press (+/-): ")
if '+' in ace:
aces_value = 11
break
elif '-' in ace:
aces_value = 1
break
else:
print("\nInvalid selection. You must enter + (ace's high) or - (ace's low)\n")
elif 'd' in assign_aces_for.lower():
if dealers_hand_value + 11 <= 21:
aces_value = 11
else:
aces_value = 1
return aces_value
def main_menu():
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX M A I N L O O P XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
while True:
clear_screen()
print(blackjack_banner_file_string)
print("""\n\n
\t1.) Play Black Jack
\t2.) EXIT
""")
user_selection = input("\n\t\tEnter Selection: ")
match user_selection.lower():
case '1':
with open('var_log.txt', 'a') as log_file:
log_file.write('-------------- STARTING NEW HAME ---------------\n')
play_blackjack()
case 'x' | '2':
print('\n\tThanks for playing. See you next time!')
exit()
case _:
print('\n\tInvalid Entry\n')
main_menu()