# 【游戏中的算法】洗扑克牌算法

1134人阅读 评论(0)

/* ************************************************ */
/* name: shuffle algo                                 */
/* auth: tianmt                                        */
/* introduce: shuffle cards, include 52 + 2 pieces    */
/* ************************************************ */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct card{
int Order;        // 顺序
char Suit;        // 花色
char Number;    // 大小
}Card;

// card arr
Card OneCard[54] = {};

// 打印所有
void showCard(){
int i;

for(i=0; i<54; i++){
//printf("  %02d,%c,%c", OneCard[i].Order, OneCard[i].Suit, OneCard[i].Number);
printf("  %c,%c", OneCard[i].Suit, OneCard[i].Number);
if(12 == i%13){
printf("\n");
}
}
printf("\n");
}

// 随机乱序
void shuffle(){
int i;

Card tmpCard;

srand(time(NULL));
for(i=0; i<54; i++){
int tmp = rand()%54;
tmpCard = OneCard[tmp];
OneCard[tmp] = OneCard[i];
OneCard[i] = tmpCard;
}

showCard();
return;
}

// 初始化，顺序
void initCard(){
int i;

for(i=0; i<54; i++){
OneCard[i].Order = i;

if(i>=52){
if(52 == i){
OneCard[i].Suit = 'g';
OneCard[i].Number = 'g';
}else{
OneCard[i].Suit = 'G';
OneCard[i].Number = 'G';
}
}else{
if(i<=12){
OneCard[i].Suit = 'H';	// heart
}else if(i<=25){
OneCard[i].Suit = 'S';	// space
}else if(i<=38){
OneCard[i].Suit = 'D';	// diamond
}else{
OneCard[i].Suit = 'C';	// club
}

switch(i%13){
case 0:
OneCard[i].Number = 'A';
break;
case 9:
OneCard[i].Number = '@';
break;
case 10:
OneCard[i].Number = 'J';
break;
case 11:
OneCard[i].Number = 'Q';
break;
case 12:
OneCard[i].Number = 'K';
break;
default:
OneCard[i].Number = (i%13)+'1';
}
}
}

showCard();
return;
}

int main(void){

printf("init card:\n");
initCard();

printf("\nafter shuffle1 cards: \n");
shuffle();

printf("\nafter shuffle2 cards: \n");
shuffle();

return 0;
}


1、初始页面 和 clear 后：

2、初始化扑克牌：

3、洗扑克牌后：