/*********************************************************
* From C PROGRAMMING: A MODERN APPROACH, by K. N. King *
* Copyright (c) 1996 W. W. Norton & Company, Inc. *
* All rights reserved. *
* This program may be freely distributed for class use, *
* provided that this copyright notice is retained. *
*********************************************************/
/* deal.c (Chapter 8, page 150) */
/* Deals a random hand of cards */
/*发牌*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_SUITS 4 //4个花色
#define NUM_RANKS 13 //每个花色13张牌
#define TRUE 1
#define FALSE 0
typedef int Bool; //定义新数据类型Bool
main()
{
Bool in_hand[NUM_SUITS][NUM_RANKS] = {0}; //定义二维数组in_hand 4行13列
int num_cards, rank, suit;
const char rank_code[] = {'2','3','4','5','6','7','8',
'9','t','j','q','k','a'}; //数组中存13牌
const char suit_code[] = {'c','d','h','s'}; //数组中存4个花色
// c,d,h,s代表梅花、红桃 、方片 、黑桃四种花色
//声明为const的数组不能进行修改
srand((unsigned) time(NULL));
//srand函数:初始化C语言的随机数生成器,通过把time函数的返回值传递给srand这种方法
//可以避免程序在每次运行时发同样的牌
printf("Enter number of cards in hand: ");
scanf("%d", &num_cards);
printf("Your hand:");
while (num_cards > 0) {
suit = rand() % NUM_SUITS; /* picks a random suit */
rank = rand() % NUM_RANKS; /* picks a random rank */
if (!in_hand[suit][rank]) {
in_hand[suit][rank] = TRUE; //避免重复选择同一花色的牌
num_cards--; //这里是循环条件
printf(" %c%c", rank_code[rank], suit_code[suit]);//输出每次随机产生的牌
}
}
printf("\n");
return 0;
}