Created
May 8, 2018 03:24
-
-
Save cjanis/2ea733e394aa5e37a39e3b1bdbaf0adb to your computer and use it in GitHub Desktop.
A simple blackjack game built with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## initiate game | |
print( | |
'\n' * 100 + | |
'#' * 16 + | |
'\n\nSIMPLE BLACKJACK' + | |
'\nby Craig Janis\n' + | |
'\nOverview: You start with two cards\nand decide whether to "hit" (ask\nfor another card) or "stand" (end\nyour turn with the cards you\nalready have). The dealer starts\nwith one card visible and one\ncard face down, and after your\nturn, the dealer will have a\nchance to hit or stand. You win\nif you end the game with more\npoints the dealer, but fewer\nthan 21 points. If you go over 21\npoints, that\'s called a "bust".\nTies go to the Dealer.\n\n' + | |
'#' * 16 | |
) | |
## press key to continue | |
''' | |
Without these periodic pauses, too much text is displayed at once and it's hard for users to read it all. I also added a hidden quit feature by typing q or quit during one of these pauses. It's helpful during testing. | |
''' | |
def go(text='proceed'): | |
go = input(f"\nHit enter to {text} > ") | |
if go in ['q','quit']: | |
print("\n Goodbye!\n\n\n") | |
quit() | |
## player class | |
class Player(): | |
def __init__(self,name='Player'): | |
self.name = name | |
self.stats = {'account':1000,'games':0} | |
def __str__(self): | |
return f"\n# PLAYER DATA\nName: {self.name}\nHand: X\nStats: X\n" | |
## create the player | |
name = '' | |
while not name: | |
name = input("\nWhat is your name? > ") | |
p = Player(name) | |
print(f"\n Welcome, {p.name}! Let's get started.") | |
## game play | |
def play(): | |
# create empty hands | |
hand_d = {'up':{},'down':{}} | |
hand_p = {} | |
# create deck | |
deck = {} | |
for suite in ('spades','diamonds','hearts','clubs'): | |
for i in range(2,11): | |
deck[f'{str(i)} of {suite}'] = i | |
for i in ('jack','queen','king'): | |
deck[f'{str(i)} of {suite}'] = 10 | |
deck[f'ace of {suite} (counted as 11)'] = 11 | |
# place bet | |
while True: | |
# update game count | |
p.stats['games'] += 1 | |
# ask for bet | |
print(f"\n This is game {p.stats['games']}. You currently have ${p.stats['account']}.") | |
bet = input(f"\nHow much will you bet? > ") | |
# validate input | |
try: | |
int(bet) | |
except: | |
print("Please enter a number!") | |
continue | |
# convert to integer | |
bet = int(bet) | |
# bet is greater than 0? | |
if bet <= 0: | |
print("Please enter a number greater than zero!") | |
continue | |
# can player afford the bet? | |
if not bet <= p.stats['account']: | |
print(f"You can't afford to bet ${bet}! Try again.") | |
continue | |
else: | |
p.stats['account'] = p.stats['account'] - bet | |
print(f"\n Your bet of ${bet} has been accepted. Let's deal your cards!") | |
break | |
go('deal the cards') | |
# status check | |
def status(): | |
# calculate dealer status | |
count = len(hand_d['up']) | |
count_value = sum(hand_d['up'].values()) | |
count_s = '' | |
if not count == 1: | |
count_s = 's' | |
count_down = '' | |
if sum(hand_d['down'].values()) > 0: | |
count_down = f" has 1 card facing down and" | |
# print dealer status | |
print(f"\n The dealer{count_down} is showing {count} card{count_s} worth {count_value} points:") | |
for i in hand_d['up'].keys(): | |
print(" - " + i) | |
# calculate player status | |
count = len(hand_p) | |
count_value = sum(hand_p.values()) | |
count_s = '' | |
if not count == 1: | |
count_s = 's' | |
# print player status | |
print(f"\n You are showing {count} card{count_s} worth {count_value} points:") | |
for i in hand_p.keys(): | |
print(" - " + i) | |
# results display | |
def results_display(): | |
status() | |
go('see who won') | |
count_d = sum(hand_d['up'].values()) | |
count_p = sum(hand_p.values()) | |
# player won | |
if (count_p <= 21) and ((count_p > count_d) or (count_d > 21)): | |
if (count_d > 21): | |
print('\n The Dealer has more than 21 points and busted!') | |
print(f"\n Good job, {p.name}, you win!\n You win ${bet*2}, double your ${bet} bet!") | |
# update player account | |
p.stats['account'] += int(bet)*2 | |
print(f" You now have ${p.stats['account']}.") | |
# dealer won | |
else: | |
if (count_p > 21): | |
print(f"\n You have more than 21 points and busted") | |
print(f"\n Sorry, {p.name}, you lose. You lost your ${bet} bet.") | |
print(f" You now have ${p.stats['account']}.") | |
# player still has money | |
if (p.stats['account'] > 0): | |
while True: | |
again = input("\nWould you like to play again? (Y/N) > ") | |
try: | |
again.lower() | |
except: | |
print("That's not an option!") | |
if (again.lower() in ['yes','y']): | |
play() | |
break | |
elif (again.lower() in ['no','n']): | |
print(f"\n Game over. You played {p.stats['games']} game(s) and ended with ${p.stats['account']}.\n\n\n") | |
quit() | |
# player is broke | |
else: | |
print(f"\n You're out of money!") | |
print(f" Game over, {p.name}. You played {p.stats['games']} game(s) and ended with ${p.stats['account']}.\n\n\n") | |
quit() | |
# results check | |
def results_check(final=False,dealer=False): | |
count_d = sum(hand_d['up'].values()) | |
count_p = sum(hand_p.values()) | |
# deal with aces | |
while (count_d > 21): | |
# is there at least one ace at 11? | |
if not 11 in hand_d['up'].values(): | |
break | |
# get first ace | |
count = 0 | |
for k,v in hand_d['up'].items(): | |
if (v == 11) and (count < 1): | |
count += 1 | |
# change 11 to 1 | |
k2 = k.replace("11","1") | |
hand_d['up'][k2] = 1 | |
del(hand_d['up'][k]) | |
# update count_d | |
count_d = sum(hand_d['up'].values()) | |
while (count_p > 21): | |
# is there at least one ace at 11? | |
if not 11 in hand_p.values(): | |
break | |
# get first ace | |
count = 0 | |
for k,v in hand_p.items(): | |
if (v == 11) and (count < 1): | |
count += 1 | |
# change 11 to 1 | |
k2 = k.replace("11","1") | |
hand_p[k2] = 1 | |
del(hand_p[k]) | |
# update count_p | |
count_p = sum(hand_p.values()) | |
# return results | |
if ((count_d > 21) or (count_p > 21) or final) or (dealer and count_d >= count_p): | |
return True | |
else: | |
return False | |
# deal function | |
def deal(hand,count): | |
import random | |
for i in range(0,count): | |
value = random.choice(list(deck)) | |
hand[value] = deck[value] | |
del deck[value] | |
return value | |
# initial deal visible and hidden cards to dealer | |
deal(hand_d['up'],1) | |
deal(hand_d['down'],1) | |
# initial deal to player | |
deal(hand_p,2) | |
status() | |
# dealer actions | |
def action_d(): | |
# hidden cards | |
while sum(hand_d['down'].values()) > 0: | |
for i in hand_d['down'].keys(): | |
hand_d['up'][i] = hand_d['down'][i] | |
hand_d['down'][i] = 0 | |
print(f"\n The Dealer turned over a hidden card: {i}") | |
if not results_check(False,True): | |
status() | |
go() | |
action_d() | |
else: | |
results_display() | |
# dealer hits | |
if (((sum(hand_d['up'].values()) < 18) and (sum(hand_d['up'].values()) < sum(hand_p.values()))) or (sum(hand_d['up'].values()) < sum(hand_p.values()))): | |
while ((sum(hand_d['up'].values()) < 18) and (sum(hand_d['up'].values()) < sum(hand_p.values()))) or (sum(hand_d['up'].values()) < sum(hand_p.values())): | |
card = deal(hand_d['up'],1) | |
print(f"\n The Dealer hit and has 1 new card: {card}") | |
if not results_check(False,True): | |
status() | |
go() | |
action_d() | |
else: | |
results_display() | |
else: | |
results_display() | |
# player actions | |
def action_p(): | |
while True: | |
action = input("\nWould you like to hit or stand? (H/S) > ").lower() | |
if action in ('hit','stand','h','s'): | |
break | |
else: | |
print("Sorry, that's not an option.") | |
# player hits | |
if action in ('hit','h'): | |
card = deal(hand_p,1) | |
print(f"\n You decided to hit! You have 1 new card: {card}") | |
if not results_check(): | |
status() | |
action_p() | |
else: | |
results_display() | |
else: | |
print("\n You decided to stand! Now it's the Dealer's turn ...") | |
go() | |
action_d() | |
action_p() | |
play() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cool cool)
It's a hot topic around git. Here a have red an article about gambling - https://gitlab.com/LeslieDavis22/top-popular-gambling-games/-/milestones/2
and I motivated to make my personal project. Will use yours as an example))