2012-11-12 4 views
1

데크 맨 위에서 지정된 수의 카드를 제거하고 배열로 반환하는 메소드를 작성하려고합니다.데크에서 카드를 처리하기위한 Java 코드

이것은 내가 지금까지 해 온 것입니다. 데크 만들기, 데크 복사, 배열의 지정된 위치에있는 카드 반환 방법, 카드 ​​배열 크기 반환, 셔플 및 데크 잘림 올바른지). 여기에 카드 클래스는 갑판 방법은 내가에 도움이 필요 하나입니다

public class Card { 

    private final int suit; // 0, 1, 2, 3 represent Spades, Hearts, Clubs, 
          // Diamonds, respectively 

    private final int value; // 1 through 13 (1 is Ace, 11 is jack, 12 is 
           // queen, 13 is king) 

    /* 
    * Strings for use in toString method and also for identifying card images 
    */ 
    private final static String[] suitNames = { "s", "h", "c", "d" }; 
    private final static String[] valueNames = { "Unused", "A", "2", "3", "4", 
      "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; 

    /** 
    * Standard constructor. 
    * 
    * @param value 
    *   1 through 13; 1 represents Ace, 2 through 10 for numerical 
    *   cards, 11 is Jack, 12 is Queen, 13 is King 
    * @param suit 
    *   0 through 3; represents Spades, Hearts, Clubs, or Diamonds 
    */ 
    public Card(int value, int suit) { 
     if (value < 1 || value > 13) { 
      throw new RuntimeException("Illegal card value attempted. The " 
        + "acceptable range is 1 to 13. You tried " + value); 
     } 
     if (suit < 0 || suit > 3) { 
      throw new RuntimeException("Illegal suit attempted. The " 
        + "acceptable range is 0 to 3. You tried " + suit); 
     } 
     this.suit = suit; 
     this.value = value; 
    } 

    /** 
    * "Getter" for value of Card. 
    * 
    * @return value of card (1-13; 1 for Ace, 2-10 for numerical cards, 11 for 
    *   Jack, 12 for Queen, 13 for King) 
    */ 
    public int getValue() { 
     return value; 
    } 

    /** 
    * "Getter" for suit of Card. 
    * 
    * @return suit of card (0-3; 0 for Spades, 1 for Hearts, 2 for Clubs, 3 for 
    *   Diamonds) 
    */ 
    public int getSuit() { 
     return suit; 
    } 

    /** 
    * Returns the name of the card as a String. For example, the 2 of hearts 
    * would be "2 of h", and the Jack of Spades would be "J of s". 
    * 
    * @return string that looks like: value "of" suit 
    */ 
    public String toString() { 
     return valueNames[value] + " of " + suitNames[suit]; 
    } 

    /** 
    * [STUDENTS SHOULD NOT BE CALLING THIS METHOD!] Used for finding the image 
    * corresponding to this Card. 
    * 
    * @return path of image file corresponding to this Card. 
    */ 
    public String getImageFileName() { 

     String retValue; 
     retValue = suitNames[suit]; 
     if (value <= 10) 
      retValue += value; 
     else if (value == 11) 
      retValue += "j"; 
     else if (value == 12) 
      retValue += "q"; 
     else if (value == 13) 
      retValue += "k"; 
     else 
      retValue += "Unknown!"; 
     return "images/" + retValue + ".gif"; 
    } 
} 

입니다

public class Deck { 

    private Card[] cards; 

    public Deck() { 
     cards = new Card[52]; 
     int numberOfCard = 0; 
     for (int suit = 0; suit <= 3; suit++) { 
      for (int value = 1; value <= 13; value++) { 
       cards[numberOfCard] = new Card(value, suit); 
       numberOfCard++; 
      } 
     } 
    } 

    public Deck(Deck other) { 

     cards = new Card[other.cards.length]; 
     for (int i = 0; i < other.cards.length; i++) { 
      cards[i] = other.cards[i]; 
     } 
    } 

    public Card getCardAt(int position) { 
     if (position >= cards.length) { 
      throw new IndexOutOfBoundsException("Values are out of bounds"); 
     } else { 
      return cards[position]; 
     } 
    } 

    public int getNumCards() { 
     return cards.length; 
    } 

    public void shuffle() { 
     int temp = 0; 
     for (int row = 0; row < cards.length; row++) { 
      int random = (int) (Math.random() * ((cards.length - row) + 1)); 
      Deck.this.cards[temp] = this.getCardAt(row); 
      cards[row] = cards[random]; 
      cards[random] = cards[temp]; 
     } 

    } 

    public void cut(int position) { 
     Deck tempDeck = new Deck(); 
     int cutNum = tempDeck.getNumCards()/2; 
     for (int i = 0; i < cutNum; i++) { 
      tempDeck.cards[i] = this.cards[52 - cutNum + i]; 
     } 
     for (int j = 0; j < 52 - cutNum; j++) { 
      tempDeck.cards[j + cutNum] = this.cards[j]; 
     } 
     this.cards = tempDeck.cards; 
    } 

    public Card[] deal(int numCards) { 
     return cards; 
    } 

} 
+4

귀하의 질문은 무엇입니까? –

+0

잘못되었거나 도움이 필요한 내용을 말하지 않았습니다. 보조 노트에서 복사 생성자는 얕은 복사본 만 만들고 원하는 것이 아닐 수도 있습니다. –

+0

그는 "지정된 수의 카드를 덱 맨 위에서 제거하여 배열로 반환하는 메서드를 작성하려고합니다."그리고 Deck.deal()은 단지 스텁 일뿐입니다. 포스트는 지저분하지만 문제는 무엇인지 말합니다. – mgarciaisaia

답변

1

List의를 사용할 수 없습니다 제공, 그것은 또 다른 변수가 좋은 아이디어를 보인다 갑판의 최고 카드의 인덱스 :

public class Deck { 

    private Card[] cards; 
    private int topCardIndex; 

    public Deck() { 
     cards = new Card[52]; 
     int numberOfCard = 0; 
     for(int suit = 0; suit <= 3; suit++){ 
      for(int value = 1; value <= 13; value++){ 
       cards[numberOfCard] = new Card(value, suit); 
       numberOfCard++; 
      } 
     } 
     topCardIndex = 0; 
    } 

    public Card getCardAt(int position) { 
     if (position >= cards.length - topCardIndex || position < topCardIndex) { 
      throw new IndexOutOfBoundsException("Values are out of bounds"); 
     } else { 
      return cards[topCardIndex + position]; 
     } 
    } 

    public Card[] deal(int numCards) { 
     // FIXME: check bounds, or make method "Card pickCardAt(int position)" 
     // that removes the card from the deck 
     Card[] drawnCards = new Card[numCards]; 
     for(int index = 0; index < numCards; index ++) { 
      drawnCards[index] = cards[topCard]; 
      topCard++; 
     } 
     return drawnCards; 
    } 

난 당신이 만드는 더 나은 것 같아요 갑판의 card 컬렉션은 Card[] 대신 List이므로 remove()과 같은 더 나은 작업을 수행 할 수 있습니다.

당신은 갑판에서 n 첫 번째 카드를 가지고 싶다면

, 당신은 다음 결과 배열에 단순히 remove() N 시간 (I, 너무 목록을 만들 것이다).

public List<Card> deal(int numCards) { 
    List<Card> drawnCards = new ArrayList<Card>(numCards); 
    for(int index = 0; index < numCards; index++) { 
     drawnCards.add(cards.remove(0)); 
    } 
    return drawnCards; 
} 
+0

카드의 카드 수집을 시도해야합니다. [], 사용할 수 없습니다. 명부. Lis – user1817301

+0

@ user1817301을 사용하는 것이 훨씬 쉽다는 것을 알고 있습니다. 그렇다면 카드를 "불변"으로 만들고 데크의 최상위 카드의 색인을 저장하는 것이 좋습니다. 나는 나의 지위를 고치려고 노력할 것이다. – mgarciaisaia

0

이것은 내가 게임에서 카드 덱을 다루는 방법입니다. XML 파일에서 카드를 읽고 푸시하는 read() 메소드도 있습니다.

import java.util.Stack; 

public class CardStack extends Stack<Card> { 

    public CardStack() {} 

    public void shuffle() { 
     List<Card> list = this.subList(0, this.size()); 
     //changes in this list are reflected in original Stack 
     Collections.shuffle(list); 
    } 

    public Card pop() { 
     try { 
      Card card = super.pop(); 
      return card; 
     } catch (EmptyStackException e) { 
      return null; 
     } 
    } 
} 
+0

데크 카드 컬렉션을 카드 []로 만들어야하는데 다른 방법은 사용할 수 없습니다. 나는 이것을 생각하고 있었지만 오류가 발생했다. 공개 카드 [] deal (int numCards) { \t \t int numCards; \t for (int i = 0; i user1817301