5

我有洗牌和返回结果的一副牌,但现在我想根据用户输入更改输出:玩家数量和每位玩家的卡片数量。

原始代码:

CardRun - 主要

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    Deck deck = new Deck();
    Card C;

    System.out.println(deck.getTotalCards());
    System.out.print("Number of players: ");
    int players = scan.nextInt();
    System.out.print("Number of cards: ");
    int cards = scan.nextInt();

    while(deck.getTotalCards() != players)
    {
        C = deck.drawFromDeck();
        System.out.println(C.toString());
    }

}

甲板等级

public class Deck {
private ArrayList<Card>cards;

Deck()
{
    cards = new ArrayList<Card>();
    for(int a=0; a<=3; a++)
    {
        for(int b=0; b<=12; b++)
        {
            cards.add(drawFromDeck());
        }
        cards.addAll(cards);
    }
}

public Card drawFromDeck()
{
    Random generator = new Random();
    int index = generator.nextInt(cards.size());
    return cards.remove(index);
}

public int getTotalCards()
{
    return cards.size();
}

}

卡类

public class Card {
private int card, suit;
private static String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
private static String[] cards = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

Card(int suit, int card)
{
    this.card = card;
    this.suit = suit;
}

public @Override String toString()
{
    for(int i = 0; i<players; ++i)
    {
        System.out.println("Player " + (i+1) + ": "+ cards.get(i));
    }
}

public int getCard()
{
    return card;
}

public int getSuit()
{
    return suit;
}
}

输出 牌组:54
玩家数量:4(由用户输入)
每个用户的卡片数量:5(由用户输入)
玩家 1:黑桃 A、红心 2、红色小丑
玩家 2:红心 8、10 Clubs, 9 of Hearts
Player 1 有更好的牌。

4

1 回答 1

1

如我所见,您让每个玩家cards从牌组中抽牌:

List<Hand> hands = new ArrayList<Hand>(players); // defines each players hand (in your case one, each "cards" cards);

// let 'em draw
for(int k=0; k<players; ++k) {
    Hand currentHand = new Hand();
    for(int i=0; i<cards; ++i) {
       currentHand.add(deck.drawFromDeck());
    }
    hands.add(currentHand);
}

// find the best
Collections.sort(hands); // make sure to implement Comparable, to reasonably check which one has the best hand

for(int i=0; i<players; ++i) {
    System.out.println("Player " + (i+1) + ": " + hands.get(i)); // Make sure Hand::toString() is overriden properly
}

是的,我认为应该这样做,它仍然非常干净和模块化

于 2013-03-10T18:34:55.733 回答