今天我们来看看,如何随机产生一副扑克牌。
#include <stdio.h>
#include <stdlib.h>
typedef enum {
XIAO_GUI = 1,
DA_GUI,
RED_HEART = 3,
FANG_PIAN,
MEI_HUA,
HEI_TAO
}FLOWER_COLOR;
typedef struct {
FLOWER_COLOR flower;
int num;
}CARDS;
CARDS cards[54];
void print_card_num(int num)
{
if(num == 1) printf("%c ",'A');
else if(num >= 2 && num <= 10) printf("%d ", num);
else if(num == 11) printf("%c ",'J');
else if(num == 12) printf("%c ",'Q');
else if(num == 13) printf("%c ",'K');
}
void wash_cards(int times)
{
int i, j;
CARDS temp;
//如果不加这个函数,程序每次运行产生的随机数都一样。
srand((unsigned int)(time(NULL))); //每次运行都足够随机
if(times < 0 || times > 100000)
{
printf("wash times err\n");
return;
}
while(times--)
{
i = rand()%54;
j = rand()%54;
memcpy(&temp, &cards[i], sizeof(CARDS));
memcpy(&cards[i], &cards[j], sizeof(CARDS));
memcpy(&cards[j], &temp, sizeof(CARDS));
}
}
void print_cards(int num)
{
int i;
int count_line;
printf("\nwash cards:\n");
for(i = 0, count_line = 1 ; i < num; i++)
{
printf("%c",cards[i].flower);
print_card_num(cards[i].num);
if(count_line == i/12)
{
count_line += 1;
printf("\n");
}
}
}
void init_cards(void)
{
FLOWER_COLOR color;
int i;
for(color = RED_HEART; color <= HEI_TAO; color++)
{
for(i = 1; i <= 13; i++)
{
cards[(color-3)*13 + i -1].flower = color;
cards[(color-3)*13 + i - 1].num = i;
}
}
cards[52].flower = XIAO_GUI;
cards[52].num = 0;
cards[53].flower = DA_GUI;
cards[53].num = 0;
}
int main(int argc, char *argv[])
{
init_cards();
print_cards(54);
wash_cards(100);
print_cards(54);
//printf("%c", FANG_PIAN);
system("PAUSE");
return 0;
}
运行结果如下:
init cards:....
A 2 3 4 5 6 7 8 9 10 J Q K
A 2 3 4 5 6 7 8 9 10 J Q
K A 2 3 4 5 6 7 8 9 10 J
Q K A 2 3 4 5 6 7 8 9 10
J Q K
wash cards:
5 9 7 7 Q Q 4 8 2 Q 8 9 4
K 5 3 3 5 2 7 3 A 2 8
10 10 6 4 10 10 9 K K 5 6 J
6 K 3 A J J Q A 2 8 J
A 7 4 9 6 请按任意键继续. . .