Last active
December 14, 2015 17:28
-
-
Save cleure/5122382 to your computer and use it in GitHub Desktop.
Simple deck of cards example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <limits.h> | |
#include <time.h> | |
/* Lookup array for card suits */ | |
const char *card_suits[] = { | |
"hearts", | |
"diamonds", | |
"spades", | |
"clubs" | |
}; | |
/* Lookup array for card numbers */ | |
const char *card_numbers[] = { | |
"ace", | |
"two", | |
"three", | |
"four", | |
"five", | |
"six", | |
"seven", | |
"eight", | |
"nine", | |
"ten", | |
"jack", | |
"queen", | |
"king", | |
}; | |
/* Array of char[32], which will hold card labels */ | |
char *card_labels[52][32]; | |
/* Compare function that returns random negative/positive */ | |
int random_compare(const void *A, const void *B) | |
{ | |
return rand() - INT_MAX / 2; | |
} | |
/* Initialize deck of cards */ | |
void init_deck(int *deck_of_cards) | |
{ | |
int i; | |
for (i = 0; i < 52; i++) { | |
deck_of_cards[i] = i; | |
} | |
qsort(deck_of_cards, 52, sizeof(int), &random_compare); | |
} | |
/* Init card labels */ | |
void init_labels() | |
{ | |
int a, b, i, l; | |
char *ptr; | |
i = 0; | |
for (a = 0; a < 4; a++) { | |
for (b = 0; b < 13; b++) { | |
ptr = (char *)&card_labels[i]; | |
l = strlen(card_numbers[b]); | |
strcpy(ptr, card_numbers[b]); | |
ptr += l; | |
strcpy(ptr, " of "); | |
ptr += 4; | |
strcpy(ptr, card_suits[a]); | |
i++; | |
} | |
} | |
} | |
int main(void) | |
{ | |
int i; | |
int card; | |
/* Array that holds deck of cards */ | |
int deck[52]; | |
/* Init random number generator */ | |
srand(time(NULL)); | |
/* Init card labels */ | |
init_labels(); | |
/* Init deck of cards */ | |
init_deck((int *)&deck); | |
/* "Draw" every card from deck */ | |
for (i = 0; i < 52; i++) { | |
card = deck[i]; | |
printf("%s\n", (char *)card_labels[card]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment