比较ArrayList扑克游戏Java

时间:2013-12-14 00:24:01

标签: java arraylist poker

问题(简​​短版):如何将ArrayList中的元素相互比较?

我已经将ArrayList的大部分基础知识都很好地添加(添加,获取,设置,大小......)。我无法踩到ArrayList来比较对象(扑克牌的价值和套装)以确定最好的扑克牌。我有一个班级来存储有关卡片的信息。

卡片类:

    /** class Card : for creating playing card objects
     *  it is an immutable class.
     *  Rank - valid values are 1 to 13
     *  Suit - valid values are 0 to 3
     *  Do not modify this class!
     */
    class Card {

        /* constant suits and ranks */
        static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
        static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};

        /* Data field of a card: rank and suit */
        private int cardRank;  /* values: 1-13 (see Rank[] above) */
        private int cardSuit;  /* values: 0-3  (see Suit[] above) */

        /* Constructor to create a card */
        /* throw PlayingCardException if rank or suit is invalid */
        public Card(int rank, int suit) throws PlayingCardException { 
        if ((rank < 1) || (rank > 13))
            throw new PlayingCardException("Invalid rank:"+rank);
        else
                cardRank = rank;
        if ((suit < 0) || (suit > 3))
            throw new PlayingCardException("Invalid suit:"+suit);
        else
                cardSuit = suit;
        }

        /* Accessor and toString */
        /* You may impelemnt equals(), but it will not be used */
        public int getRank() { return cardRank; }
        public int getSuit() { return cardSuit; }
        public String toString() { return Rank[cardRank] + " " + Suit[cardSuit]; }


        /* Few quick tests here */
        public static void main(String args[])
        {
        try {
            Card c1 = new Card(1,3);    // A Spades
            System.out.println(c1);
            c1 = new Card(10,0);    // 10 Clubs
            System.out.println(c1);
            //c1 = new Card(10,5);        // generate exception here
        }
        catch (PlayingCardException e)
        {
            System.out.println("PlayingCardException: "+e.getMessage());
        }
        }
    } 

还有一个班级来检查每一张牌(这是我无法搞清楚的等级)。我目前添加了代码,使其添加一个ArrayList并再次打印每一个(只是为了确保我可以创建一个单独的ArrayList,因为我对我的能力不太满意),但我无法弄清楚如何比较每张卡的元素(等级和套装)。

检查手班:

/** Check current currentHand using multipliers and goodHandTypes arrays
*  Must print yourHandType (default is "Sorry, you lost") at the end o function.
*  This can be checked by testCheckHands() and main() method.
*/
    private void checkHands()
    {
        // implement this method!
        ArrayList<Card> multiplierCheck = new ArrayList<Card>();
        String yourhandtype = "Sorry, you lost";

        for (int toList = 0; toList<5; toList++) {
                multiplierCheck.add(currentHand.get(toList));
            }
        System.out.println(multiplierCheck);

        System.out.println(yourhandtype);
    }

一种测试双手的方法,可以创造出赢手牌(直线,同花,三种)。我无法弄清楚如何在我的Check Hands Class中比较这些卡片。

testCheckHands()方法

public void testCheckHands()
    {
        try {
            currentHand = new ArrayList<Card>();

        // set Royal Flush
        currentHand.add(new Card(1,3));
        currentHand.add(new Card(10,3));
        currentHand.add(new Card(12,3));
        currentHand.add(new Card(11,3));
        currentHand.add(new Card(13,3));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Straight Flush
        currentHand.set(0,new Card(9,3));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Straight
        currentHand.set(4, new Card(8,1));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Flush 
        currentHand.set(4, new Card(5,3));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // "Royal Pair" , "Two Pairs" , "Three of a Kind", "Straight", "Flush   ", 
        // "Full House", "Four of a Kind", "Straight Flush", "Royal Flush" };

        // set Four of a Kind
        currentHand.clear();
        currentHand.add(new Card(8,3));
        currentHand.add(new Card(8,0));
        currentHand.add(new Card(12,3));
        currentHand.add(new Card(8,1));
        currentHand.add(new Card(8,2));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Three of a Kind
        currentHand.set(4, new Card(11,3));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Full House
        currentHand.set(2, new Card(11,1));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Two Pairs
        currentHand.set(1, new Card(9,1));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // set Royal Pair
        currentHand.set(0, new Card(3,1));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");

        // non Royal Pair
        currentHand.set(2, new Card(3,3));
        System.out.println(currentHand);
            checkHands();
        System.out.println("-----------------------------------");
        }
        catch (Exception e)
        {
        System.out.println(e.getMessage());
        }
    }

2 个答案:

答案 0 :(得分:1)

不确定你是否说它不起作用,而是迭代一个arrayList ..

for (String s : arrayList)
    if (s.equals(value))
         // ...

可以替换int,ect ..

答案 1 :(得分:1)

要评估扑克手牌,你可能会做的最常见的事情是循环数据结构(可能是数组,列表,等等)并将卡片相互比较。例如,这里有一些伪Java来比较直线:

for (int i = 1; i < /* length of hand */; i++) {

    if (/* rank for card i is not 1 greater
           than rank for card i - 1 */) {

         /* not a straight */
    }
}

请注意,上面假设我将对结构进行排序。此外,由于扑克之手是如此不同,所以所有的实际上并不是“最佳方式”。你必须为每一个编写一个例程。所以我建议你想出一些可以帮助你的抽象。我要做的是使用Enum。这是一个基本的例子:

enum PokerHand {
    STRAIGHT {
        @Override
        boolean matches(List<Card> hand) {

            for (int i = 1; i < hand.size(); i++) {
                if (
                    card.get(i).getRank() !=
                    card.get(i - 1).getRank() + 1
                ) {
                    return false;
                }
            }

            return true;
        }
    },
    FOUR_OF_A_KIND {
        @Override
        boolean matches(List<Card> hand) {

            int[] rankCount = new int[14];

            /* count up the ranks in the hand */
            for (Card card : hand) {
                rankCount[card.getRank()]++;
            }

            boolean foundHasOne = false;
            boolean foundHasFour = false;

            /* now evaluate exclusively
             * there must be only a 1 count and a 4 count
             */
            for (int i = 1; i < rankCount.length; i++) {

                if (rankCount[i] == 1) {
                    if (!foundHasOne) {
                        foundHasOne = true;
                    } else {
                        return false;
                    }

                } else if (rankCount[i] == 4) {
                    if (!foundHasFour) {
                        foundHasFour = true;
                    } else {
                        return false;
                    }

                } else if (rankCount[i] != 0) {
                    return false;
                }
            }

            return true;
        }
    },
    ROYAL_FLUSH {
        final int[] rfRanks = {
            1, 10, 11, 12, 13
        };

        @Override
        boolean matches(List<Card> hand) {

            for (int i = 0; i < rfRanks.length; i++) {
                if (rfRanks[i] != hand.get(i).getRank())
                    return false;
            }

            return true;
        }
    };

    abstract boolean matches(List<Card> hand);
}

当然,上述内容并未涵盖所有扑克牌手,仅举几例。此外,我不玩扑克,所以这可能有点不对,但重点是展示一些评估示例。

如前所述,如果您提前对列表进行排序,这会变得更加简单。 java.util.Collectionsjava.util.Arrays具有实用方法,因此它非常简单。如果您在检查手牌后不希望排序继续存在,请确保在排序前制作副本。

/* make a shallow copy */
List<Card> sortedHand = new ArrayList<Card>(playerHand);

/* sort based on rank */
Collections.sort(sortedHand, new Comparator<Card>() {
    @Override
    public int compare(Card card1, Card card2) {
        int rank1 = card1.getRank();
        int rank2 = card2.getRank();

        if (rank1 > rank2) {
            return 1;

        if (rank1 < rank2)
            return -1;

        return 0;
    }
});

请参阅Comparator#compare,了解其工作原理,但基本上是排序。

使用枚举或类似的东西,然后在逻辑上使评估相当简单。

现在我建议的是制作一个评估方法,因为这样你就可以方便地返回手的常数。

static PokerHand evaluateHand(List<Card> hand) {
    for (PokerHand potential : PokerHand.values()) {
        if (potential.matches(hand))
            return potential;
    }

    /* imply there is not a matching hand */
    return null;
}

因此,在您复制了手并对其进行了分类后,您可以致电进行评估:

PokerHand evaluated = evaluateHand(sortedHand);

if (evaluated != null) {
    /* it's a recognized hand */
}

您不必制作方法,您可以执行以下操作:

PokerHand evaluated = null;
for (PokerHand potential : PokerHand.values()) {
    if (potential.matches(sortedHand)) {
        evaluated = potential;
        break;
    }
}

if (evaluated != null) {
    /* it's a recognized hand */
}

但是使用辅助方法有助于组织代码。

我希望有所帮助。如果您还需要得分,以确定是否有赢家,只需在枚举中添加另一种返回分数的方法。然后看看哪一个是最大的。