我试图在4个玩家中平均处理52张扑克牌,这意味着他们每人将有13张扑克牌每人只能发4张牌

bvuwiixz  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(298)

我试着在4个玩家中平分52张扑克牌,这意味着他们每人将有13张扑克牌。我似乎每人只能发4张牌,我不知道为什么。任何帮助都会很好。我还附上了输出的图像: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]);

                    }
                }
            }

当我把4换成一个更大的数字时 System.out.println(ranks[i + j * 4] + " of " + suits[j]); 我出错了。

aij0ehis

aij0ehis1#

似乎您需要先创建(并洗牌)一副牌,然后将这些牌发给4名玩家:

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

使用java流将卡片呈现为玩家卡片列表的集合可能很方便:

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

样本输出(套装按顺序排序) ♥ ♦ ♠ ♣ ):

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♣

相关问题