#include <stdio.h>
#include <stdlib.h>
#include <time.h>

// Function to draw a card
int drawCard() {
    return rand() % 10 + 1;  // Cards are numbered 1 to 10
}

// Function to calculate the total value of a hand
int calculateHandValue(int *hand, int numCards) {
    int totalValue = 0;
    int numAces = 0;

    // Calculate the total value of the hand
    for (int i = 0; i < numCards; ++i) {
        if (hand[i] == 1) {
            // Ace can be 1 or 11; count the number of aces
            totalValue += 11;
            numAces++;
        } else {
            // Face cards and numbered cards
            totalValue += (hand[i] > 10) ? 10 : hand[i];
        }
    }

    // Adjust the value for aces if needed
    while (totalValue > 21 && numAces > 0) {
        totalValue -= 10;
        numAces--;
    }

    return totalValue;
}

int main() {
    srand(time(NULL));  // Seed for random number generation

    int playerHand[10];  // Assuming a maximum of 10 cards in a hand
    int numPlayerCards = 0;

    printf("Welcome to Blackjack!\n");

    // Initial draw for the player
    playerHand[numPlayerCards++] = drawCard();
    playerHand[numPlayerCards++] = drawCard();

    printf("Your hand: %d %d\n", playerHand[0], playerHand[1]);
    printf("Total value: %d\n", calculateHandValue(playerHand, numPlayerCards));

    // Player's turn
    while (1) {
        printf("Do you want to draw another card? (y/n): ");
        char choice;
        scanf(" %c", &choice);

        if (choice == 'n') {
            break;
        }

        if (choice == 'y') {
            // Draw another card
            playerHand[numPlayerCards++] = drawCard();

            // Display the updated hand and total value
            printf("Your hand:");
            for (int i = 0; i < numPlayerCards; ++i) {
                printf(" %d", playerHand[i]);
            }
            printf("\nTotal value: %d\n", calculateHandValue(playerHand, numPlayerCards));

            // Check if the player has exceeded 21
            if (calculateHandValue(playerHand, numPlayerCards) > 21) {
                printf("Busted! You exceeded 21. You lose.\n");
                return 0;
            }
        } else {
            printf("Invalid choice. Please enter 'y' or 'n'.\n");
            // Clear input buffer in case of invalid input
            while (getchar() != '\n');
        }
    }

    // Rest of the code remains the same...

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: