提问者:小点点

如何在桥牌游戏的卡牌洗牌()中切换卡牌位置


因此,首先我有一副牌,其中数字2-14作为俱乐部或[0]-[12]在Card[]对象中,价值(等级)2-14为钻石[13]-[25],红心[26]-[38],黑桃[39]-[51]。

然后,我必须通过在shaffle()类(例如…

//Holds an array of card objects
private Card [] cards  = new Card [52];

//Holds number of cards remaining in deck
private int count;

public Deck()
{
    for (int i = 0; i <= 12; i++) {
        cards[i] = new Card(i+2, 'C');
        count = 52-13;
    }

    for (int i = 13; i <= 25; i++) {
        cards[i] = new Card(i-13+2, 'D');
        count = 39-13;
    }

    for (int i = 26; i <= 38; i++) {
        cards[i] = new Card(i-26+2, 'H');
        count = 26-13;
    }

    for (int i = 39; i <= 51; i++) {
        cards[i] = new Card(i-39+2, 'S');
        count = 13-13;
    }
}

public void shuffle()
    {
        for (int i = 0; i <= 51; i++)
            if (i <= 12) 
                cards[i] = new Card((int)(Math.random() * 52), 'C');
            else if (i <= 25) 
                cards[i] = new Card((int)(Math.random() * 52), 'D');
            else if (i <= 38) 
                cards[i] = new Card((int)(Math.random() * 52), 'H');
            else if (i <= 51) 
                cards[i] = new Card((int)(Math.random() * 52), 'S');


    }

这将数字2-14的值更改为从0-51的随机整数,我唯一不明白的部分是如何取那个随机整数来替换我的值2-14,并使其(例如)卡[14]=35,然后用卡[35]交换卡[14]。我没有使用集合或数组列表的经验。


共1个答案

匿名用户

在shuffle()中,您实际上并不想创建新卡,只需交换它们。我建议使用(int)(Math.随机()*52)选择数组索引的值,然后使用临时变量来执行交换。

public void shuffle()
{ // replace 51 with any arbitrary number
  for (int i = 0; i <= 51; i++) {
    // two cards to swap
    int j = (int)Math.floor(Math.random() * 52);
    int k = (int)Math.floor(Math.random() * 52);

    // swap cards
    Card temp = card[j];
    card[j] = card[k];
    card[k] = temp;
  }
}

希望有帮助。