模拟扑克牌游戏的洗牌

大家都很喜欢玩扑克牌,那么如果面试官让你用计算机模拟一个扑克游戏的发牌或者洗牌,你会怎么做呢?
代码如下:

#include
#include
#include
#include
#define POKER_NUM 52
//s:黑桃,h:红桃,c:梅花,d:方块
char poker_kinds[4] = {'s','h','c','d'};
char *poker_point[13] = { "A", "2", "3", "4", "5",
"6", "7", "8", "9", "10", "J", "Q", "K" };
typedef struct poker
{
	char kinds;
	char points[6];
}Poker;

Poker poker[POKER_NUM];

void InitPoker(Poker *poker)
{
	int i, j = 0, k = 0;
	for (i = 0; i < POKER_NUM; ++i)
	{
		if (i % 4 == 0)
		{
			j = 0;
		}
		if (i % 13 == 0)
		{
			k = 0;
		}
		while (j < 4 && k < 13)
		{
			poker[i].kinds = poker_kinds[j];
			strcpy_s(poker[i].points, strlen(poker_point[k]) + 1, poker_point[k]);
			j++;
			k++;
			break;
		}
	}
}

void Shuffle(Poker *poker)
{
	Poker *a, *b, tmp;
	srand((unsigned)time(NULL));
	for (int i = 0; i < 100; ++i)
	{
		a = poker + rand() % 52;
		b = poker + rand() % 52;
		tmp = *a;
		*a = *b;
		*b = tmp;
	}
}

void DisplayPoker(Poker *poker)
{
	for (int i = 0; i < POKER_NUM; ++i)
	{
		printf("%c%2s  ", poker[i].kinds, poker[i].points);
		if ((i + 1) % 13 == 0)
		{
			printf("\n");
		}
	}
}
int main()
{
	printf("洗牌前:\n");
	InitPoker(poker);
	DisplayPoker(poker);
	printf("洗牌后:\n");
	Shuffle(poker);
	DisplayPoker(poker);
	return 0;
}

你可能感兴趣的:(C/C++)