写这个的更优雅的方式? (纸牌组)

时间:2018-08-22 12:47:33

标签: c

我目前正在编写二十一点模拟器,并且正在生成n副牌来玩:

int i;
int value = 1;
for (i = 0; i < deck->n_cards; i++) {
    deck->cards[i] = value;
    value++;
    if (value == 14) value = 1;
}

(deck-> n_cards%52 == 0)

我尝试了一种使用模运算编写相同内容的方法,但是我使用不了1个套牌就无法摆脱它。我认为使用if真的很丑。有没有更优雅的解决方案?

3 个答案:

答案 0 :(得分:1)

我对二十一点游戏不熟悉,但是我从您的代码中了解到,值范围是1到13。 尝试以下代码:

int i;
for (i = 0; i < deck->n_cards; i++) {
    deck->cards[i] = (i % 13) + 1;
}

i%13的范围是0到12,对此加1会使范围从1到13

答案 1 :(得分:0)

在代码中使用“魔术”数字不好。定义或枚举一些值...您只在合计每手牌时才关心纸牌的价值。

#define CARDS_IN_DECK 52
#define CARDS_IN_SUIT 13
#define DECKS_IN_BOOT 8
#define SUITS_IN_DECK 4

#define HEARTS 0
#define SPADES 1
#define CLUBS  2
#define DIAMONDS 3
#define CARD_SUIT(c)  suits[((c)/CARDS_IN_SUIT)]
#define CARD_FACE(c)  cards[((c)%CARDS_IN_SUIT)]
#define CARD_VALUE(c) cardValue[((c)%CARDS_IN_SUIT)]

int deck[DECKS_IN_BOOT][CARDS_IN_DECK];
int boot, card;
int needsShuffle = 1;
const char *suits[] = {"Hearts", "Spades", "Clubs", "Diamonds"};
const char *cards[] = {"Ace", "Two", "Three", "Four", "Five", "Six",
                  "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
const int cardValue[] = {11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};

void shuffle()
{
    int num_shuffles = 1000;
    int i, j, k, m, n, temp;

    printf("\n\t Shuffling ... \n");
    /* Create the boot */
    for (i=0;i<DECKS_IN_BOOT;i++)
        for (j=0;j<CARDS_IN_DECK;j++)
            deck[i][j] = j;

    for ( ;num_shuffles--; )
    {
        m = rand() % DECKS_IN_BOOT;
        n = rand() % DECKS_IN_BOOT;

        j = rand() % CARDS_IN_DECK;
        k = rand() % CARDS_IN_DECK;

        temp = deck[n][j];
        deck[n][j] = deck[m][k];
        deck[m][k] = temp;
    }
    needsShuffle = boot = card = 0;
}

void testPrintDeck()
{
    int i, j;

    /* Create the boot */
    for (i=0;i<DECKS_IN_BOOT;i++)
        for (j=0;j<CARDS_IN_DECK;j++)
            printf("%d %s %s\n",
                   deck[i][j],
                   CARD_FACE(deck[i][j]),
                   CARD_SUIT(deck[i][j]));
}

main(int c, char *v[])
{
    srand(time(0));
    shuffle();
    testPrintDeck();
}

答案 2 :(得分:0)

如果您想要的是给定指向52个int数组的指针,并将其填充到4组1-13中,则更简单的方法是IMO:

#include <stdio.h>

typedef struct deck{
    int n_cards;
    int cards[52];
}deck_t;

 int main(void) {

    deck_t *deck = malloc(sizeof(deck_t));
    deck->n_cards = 52;

    int value = 1, suit_size = 13, num_of_suits = 4;

    /* 1st option*/
    for(int i = 0; i < deck->n_cards / num_of_suits; i++){
        for(int j = 0; j < deck->n_cards; j += suit_size){
            deck->cards[i+j] = value;
        }
        value++;
    }

    for(int i = 0; i < deck->n_cards; i++){
        printf("%d ", deck->cards[i]);
    }

    /* 2nd option*/
    value = 0;
    for(int i = 0; i < deck->n_cards; i++){
        deck->cards[i] = 1 + value++ % 13;
    }

    for(int i = 0; i < deck->n_cards; i++){
        printf("%d ", deck->cards[i]);
    }
    return 0;
}