Quick actions

cmd+k|ctrl+k

Navigation

Languages

Print card example (win32 / *nix charcodes)

Snippet info

Language

C

Visibility

public

Author

mrsimb

Created

2017-05-21T14:45:30Z

Updated

2017-05-31T11:19:21Z

#include <stdio.h>
#include <math.h>   // floor, rand
#include <stdlib.h> // srand (for rand init)
#include <time.h>   // time (for srand based on time)

// returns random double between in [0, 1)
double random_double() {
  static int initialized = 0;

  if (!initialized) {
    srand(time(NULL));
    initialized = 1;
  }

  return (double) rand() / RAND_MAX;
}

// returns random int between min and max
int random_int(int min, int max) {
  return floor(random_double() * (max - min + 1)) + min;
}

// returns character representation of suit (depends on OS)
const char* get_suit_char(int suit) {
  static const char* suits[] = {
  #ifdef _WIN32
    "\3",
    "\4",
    "\5",
    "\6"
  #else
    "\u2665",
    "\u2666",
    "\u2663",
    "\u2660"
  #endif
  };

  if (suit < 0) return suits[0];
  if (suit > 13) return suits[3];
  return suits[suit];
}

// returns character representation of rank (if has)
const char get_rank_char(int rank) {
  switch (rank) {
    case 1:  return 'A';
    case 11: return 'J';
    case 12: return 'Q';
    case 13: return 'K';
    default: return ' ';
  }
}

// prints card of given rank and suit
void print_card(int rank, int suit) {
  if (rank < 1 || rank > 13) return;

  const char* suit_char = get_suit_char(suit);
  const char rank_char = get_rank_char(rank);

  printf("-------\n");
  printf("|%s    |\n", suit_char);
  if (rank_char != ' ') {
    printf("|  %c  |\n", rank_char);
  } else if (rank < 10) {
    printf("|  %i  |\n", rank);
  } else {
    printf("| %i  |\n", rank);
  }
  printf("|    %s|\n", suit_char);
  printf("-------\n");
}

int main() {
  print_card(11, 0);
  return 0;
}
INFO