質問

I'm creating a blackjack program and am trying to deal random cards to the players at the beginning of the program. This is the function I have written in Java to initially deal cards to players.

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

I think there is a problem with the Random method and the for loop as although the two cards for each player are being generated randomly, all players are dealt the same cards.

役に立ちましたか?

解決

You need to have a 'Deck' of cards or somesuch, and randomly shuffle them, and then deal them out to Players by removing them from the Deck.

Otherwise you can deal the same card twice, which is not possible in real life. (Though larger decks can be used.)

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

If/when you do need to generate random integers, you should use truncation, not rounding. Otherwise the bottom value will have only half its desired probability..

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
..

There's no Math function to truncate, just cast to int.

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

Or, you can use the Random.nextInt( n) function to do this.

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

Fill in the blanks.

他のヒント

Try using the nextInt(n) of the class java.util.Random. Where n = 13. But by the looks of it, the problem seems to be elsewhere. The function is indeed returning random values but you are not using it properly somewhere else.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top