gpt4 book ai didi

c - C中如何将每手牌先按牌值排序,再按花色排序?

转载 作者:行者123 更新时间:2023-11-30 20:55:44 25 4
gpt4 key购买 nike

我想对每手牌中的 5 张牌进行排序,首先按牌值排序(从 A 到 K),然后按牌组排序(从红心,然后是方 block ,然后是梅花,最后是黑桃),但事实并非如此。不工作。你怎样才能成功呢?

代码:

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

/* handy typedefs */
typedef unsigned char card;
typedef unsigned char pairs;

/* arrays for the names of things */
static char *suits[4] = {"Hearts","Diamonds","Clubs","Spades"};
static char *values[13]= {"Ace","Two","Three","Four","Five","Six","Seven",/
"Eight","Nine","Ten","Jack","Queen","King"};
static char *colour[2]= {"Black","Red"};
int compareface(const void* c1,const void *c2);

int main()
{
card deck[52][24],*deckp;
int s, c, a;

for(s = 0; s < 4; s++)//for filling a deck of 52 cards
{
for(c = 0; c < 13; c++)
{
if (s== 0 || s== 1)
sprintf(deck[s * 13 + c], "%s of %s", values[c], suits[s]);
else
if (s== 2 || s== 3)
sprintf(deck[s * 13 + c], "%s of %s", values[c], suits[s]);
}
}

for(a = 0; a < 52; a++)
{
printf("%s\n", deck[a]);
}

int hand,cd,winner;
int irand;

srand(time(NULL)); /* seed the random number generator */

for (hand=0;hand<5;hand++)
{
printf("Hand %i:\n",hand+1 );
for ( i = 0; i < 5; i++) {
irand = (rand() % 52);
// qsort(deck, 52, sizeof(int), compareface);
if ( (irand >= 0) && (irand <26))
printf(" %s, is Red.\n ", deck[irand]);
else
if ( (irand >= 26) && (irand <52))
printf(" %s, is Black.\n ", deck[irand]);
}
}
/* determine the winner and print it */
return 0;
}

void shuffle(card deck[52])
{
int i,rnd;
card c;

for(i=0;i<52;i++)
{
/* generate a random number between 0 & 51 */
rnd=rand() * 52.0 / RAND_MAX;
c = deck[i];
deck[i] = deck[rnd];
deck[rnd] = c;
}
}

int compareface(const void* c1, const void *c2)
{
/* This function extracts the two cards face values
and returns 1 if cd1 > cd2, 0 if cd1 == cd2, and
-1 otherwise. The weird argument types are for
compatibility with qsort(), the first two lines
decode the arguments back into "card".
*/
card cd1,cd2;
cd1=*((card*) c1);
cd2=*((card*) c2);

cd1= (cd1&0x1e)>>1;
cd2= (cd2&0x1e)>>1;

if (cd1>cd2)
return 1;

if (cd1==cd2)
return 0;

return -1;
}

最佳答案

如果你给每张卡牌一个数值并将这个值保存在牌组数组中,会更容易。现在,一种方法是:1 = 黑桃 A,2 = 黑桃 2 ... 13 = 黑桃 K,14 = 红心 A 等等,但更难排序。

然而,另一种方法是:0 = 两张方 block ,1 = 两张梅花,2 = 两张红心,3 = 两张黑桃,4 = 三个钻石,依此类推。

如果您使用这种方式,(卡号)/4 将为您提供值(带有偏移量),(卡号)% 4 为您提供花色。

此外,return (card1 number) - (card2 number) 为您提供您想要的比较函数。

希望有帮助

关于c - C中如何将每手牌先按牌值排序,再按花色排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com