Created
November 4, 2020 16:49
-
-
Save cbscribe/5446a01868fc45c46116290e3220ce22 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <cs50.h> | |
| #include <time.h> | |
| #define DECK_SIZE 52 | |
| // strings for pretty printing values | |
| string ranks[] = {"", "A", "2", "3", "4", "5", "6", | |
| "7", "8", "9", "10", "J", "Q", "K"}; | |
| string suits[] = {"♥", "♣", "♠", "♦"}; | |
| // 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(); | |
| // 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() | |
| { | |
| next_card = 0; | |
| 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