简体   繁体   中英

Dealing four random hands from a deck of cards in Java using arrays

I am trying to write some code that creates two arrays, one with suits, one with values, of a deck of cards. It then shuffles the cards randomly and prints out the cards that each of the four players is dealt. If anyone could give me some ideas on how to proceed from what I have I would be grateful. The main problems I'm having is how to switch the arrays around (shuffle) and then how to show what the players get (deal).

public class BridgeHands 

{

private card[] deck;
private int cardsUsed;

public static void dealHands() 
{
    final int SUITS = 4;                    // number of suits in a standard deck
    final int CARDS_PER_SUIT = 13;          // number of cards in each suit
    final int CARDS = SUITS*CARDS_PER_SUIT; // number of cards in a standard deck

    deck = new Card[CARDS];
    int cardCt = 0;
    for(int suit = 0; suit < SUITS; suit++)
    {
        for(int value = 1; value < CARDS_PER_SUIT; value++)
        {
            deck[cardCt] = new Card(value,suit);
            cardCt++;
        }
        cards used = 0;

    }
}

public void shuffle()
{
    for(int i = deck.length-1; i > 0; i--)
    {
        int rand = (int)(Math.random()*(i+1));
        Card temp = deck[i];
        deck[i] = deck[rand];
        deck [rand] = temp;
    }
    cards used = 0;
}

public int cardsLeft() 
{
    int cardsUsed = 0;
    return deck.length - cardsUsed;
}

public Card dealCard()
{
    if(cardsUsed == deck.length)
        throw new IllegalStateException("No cards are left in the deck.");
    cardsUsed++;
    return deck[cardsUsed - 1];
}

final int HANDS = 4;
final int CARDS_PER_HAND = CARDS/HANDS;

public static String cardName(int suit, int value)
{
    final String[] CARD_NAMES =
        {"not used", "ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"};
    final String[] SUIT_NAMES = 
        {"spades", "clubs", "diamonds", "hearts"};

    return CARD_NAMES[value] + " of " + SUIT_NAMES[suit];
}

}

i'm struggling with the same question as you, we're probably in the same unit. I've done a little more than you for the shuffling part, I've got:

int cards = 52;
    int card1, card2
    while (cards > 1)

            for( int k=0; k<100; k++ ) 
        { 
            card1 = rand.nextInt(52); 
            card2 = rand.nextInt(52); 
            int keepSuit = dk[card1]; 
            dk[card1] = dk[card2]; 
            dk[card2] = keepSuit; 
        }  

Maybe this helps? Not sure if it's right however, sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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