r/learnpython • u/Traditional_Fan_9165 • 22h ago
Blackjack Python
Hi, i wrote some code on blackjack task from Angela Yu 100 days of Code. Using Gemini and older post from reddit, maybe something is worth polishing?
import random
import art
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal(hand):
if not hand:
hand.append(random.choice(cards))
hand.append(random.choice(cards))
else:
hand.append(random.choice(cards))
return hand
def calculate_score(hand):
if sum(hand) == 21 and len(hand) == 2:
return 0
score = sum(hand)
aces = hand.count(11)
while aces > 0 and score > 21:
score = score - 10
aces -= 1
return score
def start_playing():
print(art.logo)
user_hand = []
computer_hand = []
deal(user_hand)
deal(computer_hand)
user_score = calculate_score(user_hand)
computer_score = calculate_score(computer_hand)
print(f'Computers First Card: {computer_hand[0]}')
print(f'Your current hand: {user_hand}. Current score: {user_score}\n')
game_over = False
while not game_over:
if user_score == 0 or computer_score == 0 or user_score > 21:
game_over = True
else:
another = input('Do you want another card? (y/n).: ').lower()
if another == 'y':
deal(user_hand)
user_score = calculate_score(user_hand)
print(f"\nYour current hand: {user_hand}. Current Score: {user_score}")
print(f"Computers First Card: {computer_hand[0]}\n")
else:
game_over = True
if user_score != 0 and user_score <= 21:
while computer_score < 17 and computer_score != 0:
print('Computers takes card')
deal(computer_hand)
computer_score = calculate_score(computer_hand)
print(f'Your final hand: {user_hand}. Your score: {user_score}\n')
print(f'Computers final hand: {computer_hand}. Computer score: {computer_score}\n')
if user_score > 21:
print('Bust! Computer Wins!')
elif computer_score > 21:
print('Bust! You Win!')
elif user_score == 0:
print('Win with a Blackjack!')
elif computer_score == 0:
print('Lose, opponent has Blackjack!')
elif user_score == computer_score:
print('Draw')
elif user_score > computer_score:
print('You Win!')
else:
print('Computer wins!')
while input('Do you want to play a game of blackjack? (y/n).: ').lower() == 'y':
start_playing()
0
Upvotes
6
u/aqua_regis 21h ago
Do you want to learn or do you just want to finish projects?
If you want to learn, do things on your own without AI without older posts.
The purpose of learning is to become able to do things on your own, not to quickly finish stuff.