2013-10-04 56 views
1

我正在創建一個二十一點程序,並試圖在程序開始時向玩家發送隨機卡。這是我用Java編寫的函數,用於向玩家初始交易牌。Java在for循環中生成隨機數

public static int[][] initDeal(int NPlayers) 
    { 
     int hands[][] = new int[NPlayers][2]; 

     for(int a = 0; a<NPlayers; a++) 
     { 

      hands[a][0] = (int)Math.round((Math.random() * 13))-1; 
      hands[a][1] = (int)Math.round((Math.random() * 13))-1; 

     } 
     return hands; 
    } 

我認爲這是與隨機方法的問題,並在for循環中,雖然被隨機生成的兩個卡每個球員,所有球員都處理相同的牌。

+0

你的問題是什麼? – Masudul

+0

如果我是你,我會換出你的多維數組以獲得一個「Hand」對象的列表或數組。將使它更清潔。 – christopher

+0

爲什麼不使用java.util.Random.nextInt(13)'? – Mureinik

回答

1

你需要有一副牌或者某些東西,然後隨機洗牌,然後把它們從甲板上移走,交給玩家。

否則,您可以處理同一張卡片兩次,這在現實生活中是不可能的。 (雖然較大的甲板可以使用。)

public class Card { 
    public enum Suit {HEART, DIAMOND, CLUB, SPADE}; 
    public int getValue();   // Ace, Jack, Queen, King encoded as numbers also. 
} 

public class Deck { 
    protected List<Card> cardList = new ArrayList(); 

    public void newDeck() { 
     // clear & add 52 cards.. 
     Collections.shuffle(cardList); 
    } 
    public Card deal() { 
     Card card = cardList.remove(0); 
     return card; 
    } 
} 

如果/當你需要生成隨機整數,你應該使用截斷,而不是四捨五入。否則,底部值將只有一半的期望概率..

int y = Math.round(x) 
0 - 0.49 -> 0   // only half the probability of occurrence! 
0.5 - 1.49 -> 1 
1.5 - 2.49 -> 2 
.. 

有沒有Math函數來截斷,只投給int

int faceValue = (int) ((Math.random() * 13)) + 1; 

或者,您可以使用Random.nextInt(n)函數來執行此操作。

Random rand = new Random(); 
int faceValue = rand.nextInt(13) + 1; 

填空。

0

嘗試使用類java.util.RandomnextInt(n)。其中n = 13。但從外觀上看,問題似乎在別處。該函數確實返回了隨機值,但您沒有在其他地方正確使用它。