我有这个作业,老师要我们用Java创建纸牌游戏“ War”。其中很大一部分是将52张不同的牌洗牌到两个玩家手中。对于改组它的任何帮助,我将不胜感激。我是一个没有经验的编码员,其他发布者对我来说没有任何意义。
我的代码:

package shuffle;

import java.util.Random;

public class SHUFFLE {

    public static void main(String[] args) {
        shuffle();
    }

    public static void shuffle() {
        Random r = new Random();
        int[] hand1 = new int[26];
        int[] hand2 = new int[26];
        int i = 1, rand, rand2;
        int o = 1;
        do {
            System.out.println("Top");
            rand = r.nextInt(52) + 1;
            rand2 = r.nextInt(2) + 1;
            System.out.println("number generated: "+rand);
            System.out.println("sector: " + rand2);
            if (rand2 == 1) {
                if (rand <= 52) {
                    while (hand1[o] > 0) {
                        if (hand1[o] == rand) {
                        } else {
                            hand1[o]--;
                        }
                    }
                    while (hand2[i] > 0) {
                        if (hand2[i] == rand) {
                        } else {
                            hand2[i]--;
                        }
                        hand1[o] = rand;
                        o++;
                    }
                }

            }

            if (rand2 == 2) {
                if (rand <= 52) {
                    while (hand1[o] > 0) {
                        if (hand1[o] == rand) {
                        } else {
                            hand1[o]--;
                        }
                    }
                    while (hand2[i] > 0) {
                        if (hand2[i] == rand) {
                        } else {
                            hand2[i]--;
                        }
                        hand2[i] = rand;
                        i++;
                    }
                }

            }

        }while(hand1[o] < 26 && hand2[i] < 26);
    }

}

最佳答案

不要浪费时间事先洗牌,费舍尔·耶茨(Fisher Yates)洗牌是从分类卡片中随机选择卡片的更有效的方法。

您可以看到this answer来了解它是如何完成的,然后基本上就是使用该算法将选定的卡片分发给其他人。

因此,最重要的是(由于是类作业,所以是伪代码),您可以使用以下代码创建两只手,每只二十六个卡(具有基于一个的数组):

# Set up deck of cards with initial size, and empty hands.

cards[] = [acespades, twospades, ..., queenhearts, kinghearts]
quant = size(cards)

hand1 = []
hand2 = []

# Need to distribute entire deck.

while quant > 0:
    # Get card for first hand using Fisher Yates shuffle

    index = random(1..quant)
    hand1.append(cards[index])
    cards[index] = cards[quant]
    decrement quant

    # If no cards left, exit the loop.

    if quant == 0:
        exit while

    # Now get card for second hand.

    index = random(1..quant)
    hand2.append(cards[index])
    cards[index] = cards[quant]
    decrement quant


请注意那里的额外检查,以了解原始卡组的卡数是否为奇数(if ... exit while位)。如果您知道卡座将是均匀的,则不需要这样做-我只是将其放在其中,以便事前无法知道卡座的大小。

还要注意,有机会重构发卡的代码,以免重复发生。我将其保留为教育性练习。

10-07 13:59