用c写的桥牌发牌代码

 最近学桥牌,据说要经常自己做叫牌练习。为了偷懒不用发牌,随便写了一段发牌的程序。
我用的是cygwin。如果是别的系统,产生随机数洗牌那里要改,其它的都不用动。


大致思路是:
用整数51~0代表52张牌,依次是黑桃A~2、红桃A~2、方块A~2、草花A~2,保存到数组。
洗牌:循环10000次,每次产生两个0~51的随机数,交换这个位置的数组元素。
洗好牌之后,就可以把序号0~12、13~25、26~38、39~51分别作为4家的牌,各自在组内从大到小排序。
然后把整数转换成花色和牌点,保存到4x4x13的三维char数组,cards[玩家][花色][牌点]。用't'代表10,0代表没有牌。

/* * deal 4 hands of cards for bridge * May 15, 2009 */ #include #include #include #define NORTH 0 #define WEST 1 #define EAST 2 #define SOUTH 3 #undef DBG int numbers[52]; char cards[4][4][13] = {0}; #if 1 char suits[4] = { 'S', 'H', 'D', 'C' }; #else /* for DOS */ char suits[4] = { 6, 3, 4, 5 }; #endif void deal(void); void numbers2cards(void); void display_numbers(void); void display_cards(void); void swap(int *x, int *y); void sort(int *data, int total); int main(void) { deal(); // store number 0~51 in numbers[52] as 52 cards numbers2cards(); // transform numbers into cards[player][suit][point] display_cards(); return 0; } /* * use numbers 51~0 as cards: * 51~39: Spade, A~2 * 38~26: Heart, A~2 * 25~13: Diamond, A~2 * 12~0: Club, A~2 * * The numbers are stored in an array and shuffled. * After shuffle, * numbers[ 0~12]: cards of north * numbers[13~25]: cards of west * numbers[26~38]: cards of east * numbers[39~51]: cards of south * * then the 4 groups of numbers are sorted within each hand */ void deal(void) { int i; int idx1, idx2; for (i=0; i<52; i++) { numbers[i] = i; } // shuffle srand((unsigned int)time(NULL)); for (i=0; i<10000; i++) { idx1 = rand() % 52; idx2 = rand() % 52; swap(numbers+idx1, numbers+idx2); } #ifdef DBG display_numbers(); #endif for (i=0; i<4; i++) { // sort the 4 groups of numbers within 0~12, 13~25, 26~38, 39~51 sort(numbers + i*13, 13); } #ifdef DBG display_numbers(); #endif } // swap 2 integers at x and y void swap(int *x, int *y) { #if 0 // normal solution int temp; temp = *x; *x = *y; *y = temp; #else // this looks cool if (x != y) { *x = *x ^ *y; *y = *x ^ *y; *x = *x ^ *y; } #endif } // print the array numbers[]. debug only void display_numbers(void) { int i; for (i=0; i<52; i++) { printf("%3d", numbers[i]); if (i%13 == 12) printf("/n"); } printf("/n"); } // sort integers in array data[total] void sort(int *data, int total) { #if 1 // Pigeonhole int count[52] = {0}; int i, j; int idx=0; for (i=0; i=0; i--) for (j=0; j

你可能感兴趣的:(c/c++,c,numbers,dos,each,null)