I’m having an issue with getting my blackjack game to clear the console once the game is completed and a new game is started. Instead, the game adds the new cards to the previous game making an instant loss? Below is my code.
import random
from replit import clear
from art import logo
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal_card():
return random.choice(cards)
player_cards = []
computer_cards = []
def deal_round():
for i in range(2):
player_cards.append(deal_card())
computer_cards.append(deal_card())
def calculate_score(n1):
if sum(n1) == 21 and len(n1) == 2:
return 0
if 11 in n1 and len(n1) > 2:
n1.remove(11)
n1.append(1)
return sum(n1)
def compare(player_sum, computer_sum):
if player_sum > 21 and computer_sum > 21:
return "You went over. You lose."
elif player_sum == computer_sum:
return "Draw"
elif computer_sum == 0:
return "Computer Blackjack!. You lose!"
elif player_sum == 0:
return "Blackjack. You won the game!"
elif player_sum > 21:
return "You lose!"
elif computer_sum > 21:
return "Computer went over. You win!"
elif player_sum > computer_sum:
return "You win!"
else:
return "You lose!"
def blackjack():
print(logo)
end_of_game = False
deal_round()
def computer_card():
return computer_cards[0]
while not end_of_game:
player_sum = calculate_score(player_cards)
computer_sum = calculate_score(computer_cards)
print(f"Your cards are: {player_cards}, current score: {player_sum}")
print(f"Computer's first card: {computer_card()}")
if player_sum == 0 or computer_sum == 0 or player_sum >21:
end_of_game = True
else:
if input("Type 'y' to get another card, type 'n' to pass: ") == 'y':
player_cards.append(deal_card())
else:
end_of_game = True
while computer_sum <= 16:
computer_cards.append(deal_card())
computer_sum = calculate_score(computer_cards)
print(f"Your final hand: {player_cards}, final score: {player_sum}")
print(f"Computer's final hand: {computer_cards}, final score: {computer_sum}")
print(compare(player_sum, computer_sum))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clear()
blackjack()
I’ve tried to move the clear function into the blackjack function but, resulted in the same outcome. I also attempted to use the import os in place of the clear function but no success.
>Solution :
replit.clear()
will apparently clear the screen, but that does not reset the game state.
Check out How to clear the interpreter console? for alternatives to clearing the screen. I like print("\033c")
.
What you likely really want to do is reset the game state between rounds. So each round you want to reset:
player_cards = []
computer_cards = []
So, if your final while loops was:
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
#clear()
print("\033c")
player_cards = []
computer_cards = []
blackjack()
You will likely get past your current issue.