I am trying to deal a deck of 52 playing cards amongst 4 players equally, meaning they will each have 13 cards each. Can only deal cards 4 each

我与影子孤独终老i 提交于 2020-12-15 05:15:42

问题


I am trying to deal a deck of 52 playing cards amongst 4 players equally, meaning they will each have 13 cards each. I can only seem to deal 4 cards each and i'm not sure why. Any help would be great. I have also attached an image of the output : OUTPUT

 public void deals() {
                for (int i = 0; i < 4; i++) {
                    System.out.println("** Player " + (i + 1) + " has been dealt the following cards: **");
                    for (int j = 0; j <4; j++) {
                        //System.out.println(ranks[i + j * 4] + " of " + suits[j]);
                        System.out.println(ranks[i + j] + " of " + suits[j]);

                    }
                }
            }

When I change the 4 to a higher number in System.out.println(ranks[i + j * 4] + " of " + suits[j]);I get an error.


回答1:


It seems that you need to create (and shuffle) a deck of cards first and then to deal the cards to 4 players:

// setup a card deck
List<Card> deck = new ArrayList<>();
for (int i = 0; i < ranks.length; i++) {
    for (int j = 0; j < suits.length; j++) {
        deck.add(new Card(ranks[i], suits[j]));
    }
}
// shuffle
Collections.shuffle(deck);

// deal
int players = 4;
for (int p = 0; p < players; p++) {
    System.out.println("Player " + (p + 1) + " gets these cards:");
    for (int i = 0, n = deck.size() / players; i < n; i++) {
        System.out.println(deck.get(p + players * i));
    }
}

It may be convenient to use Java streams to present the cards as collection of players' lists of cards:


Collection<List<Card>> playerCards = IntStream
        .range(0, deck.size())  // indexes in range [0..52)
        .boxed()
        // "dealing" cards 1 by 1
        .collect(Collectors.groupingBy(i -> i % players, Collectors.mapping(i -> deck.get(i), Collectors.toList())))
        .values();

// print cards per player        
playerCards
        .stream() // stream of List<Card>
        .map(p ->  p.stream()  // stream of Card of the player
                    .sorted()  // if Card class implements Comparable<Card>
                    .map(Card::toString)
                    .collect(Collectors.joining(" ")) // get player's hand
        )
        .forEach(System.out::println);

Sample output (suits are sorted in order ♥ ♦ ♠ ♣):

4♥ J♥ Q♥ K♥ 2♦ 3♦ 6♠ 7♠ 8♠ 10♠ Q♠ A♣ K♣
2♥ 5♦ 6♦ 7♦ 9♦ A♠ 4♠ 9♠ K♠ 2♣ 4♣ 6♣ 10♣
5♥ 6♥ 10♥ 8♦ 2♠ 3♠ J♠ 3♣ 5♣ 7♣ 8♣ 9♣ Q♣
A♥ 3♥ 7♥ 8♥ 9♥ A♦ 4♦ 10♦ J♦ Q♦ K♦ 5♠ J♣


来源:https://stackoverflow.com/questions/64960423/i-am-trying-to-deal-a-deck-of-52-playing-cards-amongst-4-players-equally-meanin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!