2015-05-03 109 views
0

因此,首先我有一個卡牌號碼爲[2-14]的卡牌,[Card] []對象中的值爲[0] - [12] (等級)2-14等等,用於鑽石[13] - [25],心臟[26] - [38],黑桃[39] - [51]。如何在卡牌遊戲卡洗牌()中切換卡牌位置

然後我用的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'); 


    } 

這改變了值的數字2-14作爲從0到51的隨機整數,我不明白的唯一部分是如何取這個隨機整數來替換我的值2-14並且讓它如此(例如)卡[14] = 35那麼交換卡[ 14]與卡[35]。我沒有使用Collections或ArrayList的經驗。

回答

1

在shuffle()中,您實際上並不想創建新卡,只需交換它們即可。我建議使用(int)(Math.random()* 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; 
    } 
} 

希望有所幫助。