Text-based Blackjack Game
Abstract
Build a fully functional text-based blackjack game that implements classic casino rules, card dealing, betting systems, and game logic. This project demonstrates object-oriented programming, game state management, and complex conditional logic.
Prerequisites
- Python 3.6 or above
- Text Editor or IDE
- Solid understanding of Python syntax
- Knowledge of object-oriented programming (classes, objects)
- Familiarity with game logic and conditional statements
- Understanding of loops and user input handling
Getting Started
Create a new project
- Create a new project folder and name it
blackjackGame
blackjackGame
. - Create a new file and name it
blackjack.py
blackjack.py
. - Open the project folder in your favorite text editor or IDE.
- Copy the code below and paste it into your
blackjack.py
blackjack.py
file.
Write the code
- Add the following code to your
blackjack.py
blackjack.py
file.
โ๏ธ Text-based Blackjack Game
# Text-based Blackjack Game
import random
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
def value(self):
if self.rank in ['Jack', 'Queen', 'King']:
return 10
elif self.rank == 'Ace':
return 11 # Will be handled in Hand class
else:
return int(self.rank)
class Deck:
def __init__(self):
self.cards = []
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
for suit in suits:
for rank in ranks:
self.cards.append(Card(suit, rank))
self.shuffle()
def shuffle(self):
random.shuffle(self.cards)
def deal_card(self):
return self.cards.pop()
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self, card):
self.cards.append(card)
self.value += card.value()
# Track aces
if card.rank == 'Ace':
self.aces += 1
# Adjust for aces
self.adjust_for_ace()
def adjust_for_ace(self):
# If total value > 21 and we have aces, convert ace from 11 to 1
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
def __str__(self):
hand_str = "Hand contains:\n"
for card in self.cards:
hand_str += f" {card}\n"
hand_str += f"Total value: {self.value}"
return hand_str
class Chips:
def __init__(self, total=100):
self.total = total
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
chips.bet = int(input(f"You have {chips.total} chips. How many would you like to bet? "))
except ValueError:
print("Sorry, please enter a valid number!")
else:
if chips.bet > chips.total:
print(f"Sorry, you only have {chips.total} chips!")
else:
break
def hit(deck, hand):
hand.add_card(deck.deal_card())
def hit_or_stand(deck, hand):
global playing
while True:
choice = input("\nWould you like to Hit or Stand? Enter 'h' or 's': ").lower()
if choice == 'h':
hit(deck, hand)
elif choice == 's':
print("Player stands. Dealer is playing.")
playing = False
else:
print("Sorry, please try again.")
continue
break
def show_some(player, dealer):
print("\nDealer's Hand:")
print(" <card hidden>")
print(f" {dealer.cards[1]}")
print(f"\nPlayer's Hand: {player.value}")
for card in player.cards:
print(f" {card}")
def show_all(player, dealer):
print("\nDealer's Hand:", dealer.value)
for card in dealer.cards:
print(f" {card}")
print(f"\nPlayer's Hand: {player.value}")
for card in player.cards:
print(f" {card}")
def player_busts(player, dealer, chips):
print("Player busts! Dealer wins!")
chips.lose_bet()
def player_wins(player, dealer, chips):
print("Player wins!")
chips.win_bet()
def dealer_busts(player, dealer, chips):
print("Dealer busts! Player wins!")
chips.win_bet()
def dealer_wins(player, dealer, chips):
print("Dealer wins!")
chips.lose_bet()
def push(player, dealer):
print("Dealer and Player tie! It's a push.")
# Game Logic
def play_blackjack():
global playing
playing = True
print("Welcome to BlackJack! Get as close to 21 as you can without going over!")
print("Dealer hits until she reaches 17. Aces count as 1 or 11.")
# Create & shuffle the deck, deal two cards to each player
deck = Deck()
player_hand = Hand()
dealer_hand = Hand()
player_hand.add_card(deck.deal_card())
player_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
# Set up the Player's chips
player_chips = Chips()
# Prompt the Player for their bet
take_bet(player_chips)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
while playing: # recall this variable from our hit_or_stand function
# Prompt for Player to Hit or Stand
hit_or_stand(deck, player_hand)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
# If player's hand exceeds 21, run player_busts() and break out of loop
if player_hand.value > 21:
player_busts(player_hand, dealer_hand, player_chips)
break
# If Player hasn't busted, play Dealer's hand until Dealer reaches 17
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck, dealer_hand)
# Show all cards
show_all(player_hand, dealer_hand)
# Run different winning scenarios
if dealer_hand.value > 21:
dealer_busts(player_hand, dealer_hand, player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand, dealer_hand, player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand, dealer_hand, player_chips)
else:
push(player_hand, dealer_hand)
# Inform Player of their chips total
print(f"\nPlayer's winnings stand at {player_chips.total}")
# Ask to play again
new_game = input("Would you like to play another hand? Enter 'y' or 'n': ").lower()
if new_game == 'y':
playing = True
play_blackjack()
else:
print("Thanks for playing!")
if __name__ == "__main__":
play_blackjack()
# Text-based Blackjack Game
import random
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
def value(self):
if self.rank in ['Jack', 'Queen', 'King']:
return 10
elif self.rank == 'Ace':
return 11 # Will be handled in Hand class
else:
return int(self.rank)
class Deck:
def __init__(self):
self.cards = []
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
for suit in suits:
for rank in ranks:
self.cards.append(Card(suit, rank))
self.shuffle()
def shuffle(self):
random.shuffle(self.cards)
def deal_card(self):
return self.cards.pop()
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0
def add_card(self, card):
self.cards.append(card)
self.value += card.value()
# Track aces
if card.rank == 'Ace':
self.aces += 1
# Adjust for aces
self.adjust_for_ace()
def adjust_for_ace(self):
# If total value > 21 and we have aces, convert ace from 11 to 1
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
def __str__(self):
hand_str = "Hand contains:\n"
for card in self.cards:
hand_str += f" {card}\n"
hand_str += f"Total value: {self.value}"
return hand_str
class Chips:
def __init__(self, total=100):
self.total = total
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
chips.bet = int(input(f"You have {chips.total} chips. How many would you like to bet? "))
except ValueError:
print("Sorry, please enter a valid number!")
else:
if chips.bet > chips.total:
print(f"Sorry, you only have {chips.total} chips!")
else:
break
def hit(deck, hand):
hand.add_card(deck.deal_card())
def hit_or_stand(deck, hand):
global playing
while True:
choice = input("\nWould you like to Hit or Stand? Enter 'h' or 's': ").lower()
if choice == 'h':
hit(deck, hand)
elif choice == 's':
print("Player stands. Dealer is playing.")
playing = False
else:
print("Sorry, please try again.")
continue
break
def show_some(player, dealer):
print("\nDealer's Hand:")
print(" <card hidden>")
print(f" {dealer.cards[1]}")
print(f"\nPlayer's Hand: {player.value}")
for card in player.cards:
print(f" {card}")
def show_all(player, dealer):
print("\nDealer's Hand:", dealer.value)
for card in dealer.cards:
print(f" {card}")
print(f"\nPlayer's Hand: {player.value}")
for card in player.cards:
print(f" {card}")
def player_busts(player, dealer, chips):
print("Player busts! Dealer wins!")
chips.lose_bet()
def player_wins(player, dealer, chips):
print("Player wins!")
chips.win_bet()
def dealer_busts(player, dealer, chips):
print("Dealer busts! Player wins!")
chips.win_bet()
def dealer_wins(player, dealer, chips):
print("Dealer wins!")
chips.lose_bet()
def push(player, dealer):
print("Dealer and Player tie! It's a push.")
# Game Logic
def play_blackjack():
global playing
playing = True
print("Welcome to BlackJack! Get as close to 21 as you can without going over!")
print("Dealer hits until she reaches 17. Aces count as 1 or 11.")
# Create & shuffle the deck, deal two cards to each player
deck = Deck()
player_hand = Hand()
dealer_hand = Hand()
player_hand.add_card(deck.deal_card())
player_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
dealer_hand.add_card(deck.deal_card())
# Set up the Player's chips
player_chips = Chips()
# Prompt the Player for their bet
take_bet(player_chips)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
while playing: # recall this variable from our hit_or_stand function
# Prompt for Player to Hit or Stand
hit_or_stand(deck, player_hand)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
# If player's hand exceeds 21, run player_busts() and break out of loop
if player_hand.value > 21:
player_busts(player_hand, dealer_hand, player_chips)
break
# If Player hasn't busted, play Dealer's hand until Dealer reaches 17
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck, dealer_hand)
# Show all cards
show_all(player_hand, dealer_hand)
# Run different winning scenarios
if dealer_hand.value > 21:
dealer_busts(player_hand, dealer_hand, player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand, dealer_hand, player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand, dealer_hand, player_chips)
else:
push(player_hand, dealer_hand)
# Inform Player of their chips total
print(f"\nPlayer's winnings stand at {player_chips.total}")
# Ask to play again
new_game = input("Would you like to play another hand? Enter 'y' or 'n': ").lower()
if new_game == 'y':
playing = True
play_blackjack()
else:
print("Thanks for playing!")
if __name__ == "__main__":
play_blackjack()
- Save the file.
- Run the following command to run the application.
C:\Users\username\Documents\blackjackGame> python blackjack.py
Welcome to BlackJack! Get as close to 21 as you can without going over!
Dealer hits until she reaches 17. Aces count as 1 or 11.
How many chips would you like to play with? 100
Betting
-------
Current chips: 100
How much chips would you like to bet? 20
Dealer Hand:
<card hidden>
Four of Hearts
Player Hand:
Jack of Spades
Seven of Hearts
Total: 17
Would you like to Hit or Stand? Enter 'h' or 's' s
Dealer Wins!
Player chips total only 80
Would you like to play again? y/n y
C:\Users\username\Documents\blackjackGame> python blackjack.py
Welcome to BlackJack! Get as close to 21 as you can without going over!
Dealer hits until she reaches 17. Aces count as 1 or 11.
How many chips would you like to play with? 100
Betting
-------
Current chips: 100
How much chips would you like to bet? 20
Dealer Hand:
<card hidden>
Four of Hearts
Player Hand:
Jack of Spades
Seven of Hearts
Total: 17
Would you like to Hit or Stand? Enter 'h' or 's' s
Dealer Wins!
Player chips total only 80
Would you like to play again? y/n y
- Run the Blackjack Game
python blackjack.py
python blackjack.py
## Explanation
1. The `import random` statement imports the random module for card shuffling and dealing.
2. The `class Card:` defines individual playing cards with suit and rank attributes.
3. The `class Deck:` creates a full 52-card deck with shuffling functionality.
4. The `class Hand:` manages collections of cards and calculates hand values.
5. The `class Chips:` handles the betting system and chip management.
6. The ace handling logic automatically adjusts ace values from 11 to 1 when needed.
7. The `hit_or_stand()` function handles player decisions during gameplay.
8. The dealer follows standard casino rules (hits until 17 or higher).
9. The game loop allows for multiple rounds of play.
10. Win/loss conditions check for busts, blackjacks, and hand comparisons.
11. The betting system tracks wins and losses with chip adjustments.
12. Input validation ensures proper user responses throughout the game.
## Next Steps
Congratulations! You have successfully created a Text-based Blackjack Game in Python. Experiment with the code and see if you can modify the application. Here are a few suggestions:
- Add GUI interface with card graphics
- Implement double down and split functionality
- Add insurance betting option
- Create multiplayer support for multiple players
- Add statistics tracking (wins, losses, streaks)
- Implement different difficulty levels
- Add sound effects and animations
- Create tournament mode with multiple rounds
- Add card counting practice features
## Conclusion
In this project, you learned how to create a Text-based Blackjack Game in Python using object-oriented programming. You also learned about game logic, state management, and implementing classic card game rules. You can find the source code on [GitHub](https://github.com/Ravikisha/PythonCentralHub/blob/main/projects/beginners/blackjack.py)
## Code Explanation
### Card and Deck Classes
```python title="blackjack.py" showLineNumbers{1}
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def value(self):
if self.rank in ['Jack', 'Queen', 'King']:
return 10
elif self.rank == 'Ace':
return 11
else:
return int(self.rank)
## Explanation
1. The `import random` statement imports the random module for card shuffling and dealing.
2. The `class Card:` defines individual playing cards with suit and rank attributes.
3. The `class Deck:` creates a full 52-card deck with shuffling functionality.
4. The `class Hand:` manages collections of cards and calculates hand values.
5. The `class Chips:` handles the betting system and chip management.
6. The ace handling logic automatically adjusts ace values from 11 to 1 when needed.
7. The `hit_or_stand()` function handles player decisions during gameplay.
8. The dealer follows standard casino rules (hits until 17 or higher).
9. The game loop allows for multiple rounds of play.
10. Win/loss conditions check for busts, blackjacks, and hand comparisons.
11. The betting system tracks wins and losses with chip adjustments.
12. Input validation ensures proper user responses throughout the game.
## Next Steps
Congratulations! You have successfully created a Text-based Blackjack Game in Python. Experiment with the code and see if you can modify the application. Here are a few suggestions:
- Add GUI interface with card graphics
- Implement double down and split functionality
- Add insurance betting option
- Create multiplayer support for multiple players
- Add statistics tracking (wins, losses, streaks)
- Implement different difficulty levels
- Add sound effects and animations
- Create tournament mode with multiple rounds
- Add card counting practice features
## Conclusion
In this project, you learned how to create a Text-based Blackjack Game in Python using object-oriented programming. You also learned about game logic, state management, and implementing classic card game rules. You can find the source code on [GitHub](https://github.com/Ravikisha/PythonCentralHub/blob/main/projects/beginners/blackjack.py)
## Code Explanation
### Card and Deck Classes
```python title="blackjack.py" showLineNumbers{1}
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def value(self):
if self.rank in ['Jack', 'Queen', 'King']:
return 10
elif self.rank == 'Ace':
return 11
else:
return int(self.rank)
Implements card representation with proper value calculation for different card types.
Hand Management with Ace Handling
class Hand:
def adjust_for_ace(self):
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
class Hand:
def adjust_for_ace(self):
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
Automatically adjusts ace values from 11 to 1 when hand total exceeds 21, implementing classic blackjack ace rules.
Betting System
class Chips:
def __init__(self, total=100):
self.total = total
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
class Chips:
def __init__(self, total=100):
self.total = total
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
Manages playerโs chip count with betting mechanics for wins and losses.
Game Logic Flow
def hit_or_stand(deck, hand):
choice = input("Would you like to Hit or Stand? Enter 'h' or 's': ").lower()
if choice == 'h':
hit(deck, hand)
elif choice == 's':
playing = False
def hit_or_stand(deck, hand):
choice = input("Would you like to Hit or Stand? Enter 'h' or 's': ").lower()
if choice == 'h':
hit(deck, hand)
elif choice == 's':
playing = False
Handles player decisions and game state transitions with input validation.
Dealer AI
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck, dealer_hand)
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck, dealer_hand)
Implements standard casino dealer rules (hit until 17 or higher).
Win/Loss Conditions
if dealer_hand.value > 21:
dealer_busts(player_hand, dealer_hand, player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand, dealer_hand, player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand, dealer_hand, player_chips)
else:
push(player_hand, dealer_hand)
if dealer_hand.value > 21:
dealer_busts(player_hand, dealer_hand, player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand, dealer_hand, player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand, dealer_hand, player_chips)
else:
push(player_hand, dealer_hand)
Evaluates all possible game outcomes with proper chip adjustments.
Features
- Complete Card System: Full 52-card deck with proper shuffling
- Realistic Blackjack Rules: Standard casino rules including ace handling
- Betting System: Chip management with wins/losses tracking
- Dealer AI: Automated dealer following standard rules (hit until 17)
- Game State Management: Proper handling of busts, wins, and pushes
- Input Validation: Robust user input handling and error checking
- Replay Functionality: Option to play multiple hands
- Visual Card Display: Clear representation of hands and card values
Next Steps
Enhancements
- Add GUI interface with card graphics
- Implement double down and split functionality
- Add insurance betting option
- Create multiplayer support for multiple players
- Add statistics tracking (wins, losses, streaks)
- Implement progressive betting strategies
- Add sound effects and animations
- Create tournament mode with multiple rounds
Learning Extensions
- Study probability and card counting concepts
- Explore advanced blackjack strategies and optimal play
- Learn about casino mathematics and house edge
- Practice with database integration for player statistics
- Understand random number generation and fairness
- Explore AI techniques for optimal play strategies
Educational Value
This project teaches:
- Object-Oriented Programming: Creating and managing multiple interacting classes
- Game Logic Design: Implementing complex rules and state management
- Random Number Generation: Working with shuffling and fair card distribution
- Conditional Logic: Handling multiple game outcomes and decision trees
- User Interface Design: Creating intuitive text-based interactions
- State Management: Tracking game progress and player status
- Input Validation: Ensuring robust user input handling
- Mathematical Modeling: Implementing probability-based game mechanics
Perfect for understanding game development, object-oriented design, and complex program flow control in Python.
Was this page helpful?
Let us know how we did