简体   繁体   English

如何在桥牌游戏的Card Deck shuffle()中切换纸牌位置

[英]How to switch card positions in Card Deck shuffle() for Bridge game

So first of all I have a deck which has numbers 2-14 as Clubs or [0]-[12] in the Card [] object, and values(rank) 2-14 so on for Diamonds [13]-[25], Hearts [26]-[38], Spades [39]-[51]. 因此,首先,我有一个牌组,其卡片[]对象中的俱乐部为2-14,俱乐部为[0]-[12],钻石[13]-[25]的值(等级)为2-14,依此类推。 ,心[26]-[38],黑桃[39]-[51]。

I then have to shuffle these cards with their given values by using Math.random() inside a shuffle() class such as... 然后,我必须通过在shuffle()类中使用Math.random()将这些卡以其给定的值进行混洗,例如...

//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');


    }

This changes the values for the numbers 2-14 as random integers from 0-51, the only part I don't understand is how to take that random integer which replaces my values 2-14 and have it so that if (as example) card[14] = 35 THEN swap card[14] with card[35]. 这会将数字2-14的值从0-51更改为随机整数,我唯一不了解的部分是如何获取替换我的值2-14的随机整数并将其替换为if(例如) card [14] = 35然后将card [14]与card [35]交换。 I have no experience with using Collections or ArrayList. 我没有使用Collections或ArrayList的经验。

In shuffle(), you don't actually want to create new cards, just swap them. 在shuffle()中,您实际上不需要创建新卡,只需交换它们即可。 I would suggest using (int)(Math.random() * 52) to choose the value of the array index and then use a temp variable to perform the swap. 我建议使用(int)(Math.random()* 52)选择数组索引的值,然后使用temp变量执行交换。

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;
  }
}

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM