Question: Blackjack part 2 , using the code below, add a function to transfer dealer and player wins and losses onto a csv file. import random

Blackjack part 2, using the code below, add a function to transfer dealer and player wins and losses onto a csv file.
import random
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __str__(self):
return f"{self.value} of {self.suit}"
class Deck:
def __init__(self):
self.cards =[]
self.build()
def build(self):
suits =['Hearts', 'Diamonds', 'Clubs', 'Spades']
values =['2','3','4','5','6','7','8','9','10', 'Jack', 'Queen', 'King', 'Ace']
self.cards =[Card(suit, value) for suit in suits for value in values]
def shuffle(self):
random.shuffle(self.cards)
def deal(self):
return self.cards.pop()
class Hand:
def __init__(self):
self.cards =[]
self.value =0
def add_card(self, card):
self.cards.append(card)
def calculate_value(self):
self.value =0
has_ace = False
for card in self.cards:
if card.value == 'Ace':
has_ace = True
self.value += self.card_value(card)
if has_ace and self.value <=11:
self.value +=10
return self.value
@staticmethod
def card_value(card):
if card.value in ['Jack', 'Queen', 'King']:
return 10
elif card.value == 'Ace':
return 1
else:
return int(card.value)
def main():
# Initialize deck and players' hands
deck = Deck()
deck.shuffle()
player_hand = Hand()
dealer_hand = Hand()
# Deal initial cards
player_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
# Game loop
while True:
# Show player's hand and one of dealer's cards
print("
Player's Hand:")
for card in player_hand.cards:
print(card)
print("
Dealer's Hand:")
print(dealer_hand.cards[0])
print("One card face down.")
# Ask player to hit or stand
try:
action = input("
Do you want to (h)it or (s)tand?")
except EOFError:
print("
End of input. Exiting the game.")
break
if action.lower()=='h':
player_hand.add_card(deck.deal())
player_hand.calculate_value()
if player_hand.value >21:
print("
Player busts! Dealer wins.")
break
elif action.lower()=='s':
# Dealer's turn
while dealer_hand.calculate_value()<17:
dealer_hand.add_card(deck.deal())
# Show dealer's hand
print("
Dealer's Hand:")
for card in dealer_hand.cards:
print(card)
# Determine winner
if dealer_hand.value >21:
print("
Dealer busts! Player wins.")
elif dealer_hand.value > player_hand.value:
print("
Dealer wins.")
elif dealer_hand.value < player_hand.value:
print("
Player wins.")
else:
print("
It's a tie!")
break
if __name__=="__main__":
main()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!