Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Created May 26, 2020 21:38
Show Gist options
  • Save wjlafrance/64ee1d5e2e737751961ace94771bc085 to your computer and use it in GitHub Desktop.
Save wjlafrance/64ee1d5e2e737751961ace94771bc085 to your computer and use it in GitHub Desktop.
Object Oriented C Example
#import <stdio.h>
#import <stdlib.h>
typedef enum {
heart = 0,
spade = 1,
diamond = 2,
club = 3
} Suit;
char *SuitName(Suit suit) {
switch (suit) {
case heart: return "Hearts";
case spade: return "Spades";
case diamond: return "Diamonds";
case club: return "Clubs";
}
}
// ----
typedef struct {
int value;
Suit suit;
} Card;
char *CardValueString(Card card) {
switch (card.value + 1) {
case 1: return "Ace";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return NULL;
}
}
// ----
typedef struct {
Card cards[52];
} Deck;
void DeckInitialize(Deck *deck) {
for (int i = 0; i < 52; i++) {
deck->cards[i].value = i % 13;
deck->cards[i].suit = i / 13;
}
}
void DeckPrint(Deck *deck) {
for (int i = 0; i < 52; i++) {
Card card = deck->cards[i];
char *cardValueString = CardValueString(card);
if (NULL != cardValueString) {
printf("Card %02d: %s of %s\n",
i + 1, cardValueString, SuitName(card.suit));
} else {
printf("Card %02d: %d of %s\n",
i + 1, card.value + 1, SuitName(card.suit));
}
}
}
Deck *DeckCreate() {
Deck *deck = malloc(sizeof(Deck));
DeckInitialize(deck);
return deck;
}
void DeckDestroy(Deck *deck) {
// any necessary pre-deallocation cleanup
free(deck);
}
// ----
int main() {
Deck *deck = DeckCreate();
DeckPrint(deck);
DeckDestroy(deck);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment