cards.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include "cards.h"
  5. // Limits of the deck: 13 cards over 4 different suits possible.
  6. #define MAX_CARD 13
  7. #define MAX_SUIT 4
  8. // This function validates the card (suit and value) and prints a description
  9. // of it to stdout. Sample descriptions: 2 of Hearts. King of Spades.
  10. // Returns 0 if the card is valid, 1 if it's not (either invalid suit or value)
  11. int
  12. describe_card(struct playingcard c)
  13. {
  14. if (c.value < 1 || c.value > 13) {
  15. printf("Error: you've passed an invalid card!\n");
  16. return 1;
  17. }
  18. if (c.suit < 1 || c.suit > 4) {
  19. printf("Error: your card has an invalid suit!\n");
  20. return 1;
  21. }
  22. switch(c.value) {
  23. case 1:
  24. printf("Ace");
  25. break;
  26. case 11:
  27. printf("Jack");
  28. break;
  29. case 12:
  30. printf("Queen");
  31. break;
  32. case 13:
  33. printf("King");
  34. break;
  35. default:
  36. printf("%d", c.value);
  37. }
  38. // (value) of (suit)
  39. printf(" of ");
  40. switch(c.suit) {
  41. case 1:
  42. printf("Diamonds\n");
  43. break;
  44. case 2:
  45. printf("Clubs\n");
  46. break;
  47. case 3:
  48. printf("Hearts\n");
  49. break;
  50. case 4:
  51. printf("Spades\n");
  52. break;
  53. }
  54. return 0;
  55. }
  56. // This function creates a random card from the playing deck.
  57. struct playingcard
  58. draw_card()
  59. {
  60. int dice = 0;
  61. struct playingcard card;
  62. dice = rand() % MAX_CARD;
  63. if (dice == 0)
  64. dice += 1;
  65. card.value = dice;
  66. dice = rand() % MAX_SUIT;
  67. if (dice == 0)
  68. dice += 1;
  69. card.suit = dice;
  70. return card;
  71. }