卡片组JAVA

时间:2013-04-11 06:26:29

标签: java

我已经制作了一副卡片,可以处理每张卡片和一套西装,直到没有剩余卡片为止。对于我的项目,我需要将其拆分为3个类,其中包括一个驱动程序类。我首先用一切创建了一个类,所以我知道如何使它全部工作。

public class DeckOfCards2 {
  public static void main(String[] args) {
    int[] deck = new int[52];
    String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    // Initialize cards
    for (int i = 0; i < deck.length; i++) {
      deck[i] = i;
    }

    // Shuffle the cards
    for (int i = 0; i < deck.length; i++) {
      int index = (int)(Math.random() * deck.length);
      int temp = deck[i];
      deck[i] = deck[index];
      deck[index] = temp;
    }

    // Display the all the cards
    for (int i = 0; i < 52; i++) {
      String suit = suits[deck[i] / 13];
      String rank = ranks[deck[i] % 13];
      System.out.println( rank + " of " + suit);
    }
  }
}

现在尝试将其分成3个类。我在DeckOfCards类的所有deck / suit变量上得到红色sqiggle行。我不知道如何解决它。

public class DeckOfCards {
  private Card theCard;
  private int remainingCards = 52;

  DeckOfCards() {
    theCard = new Card();   
  }

  public void shuffle(){
    for (int i = 0; i < deck.length; i++) {
       int index = (int)(Math.random() deck.length);
       int temp = deck[i];
       deck[i] = deck[index];
       deck[index] = temp;
       remainingCards--;
     }
  }

  public void deal(){
    for (int i = 0; i < 52; i++) {
       String suit = suits[deck[i] / 13];
       String rank = ranks[deck[i] % 13];
       System.out.println( rank + " of " + suit);
       System.out.println("Remaining cards: " + remainingCards);
     }
   }
}

卡类:

public class Card {
  int[] deck = new int[52];
  String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
  String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

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

经销商类

public class Dealer {
  public static void main(String[]args){
    System.out.println("The deck will randomly print out a card from a full deck each time");

    DeckOfCards player = new DeckOfCards();
    player.deal();
  }
}

11 个答案:

答案 0 :(得分:34)

正如其他人已经说过的那样,你的设计不是很清晰,面向对象。

最明显的错误是,在您的设计中,卡片知道卡片组。 Deck应该知道卡片并在其构造函数中实例化对象。例如:

public class DeckOfCards {
    private Card cards[];

    public DeckOfCards() {
        this.cards = new Card[52];
        for (int i = 0; i < ; i++) {
            Card card = new Card(...); //Instantiate a Card
            this.cards[i] = card; //Adding card to the Deck
        }
     }

之后,如果你想要,你也可以扩展Deck以建立不同的Deck of Cards(例如,超过52张牌,Jolly等)。例如:

public class SpecialDeck extends DeckOfCards {
   ....

我要改变的另一件事是使用String数组来表示套装和等级。从Java 1.5开始,该语言支持Enumeration,它非常适合这类问题。例如:

public enum Suits {
    SPADES, 
    HEARTS, 
    DIAMONDS,
    CLUBS;  
}

使用Enum可以获得一些好处,例如:

1)枚举是类型安全的,你不能将除预定义的枚举常量之外的任何东西分配给Enum变量。例如,您可以按如下方式编写Card的构造函数:

public class Card {

   private Suits suit;
   private Ranks rank;

public Card(Suits suit, Ranks rank) {
    this.suit = suit;
    this.rank = rank;
}

这样您就可以构建一致的卡片,只接受枚举值。

2)你可以在Switch语句中使用Enum in int或int原始数据类型(这里我们不得不说,因为在String上也允许使用Java 1.7 switch语句)

3)在Java中使用Enum添加新常量非常简单,您可以在不破坏现有代码的情况下添加新常量。

4)您可以遍历Enum,这在实例化卡片时非常有用。例如:

/* Creating all possible cards... */
for (Suits s : Suits.values()) {
    for (Ranks r : Ranks.values()) {
         Card c = new Card(s,r);
    }  
}

为了不再发明轮子,我还会改变你将卡片从阵列保存到Java Collection的方式,这样你就可以在你的套牌上使用很多强大的方法,但最重要的是你可以使用Java Collection's shuffle function将你的甲板洗牌。例如:

private List<Card> cards = new ArrayList<Card>();

//Building the Deck...

//...

public void shuffle() {
    Collections.shuffle(this.cards); 
}

答案 1 :(得分:3)

这是我的实施:

public class CardsDeck {
    private ArrayList<Card> mCards;
    private ArrayList<Card> mPulledCards;
    private Random mRandom;

public static enum Suit {
    SPADES,
    HEARTS,
    DIAMONDS,
    CLUBS;
}

public static enum Rank {
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT,
    NINE,
    TEN,
    JACK,
    QUEEN,
    KING,
    ACE;
}

public CardsDeck() {
    mRandom = new Random();
    mPulledCards = new ArrayList<Card>();
    mCards = new ArrayList<Card>(Suit.values().length * Rank.values().length);
    reset();
}

public void reset() {
    mPulledCards.clear();
    mCards.clear();
    /* Creating all possible cards... */
    for (Suit s : Suit.values()) {
        for (Rank r : Rank.values()) {
            Card c = new Card(s, r);
            mCards.add(c);
        }
    }
}


public static class Card {

    private Suit mSuit;
    private Rank mRank;

    public Card(Suit suit, Rank rank) {
        this.mSuit = suit;
        this.mRank = rank;
    }

    public Suit getSuit() {
        return mSuit;
    }

    public Rank getRank() {
        return mRank;
    }

    public int getValue() {
        return mRank.ordinal() + 2;
    }

    @Override
    public boolean equals(Object o) {
        return (o != null && o instanceof Card && ((Card) o).mRank == mRank && ((Card) o).mSuit == mSuit);
    }


}

/**
 * get a random card, removing it from the pack
 * @return
 */
public Card pullRandom() {
    if (mCards.isEmpty())
        return null;

    Card res = mCards.remove(randInt(0, mCards.size() - 1));
    if (res != null)
        mPulledCards.add(res);
    return res;
}

/**
 * Get a random cards, leaves it inside the pack 
 * @return
 */
public Card getRandom() {
    if (mCards.isEmpty())
        return null;

    Card res = mCards.get(randInt(0, mCards.size() - 1));
    return res;
}

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public int randInt(int min, int max) {
    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = mRandom.nextInt((max - min) + 1) + min;
    return randomNum;
}


public boolean isEmpty(){
    return mCards.isEmpty();
}
}

答案 2 :(得分:0)

首先,您的课程存在架构问题。您已将属性deck移至班级Card中。但是,它是卡片组的属性,因此必须在班级DeckOfCards内。然后,初始化循环不应该在Card的构造函数中,而应该在您的deck类中。此外,该套牌目前是int的数组,但应该是Card s的数组。

其次,在方法Deal内,您应该将suits称为Card.suits并将此成员设为静态最终版。与ranks相同。

最后,请坚持命名惯例。方法名称始终以小写字母开头,即shuffle而不是Shuffle

答案 3 :(得分:0)

您的设计有问题。尽量让你的课代表现实世界的事物。例如:

  • 班级卡应该代表一张卡,即卡片的性质#34; Card类不需要了解Decks。
  • Deck类应包含52个Card对象(加上jokers?)。

答案 4 :(得分:0)

您的代码中存在许多错误,例如,只需在deck方法中键入Shuffle,您就不会真正调用您的套牌。您只能通过输入theCard.deck

来调用它

我改变了你的随机播放方法:

public void Shuffle(){
    for (int i = 0; i < theCard.deck.length; i++) {
        int index = (int)(Math.random()*theCard.deck.length );
        int temp = theCard.deck[i];
        theCard.deck[i] = theCard.deck[index];
        theCard.deck[index] = temp;
        remainingCards--;
    }
}

另外,据说你有结构问题。你应该按照你在现实生活中理解的方式命名课程,例如,当你说卡片时,它只是一张卡片,当你说它应该是52 + 2卡片时。通过这种方式,您的代码将更容易理解。

答案 5 :(得分:0)

你的程序中有很多错误。

  1. 指数的计算。我认为它应该是Math.random()%deck.length

  2. 在卡的显示中。根据我的说法,你应该制作一类具有等级的牌并制作该类型的数组

  3. 如果你愿意我可以给你完整的结构,但如果你自己做的话会更好

答案 6 :(得分:0)

这是一些代码。它使用2个类(Card.java和Deck.java)来完成这个问题,最重要的是它在你创建deck对象时自动对它进行排序。 :)

import java.util.*;

public class deck2 {
    ArrayList<Card> cards = new ArrayList<Card>();

    String[] values = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
    String[] suit = {"Club", "Spade", "Diamond", "Heart"};

    static boolean firstThread = true;
    public deck2(){
        for (int i = 0; i<suit.length; i++) {
            for(int j=0; j<values.length; j++){
                this.cards.add(new Card(suit[i],values[j]));
            }
        }
        //shuffle the deck when its created
        Collections.shuffle(this.cards);

    }

    public ArrayList<Card> getDeck(){
        return cards;
    }

    public static void main(String[] args){
        deck2 deck = new deck2();

        //print out the deck.
        System.out.println(deck.getDeck());
    }

}


//separate class

public class Card {


    private String suit;
    private String value;


    public Card(String suit, String value){
        this.suit = suit;
        this.value = value;
    }
    public Card(){}
    public String getSuit(){
        return suit;
    }
    public void setSuit(String suit){
        this.suit = suit;
    }
    public String getValue(){
        return value;
    }
    public void setValue(String value){
        this.value = value;
    }

    public String toString(){
        return "\n"+value + " of "+ suit;
    }
}

答案 7 :(得分:0)

我认为解决方案就像这样简单:

Card temp = deck[cardAindex];
deck[cardAIndex]=deck[cardBIndex]; 
deck[cardBIndex]=temp;

答案 8 :(得分:0)

public class shuffleCards{

    public static void main(String[] args) {

        String[] cardsType ={"club","spade","heart","diamond"};
        String [] cardValue = {"Ace","2","3","4","5","6","7","8","9","10","King", "Queen", "Jack" };

        List<String> cards = new ArrayList<String>();
        for(int i=0;i<=(cardsType.length)-1;i++){
            for(int j=0;j<=(cardValue.length)-1;j++){
                cards.add(cardsType[i] + " " + "of" + " " + cardValue[j]) ;
            }
        }

        Collections.shuffle(cards);
        System.out.print("Enter the number of cards within:" + cards.size() + " = ");

        Scanner data = new Scanner(System.in);
        Integer inputString = data.nextInt();
        for(int l=0;l<= inputString -1;l++){
            System.out.print( cards.get(l)) ;
        }    
    }
}

答案 9 :(得分:0)

import java.util.List;
import java.util.ArrayList;
import static java.lang.System.out;
import lombok.Setter;
import lombok.Getter;
import java.awt.Color;


public class Deck {

private static @Getter List<Card> deck = null;

final int SUIT_COUNT = 4;
final int VALUE_COUNT = 13;

public Deck() {
    deck = new ArrayList<>();
    Card card = null;
    int suitIndex = 0, valueIndex = 0;
    while (suitIndex < SUIT_COUNT) {
        while (valueIndex < VALUE_COUNT) {
            card = new Card(Suit.values()[suitIndex], FaceValue.values()[valueIndex]);
            valueIndex++;
            deck.add(card);
        }
        valueIndex = 0;
        suitIndex++;
    }
}

private enum Suit{CLUBS("Clubs", Color.BLACK), DIAMONDS("Diamonds", Color.RED),HEARTS("Hearts", Color.RED), SPADES("Spades", Color.BLACK);

    private @Getter String name = null;
    private @Getter Color color = null;

    Suit(String name) {
        this.name = name;
    }

    Suit(String name, Color color) {
        this.name = name;
        this.color = color;
    }
}

private enum FaceValue{ACE(1), TWO(2), THREE(3),
    FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT (8), NINE(9), TEN(10),
    JACK(11), QUEEN(12), KING(13);

    private @Getter int cardValue = 0;

    FaceValue(int value) {
        this.cardValue = value;
    }
}

private class Card {

    private @Getter @Setter Suit suit = null;

    private @Getter @Setter FaceValue faceValue = null;

    Card(Suit suit, FaceValue value) {
        this.suit = suit;
        this.faceValue = value;
    }

    public String toString() {
        return getSuit() + " " + getFaceValue();
    }

    public String properties() {
        return getSuit().getName() + " " + getFaceValue().getCardValue();
    }

}

public static void main(String...inputs) {
    Deck deck = new Deck();
    List<Card> cards = deck.getDeck();
    cards.stream().filter(card -> card.getSuit().getColor() != Color.RED && card.getFaceValue().getCardValue() > 4).map(card -> card.toString() + " " + card.properties()).forEach(out::println);   
}

}

答案 10 :(得分:0)

生成卡片组的非常简单的代码:

class Card{
        
    private final String suit;
    private final String rank;
    
    
    public Card(String suit, String rank){
        this.suit = suit;
        this.rank = rank;
    }       
    
    @Override
    public String toString() {
        return "Card [suit=" + suit + ", rank=" + rank + "]";
    }
    
}

class DeckOfCard{
    
    private static final String suits[] = {"club", "diamond", "heart", "spade"};
    private static final String ranks[] = {null,"ace", "deuce", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king"};
    private final ArrayList<Card> cards;
    
    public DeckOfCard(){
        cards = new ArrayList<Card>();
        for (int i = 0; i<suits.length; i++) {
            for(int j=0; j<ranks.length; j++){
                this.cards.add(new Card(suits[i],ranks[j]));
            }
        }   
        //Shuffle after the creation
        Collections.shuffle(this.cards);
        
    }

    public ArrayList<Card> getCards() {
        return cards;
    }


}
public class CardPuzzle {

    public static void main(String[] args) {

        DeckOfCard deck = new DeckOfCard();     
        ArrayList<Card> cards = deck.getCards();        
        for(Card card:cards){
            System.out.println(card);
        }
        
    }

}