2013-12-14 3 views
0

질문 (짧은 버전) : 어떻게 ArrayList의 요소를 서로 비교합니까?ArrayList 포커 게임에서의 비교 Java

저는 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() 메소드 당신이 작동하지 않습니다하지만, ArrayList를 반복하는 방법을 말했다 경우 ..

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()); 
     } 
    } 
+0

'checkHnads'는 정확히 무엇을하고 어떻게 작동하지 않습니까? –

+1

@peeskillet 아직 아무 것도하지 않는다고 생각합니다. 나는 그것이 OP가 요구하고있는 것이라고 생각한다. Mikael 정확히 무슨 문제입니까? 내가 가지고있는 것은 각 플레이어의 손에 대한 ArrayList입니다. 따라서 카드를 가져 와서 포커 규칙과 비교하십시오. 질문은 실제로 ArrayList 또는 포커의 카드 값을 비교해야합니까? – Radiodef

+0

@Radiodef 난 arraylist 안에있는 카드 안의 정보에 접근하는 방법을 모르겠습니다. 나는 [arraylist name] .get (0) .getRank()를 사용하여 슈트에 접근하는 방법을 알아 냈습니다.하지만 스트레이트 (순위에서)를 찾는 데 어려움을 겪었습니다. 또 다른 로얄 플러시> 종류의 3> 플러시> 스트레이트 (또는 순서가 실제로 무엇이든). – MikaelCMiller

답변

1

아마도 포커 핸드를 평가하려면 아마도 데이터 구조를 통해 루프를 돌리는 것이 가장 일반적입니다 (배열, 목록, w 일 수 있음). hatever) 카드를 서로 비교하십시오. 예를 들어 여기에 바로 비교하는 일부 의사 자바의 다음 위의 구조는 내가 얻을 것이다하는 정렬됩니다 가정

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 */ 
} 

그러나 헬퍼 메서드를 사용하면 코드를 구성하는 데 도움이됩니다.

도움이 되었기를 바랍니다. 승자가 있는지 결정하기 위해 손으로 점수를 매기려면 점수를 반환하는 다른 메서드를 열거 형에 추가하기 만하면됩니다. 그런 다음 가장 큰 것을보십시오.

+0

나는 손을 통해 반복하는 데 많은 어려움을 겪고 있었지만, 쪽으로. 또한 각 카드의 순위와 수트에 액세스하려면 루프를 통해 수행해야합니다. 나는 이것을 알아 내려고 노력했지만, 당신은 그것을 정리했습니다. – MikaelCMiller

1

확실하지

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

문자열은 인터넷 용 교체 할 수 있습니다 , 요법 ..

+0

이 과정을 반복하는 데 도움이됩니다. 감사합니다. 나는 특정 값 (카드와 슈트의 랭크)을 비교하여 직선, 플러시, 3 가지 등을 알아내는 방법을 알아야합니다. – MikaelCMiller