1

我正在创建一个二十一点程序,并试图在程序开始时向玩家随机发牌。这是我用 Java 编写的最初向玩家发牌的函数。

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

我认为 Random 方法和 for 循环存在问题,因为虽然每个玩家的两张牌是随机生成的,但所有玩家都得到了相同的牌。

4

2 回答 2

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

如果/当您确实需要生成随机整数时,您应该使用truncation,而不是四舍五入。否则,底部值将只有一半的期望概率..

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;

填空。

于 2013-10-04T10:20:29.720 回答
0

尝试使用nextInt(n)类的java.util.Random。哪里n = 13。但从表面上看,问题似乎出在其他地方。该函数确实返回随机值,但您没有在其他地方正确使用它。

于 2013-10-04T10:23:38.410 回答