Skip to content

Instantly share code, notes, and snippets.

@cbscribe
Created October 23, 2020 17:55
Show Gist options
  • Save cbscribe/2e549e7cb975db8d9c05cb90f9ab9ae1 to your computer and use it in GitHub Desktop.
Save cbscribe/2e549e7cb975db8d9c05cb90f9ab9ae1 to your computer and use it in GitHub Desktop.
Deck of cards in C
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <time.h>
#define DECK_SIZE 52
// strings for pretty printing values
string ranks[14] = {"", "Ace", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
string suits[4] = {"Hearts", "Clubs", "Spades", "Diamonds"};
// each card has two properties
typedef struct
{
int suit;
int rank;
} card;
// function prototypes
card deal_card();
void shuffle();
card deck[DECK_SIZE];
// keeps track of the next card to deal
// increment this every time you deal a card
// shuffle and reset this to 0 to start a new game
int next_card = 0;
int main(void)
{
// seed the rng
srand(time(0));
// create the deck of unique cards
int n = 0;
for (int s = 0; s < 4; s++)
{
for (int r = 1; r <= 13; r++)
{
deck[n].rank = r;
deck[n].suit = s;
n++;
}
}
shuffle();
// print the deck
// for (int i = 0; i < DECK_SIZE; i++)
// {
// printf("%s of %s\n", ranks[deck[i].rank], suits[deck[i].suit]);
// }
// example: deal 5 random cards
printf("Your hand:\n");
for (int i = 0; i < 5; i++)
{
card c = deal_card();
printf("%s of %s\n", ranks[c.rank], suits[c.suit]);
}
}
// performs a Fisher-Yates shuffle on the deck
void shuffle()
{
for (int i = DECK_SIZE - 1; i > 0; i--)
{
int j = rand() % (i + 1);
card tmp = deck[i];
deck[i] = deck[j];
deck[j] = tmp;
}
}
// returns the next card in the deck
// make sure you've shuffled first!
card deal_card()
{
card c = deck[next_card];
next_card++;
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment