Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int drawCard(int deck[], int drawn[] ) {
int n;
do {
// keep guessing until we find a card
// that hasn't been drawn already
n = rand() % 40;
} while ( drawn[n] );
drawn[n] = 1; // it's drawn now
return deck[n]; // return the card
}
float score(const char *player, int card, float points ) {
if (card == 8 || card == 9 || card == 10) {
printf("%s got 0.5 points", player);
points = points + 0.5;
} else {
printf("%s got %d points", player, card);
points = points + card;
}
printf("\n");
printf("%s score is: %0.1f \n", player, points);
return points;
}
int main()
{
srand(time(NULL));
int key, card, cardpc, n;
int deck[40] = {
1, 1, 1, 1,
2, 2, 2, 2,
3, 3, 3, 3,
4, 4, 4, 4,
5, 5, 5, 5,
6, 6, 6, 6,
7, 7, 7, 7,
8, 8, 8, 8,
9, 9, 9, 9,
10, 10, 10, 10
};
int draw[40] = { 0 };
//array to "delete" a card. Mark a card as "deleted", e.g., by setting it to 1,
// then if the card chosen has been deleted, it choose again.
float points, points_pc;
points = 0;
points_pc = 0;
printf("Press 1 to play or 0 to not!\t");
scanf("%d", &key);
printf("\n");
if (key == 0) {
printf("BYE\n");
} else if (key == 1) {
while (key == 1) {
card = drawCard(deck,draw);
points = score("You", card, points);
card = drawCard(deck,draw);
points_pc = score("The PC", card, points_pc);
printf("Do you want another card? (Press 1 if you want it)\t");
scanf("%d", &key);
printf("\n");
}
//if the user passes turn, the pc can still continue playing
while (points_pc < points) {
card = drawCard(deck,draw);
points_pc = score("The PC", card, points_pc);
}
printf("\n");
}
//RESULTS
if (points_pc == 7.5) {
printf("The PC won! \n");
} else if (points_pc > 7.5) {
printf("You won! The PC score is above 7.5\n");
} else if (points_pc > points) {
printf("The PC won! \n");
} else if (points > 7.5) {
printf("YOU LOST!\n");
} else if (points == 7.5) {
printf("YOU WON");
}
return 0;
}