我正在尝试用c创建一个简单的扑克游戏Texas Hold'em风格.
起初,我试图用2个char数组创建一副牌.
char *suits_str[4] = {"Spades", "Hearts", "Diamonds", "Clubs"};
char *faces_str[13] = {"2", "3", "4", "5", "6", "7", "8", "9",
"10", "J", "Q", "K", "A"};
Run Code Online (Sandbox Code Playgroud)
一切顺利,代表卡片非常简单.但是当分析手来确定胜利者时,似乎使用char类型值是一个非常糟糕的主意.所以我想将套装改为int值,其中0 = Clubs,1 =钻石,2 = Hearts,3 =黑桃,面部 0 = 2(deuce),1 = 3,11 = King,12 = Ace.(这是我的想法,但我不知道如何将这些字符串值分配给他们)
所以这里有我的阵列,
int suits[4] = {0, 1, 2, 3};
int faces[13] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将这些int值转换为匹配的字符串值.我应该使用什么方法?
从初始化程序中可以看出,您不需要数组来表示卡值和面,而是表示resp之间的简单数值.可以使用0和12表示值,0和3表示面.要转换为字符串,请使用卡值和面作为数组的索引,suits_str并且faces_str:
int suit = 0; /* spades */
int face = 12; /* ace */
printf("I am the %s of %s\n", suits_str[suit], faces_str[face]);
Run Code Online (Sandbox Code Playgroud)
您可以使用枚举让您更具可读性:
enum suits { SPADES, HEARTS, DIAMONDS, CLUBS };
enum faces { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN,
JACK, QUEEN, KING, ACE };
int suit = SPADES;
int face = ACE;
printf("I am the %s of %s\n", suits_str[suit], faces_str[face]);
Run Code Online (Sandbox Code Playgroud)
另一个想法是将卡从0到51编号并使用公式来提取面部和套装:
int card = rand() % 52;
int suit = card / 13;
int face = card % 13;
printf("I am the %s of %s\n", suits_str[suit], faces_str[face]);
Run Code Online (Sandbox Code Playgroud)
您可以通过初始化52个int的数组并使用一种简单的方法对其进行洗牌来创建一副牌:
int deck[52];
for (int i = 0; i < 52; i++) {
/* start with a sorted deck */
deck[i] = i;
}
for (int i = 0; i < 1000; i++) {
/* shuffle by swapping cards pseudo-randomly a 1000 times */
int from = rand() % 52;
int to = rand() % 52;
int card = deck[from];
deck[from] = deck[to];
deck[to] = card;
}
printf("Here is a shuffled deck:\n"
for (int i = 0; i < 52; i++) {
int card = deck[i];
int suit = card / 13;
int face = card % 13;
printf("%s of %s\n", suits_str[suit], faces_str[face]);
}
Run Code Online (Sandbox Code Playgroud)