#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");
}
}
// Dealer's turn
int dealerHand[10];
int numDealerCards = 0;
// Initial draw for the dealer
dealerHand[numDealerCards++] = drawCard();
dealerHand[numDealerCards++] = drawCard();
printf("\nDealer's hand: %d ?\n", dealerHand[0]);
// Dealer draws cards until the total value is at least 17
while (calculateHandValue(dealerHand, numDealerCards) < 17) {
dealerHand[numDealerCards++] = drawCard();
}
// Display the dealer's hand and total value
printf("Dealer's hand:");
for (int i = 0; i < numDealerCards; ++i) {
printf(" %d", dealerHand[i]);
}
printf("\nDealer's total value: %d\n", calculateHandValue(dealerHand, numDealerCards));
// Determine the winner
int playerTotal = calculateHandValue(playerHand, numPlayerCards);
int dealerTotal = calculateHandValue(dealerHand, numDealerCards);
if (playerTotal > dealerTotal || dealerTotal > 21) {
printf("Congratulations! You win!\n");
} else if (playerTotal < dealerTotal) {
printf("Sorry, you lose.\n");
} else {
printf("It's a tie!\n");
}
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: