| 1 | package com.ociweb.emma.ex1; |
| 2 | |
| 3 | import java.util.Collections; |
| 4 | import java.util.Iterator; |
| 5 | import java.util.List; |
| 6 | |
| 7 | class Card implements Comparable { |
| 8 | |
| 9 | // this class uses old-style (and unsafe) enums for brevity |
| 10 | |
| 11 | public static final int TWO = 2, THREE = 3, FOUR = 4, FIVE = 5, SIX = 6, SEVEN = 7, |
| 12 | EIGHT = 8, NINE = 9, TEN = 10, JACK = 11, QUEEN = 12, KING = 13, ACE = 14; |
| 13 | public static final int CLUBS = 0, DIAMONDS = 1, HEARTS = 2, SPADES = 3; |
| 14 | |
| 15 | private final int rank; |
| 16 | private final int suit; |
| 17 | |
| 18 | public Card(int rank, int suit) { |
| 19 | this.rank = rank; |
| 20 | this.suit = suit; |
| 21 | } |
| 22 | |
| 23 | public int getSuit() { return suit; } |
| 24 | public int getRank() { return rank; } |
| 25 | |
| 26 | public boolean equalsRank(Card card) { return this.rank == card.rank; } |
| 27 | public boolean equalsSuit(Card card) { return this.suit == card.suit; } |
| 28 | |
| 29 | public int compareTo(Object obj) { |
| 30 | int result = 0; |
| 31 | |
| 32 | Card card = (Card) obj; |
| 33 | |
| 34 | if( this.rank != card.rank ) { |
| 35 | result = ( this.rank < card.rank ) ? -1 : 1; |
| 36 | } |
| 37 | |
| 38 | return result; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public class PokerHand { |
| 43 | public enum Hand { STRAIGHT_FLUSH, THREE_OF_KIND, STRAIGHT, FLUSH, PAIR, HIGH_CARD }; |
| 44 | |
| 45 | private List cards; // generics are not used, to increase readability |
| 46 | private boolean isPair; |
| 47 | |
| 48 | public PokerHand(List cards) { |
| 49 | // TODO: the hand should be verified as being legal, this check is omitted |
| 50 | // to keep the example simple |
| 51 | this.cards = cards; |
| 52 | // Collections.sort(this.cards); |
| 53 | } |
| 54 | |
| 55 | public Hand evaluate() { |
| 56 | Hand result = null; |
| 57 | |
| 58 | isPair = false; |
| 59 | |
| 60 | Iterator iterator = cards.iterator(); |
| 61 | Card previousCard = (Card) iterator.next(); |
| 62 | |
| 63 | while( iterator.hasNext() ) { |
| 64 | Card thisCard = (Card) iterator.next(); |
| 65 | |
| 66 | if( previousCard.equalsRank(thisCard) ) { |
| 67 | |
| 68 | if( !isPair ) { |
| 69 | // one pair encountered |
| 70 | isPair = true; |
| 71 | } else { |
| 72 | // we have already seen one pair, so this 2nd pair => 3 of a kind |
| 73 | isPair = false; |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | previousCard = thisCard; |
| 78 | } |
| 79 | |
| 80 | result = (isPair) ? Hand.PAIR : Hand.HIGH_CARD; |
| 81 | |
| 82 | return result; |
| 83 | } |
| 84 | } |