Skip to content

Instantly share code, notes, and snippets.

@jasonbyrne
Last active March 9, 2024 13:17
Show Gist options
  • Save jasonbyrne/847adef4d7ef51aea50dc1db8b0b5a38 to your computer and use it in GitHub Desktop.
Save jasonbyrne/847adef4d7ef51aea50dc1db8b0b5a38 to your computer and use it in GitHub Desktop.
Black Jack Python Game - First time writing Python
import random
# List of available cards and values
cards = {
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"10": 10,
"Jack": 10,
"Queen": 10,
"King": 10,
"Ace": 11
}
# List of available suits
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
class Card:
def __init__(self, name, suit):
self.name = name
self.suit = suit
self.value = cards[name]
def __str__(self):
return f"{self.value} of {self.suit}"
class Hand:
def __init__(self, name, initialCards):
self.name = name
self.cards = []
for card in initialCards:
self.cards.append(card)
def add_card(self, card):
self.cards.append(card)
def list_cards(self):
for card in self.cards:
print(f"* {card}")
def count(self):
return len(self.cards)
def get(self, index):
return self.cards[index]
def __str__(self):
return f"{self.name} has {len(self.cards)} cards"
class Deck:
def __init__(self):
self.cards = []
for name in cards:
for suit in suits:
self.cards.append(Card(name, suit))
self.shuffle()
def shuffle(self):
random.shuffle(self.cards)
def deal(self):
return self.cards.pop()
def __str__(self):
return f"Deck of {len(self.cards)} cards"
class Round:
def __init__(self):
self.deck = Deck()
self.player_hand = Hand("You", [self.deck.deal(), self.deck.deal()])
self.dealer_hand = Hand("Dealer", [self.deck.deal(), self.deck.deal()])
def hit(self):
self.player_hand.add_card(self.deck.deal())
def player_total(self):
total = 0
for card in self.player_hand.cards:
total += cards[card.name]
return total
def dealer_total(self):
total = 0
for card in self.dealer_hand.cards:
total += cards[card.name]
return total
def stand(self):
while self.dealer_total() < 17:
self.dealer_hand.add_card(self.deck.deal())
def get_winner(self):
if self.player_total() > 21:
return "DEALER"
elif self.dealer_total() > 21:
return "PLAYER"
elif self.player_total() > self.dealer_total():
return "PLAYER"
elif self.dealer_total() > self.player_total():
return "DEALER"
else:
return "TIE"
def __str__(self):
return f"Player hand: {self.player_hand.get(0)} and {self.player_hand.get(1)}"
def start_round():
round = Round()
print("")
print("You are dealt:")
round.player_hand.list_cards()
print("")
print(f"Dealer is showing: {round.dealer_hand.get(0)}")
print("")
print(f"Your total: {round.player_total()}")
print(f"Dealer total: {round.dealer_hand.get(0).value}")
print("")
while True:
action = input("Would you like to hit? Y/N:")
if action.upper() == "Y":
round.hit()
print(f"You are dealt: {round.player_hand.get(-1)}")
print(f"Your total: {round.player_total()}")
if round.player_total() > 21:
print("Bust! You lose.")
break
elif action.upper() == "N":
round.stand()
print("You stand.")
print("")
print("Dealer has:")
round.dealer_hand.list_cards()
print("")
if round.dealer_hand.count() > 2:
## Loop through hand by length of dealer's hand
for i in range(2, round.dealer_hand.count()):
print(f"Dealer hits: {round.dealer_hand.get(i)}")
print("")
print(f"Dealer total: {round.dealer_total()}")
print(f"Your total: {round.player_total()}")
print("")
print("The winner is...")
print(f"{round.get_winner().upper()}!")
print("")
break
else:
print("Invalid input. Would you like to hit? Y/N:")
continue
def main():
print("")
print("WELCOME TO BLACKJACK!")
print("")
while True:
start_round()
play_again = input("Would you like to play again? Y/N:")
if play_again.upper() == "Y":
continue
elif play_again.upper() == "N":
print("")
print("Thanks for playing!")
print("")
break
else:
print("Invalid input. Please enter 'Y' or 'N'.")
continue
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment