100 Days of Code Day 11

toyinariyo

Oluwatoyin Ariyo

Posted on February 10, 2023

100 Days of Code Day 11

Day 11 of Angela Yu's Python bootcamp was spent building a capstone project which was a Blackjack game which uses all of the concepts I have learnt about so far (functions, while loops, range() function, random module, indexes in lists, functions with inputs). The reason why there is a 2 week gap over the last blogpost is because I have discovered other Python resources that have taught me about Python concepts such as Python Morsels, which gives out short videos on Python features and several Python exercises with pre-defined tests and is categorised by difficulty level. I also have been learning Python through Boot.dev, a bootcamp for back-end development which has courses for Python, JavaScript and Go.

For this project, the code used is a simple implementation of the card game Blackjack. The game starts by dealing 2 cards to both the player and the computer. The player can choose to hit (draw another card) or stand (keep their current hand). If the player's score exceeds 21, they lose the game. If the player stands, the computer will draw cards until it reaches a score of 17 or higher. The game then ends, and the scores are compared to determine the winner. A player wins if their score is higher than the computer's score and has not gone over 21. The game also checks for a Blackjack (an Ace and a 10-point card) and if either the player or computer gets a blackjack, that player wins the game. The game outputs the final hands and scores of both the player and computer, and the result of the game.

Here's the Python code used:

# Hint 4: Create a deal_card() function that uses the List below to *return* a random card. 11 is the Ace.
import random
import os
from art import logo


def cls():  # Cross-platform clear screen
    os.system('cls' if os.name == 'nt' else 'clear')


# Hint 4: Create a function called deal_card() that uses a list to return a random card. 11 is the Ace.
def deal_card():
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10]
    card = random.choice(cards)
    return card


# Hint 6: Create a function called calculate_score() that takes a List of cards as input and returns the score.
def calculate_score(cards):
    # Hint 7: Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0.
    # 0 will represent a blackjack in our game.
    if sum(cards) == 21 and len(cards) == 2:
        return 0
    # Hint 8: Inside calculate_score() check for an 11 (ace).
    # If the score is already over 21, remove the 11 and replace it with a 1.
    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)
    return sum(cards)


# Hint 13: Create a function called compare() and pass in the user_score and computer_score.
# If the computer and user both have the same score, then it's a draw.
# If the computer has a blackjack (0), then the user loses. If the user has a blackjack (0), then the user wins.
# If the user_score is over 21, then the user loses. If the computer_score is over 21, then the computer loses.
# If none of the above, then the player with the highest score wins.
def compare(player_score, computer_score):
    if player_score > 21 and computer_score > 21:
        return "You went over 21. You lose."
    if player_score == computer_score:
        return "Draw."
    elif computer_score == 0:
        return "Computer has Blackjack."
    elif player_score == 0:
        return "Congratulations, you got a Blackjack!"
    elif player_score > 21:
        return "You went over 21. You lose."
    elif computer_score > 21:
        return "Computer went over 21. You win!"
    elif player_score > computer_score:
        return "You win!"
    else:
        return "You lose."


def play_game():
    print(logo)
    # Hint 5: Deal the user and computer 2 cards each using deal_card()
    player_cards = []
    computer_cards = []
    game_over = False
    for _ in range(2):
        player_cards.append(deal_card())
        computer_cards.append(deal_card())
    # Hint 11: The score will need to be rechecked with every new card drawn.
    # The checks in Hint 9 need to be repeated until the game ends.
    while not game_over:
        # Hint 9: Call calculate_score().
        # If the computer or the user has a blackjack (0) or if the user's score is over 21, then the game ends.
        player_score = calculate_score(player_cards)
        computer_score = calculate_score(computer_cards)
        print(f"Your cards: {player_cards}, your current score is: {player_score}")
        print(f"Computer's first card: {computer_cards[0]}")
        if player_score == 0 or computer_score == 0 or player_score > 21:
            game_over = True
        else:
            # Hint 10: If the game has not ended, ask the user if they want to draw another card.
            # If yes, then use the deal_card() function to add another card to the user_cards List.
            # If no, then the game has ended.
            player_deals_again = input("Type 'y' to get another card or type 'n' to pass: ")
            if player_deals_again == "y":
                player_cards.append(deal_card())
            else:
                game_over = True
        # Hint 12: Once the user is done, it's time to let the computer play.
        # The computer should keep drawing cards as long as it has a score less than 17.
        while computer_score != 0 and computer_score < 17:
            computer_cards.append(deal_card())
            computer_score = calculate_score(computer_cards)
        print(f"Your final hand: {player_cards}, your final score is: {player_score}")
        print(f"Computer's final hand: {computer_cards}, computer's final score is: {computer_score}")
        print(compare(player_score, computer_score))


# Hint 14: Ask the player to restart the game.
# If they answer yes, clear the console and start a new game of blackjack and show the logo from art.py.
while input("Do you want to play a game of Blackjack? Type 'y' for yes or 'n' for no: ") == "y":
    cls()
    play_game()
Enter fullscreen mode Exit fullscreen mode

Like my other daily projects, I converted the above code to C#:

internal class Program
{
    private static void Main(string[] args)
    {
        PlayGame();
    }

    static void ClearScreen()
    {
        Console.Clear();
    }

    static int DealCard()
    {
        List<int> cards = new List<int> { 11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10 };
        Random random = new Random();
        int card = cards[random.Next(0, cards.Count)];
        return card;
    }

    static int CalculateScore(List<int> cards)
    {
        if (cards.Sum() == 21 && cards.Count == 2)
        {
            return 0;
        }
        if (cards.Contains(11) && cards.Sum() > 21)
        {
            cards.Remove(11);
            cards.Add(1);
        }
        return cards.Sum();
    }

    static string Compare(int playerScore, int computerScore)
    {
        if (playerScore > 21 && computerScore > 21) {
            return "You went over 21. You lose";
        }
        else if (playerScore == computerScore)
        {
            return "Draw";
        }
        else if (computerScore == 0)
        {
            return "Computer has Blackjack";
        }
        else if (playerScore == 0)
        {
            return "Congratulations! You got a Blackjack";
        }
        else if (playerScore > 21)
        {
            return "You went over 21. You lose";
        }
        else if (computerScore > 21)
        {
            return "Computer went over 21. You win!";
        }
        else if (playerScore > computerScore)
        {
            return "You win";
        }
        else
        {
            return "You lose.";
        }
    }

    static void PlayGame()
    {
        ClearScreen();
        List<int> playerCards = new List<int>();
        List<int> computerCards = new List<int>();
        bool gameOver = false;
        for (int i = 0; i < 2; i++)
        {
            playerCards.Add(DealCard());
            computerCards.Add(DealCard());
        }
        while (!gameOver)
        {
            int playerScore = CalculateScore(playerCards);
            int computerScore = CalculateScore(computerCards);
            Console.WriteLine("Your cards: " + String.Join(", ", playerCards) + ", your current score is: " + playerScore);
            Console.WriteLine("Computer's first card: " + computerCards[0]);
            if (playerScore == 0 || computerScore == 0 || playerScore > 21)
            {
                gameOver = true;
            }
            else
            {
                Console.WriteLine("Type 'y' to get another card or type 'n' to pass: ");
                string playerDealsAgain = Console.ReadLine();
                if (playerDealsAgain == "y")
                {
                    playerCards.Add (DealCard());
                } else
                {
                    gameOver = true;
                }
            }
            while (computerScore < 17)
            {
                computerCards.Add(DealCard());
                computerScore = CalculateScore(computerCards);
            }
            Console.WriteLine("Your final hand: " + string.Join(", ", playerCards) + ", your final score is: " + playerScore);
            Console.WriteLine("Computer's final hand: " + string.Join(", ", computerCards) + ", computer's score is: " + computerScore);
            Console.WriteLine(Compare(playerScore, computerScore));
        }
        while (gameOver)
        {
            Console.WriteLine("Do you want to play a game of Blackjack? Type 'y' for yes or 'n' for no? ");
            string response = Console.ReadLine();
            if (response == "n")
            {
                break;
            }
            Console.Clear();
            PlayGame();
        }

    } 

}

Enter fullscreen mode Exit fullscreen mode

I will do day 12 of the 100 days next week.

💖 💪 🙅 🚩
toyinariyo
Oluwatoyin Ariyo

Posted on February 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

100 Days of Code Day 11
100daysofcode 100 Days of Code Day 11

February 10, 2023

100 Days of Code: Day 9
100daysofcode 100 Days of Code: Day 9

January 23, 2023

100 Days of Code: Day 8
100daysofcode 100 Days of Code: Day 8

January 21, 2023

100 Days of Code Challenge: Day 4
100daysofcode 100 Days of Code Challenge: Day 4

January 10, 2023

100 Days of Code Challenge: Day 3
100daysofcode 100 Days of Code Challenge: Day 3

January 6, 2023