我有卡片洗牌并返回结果,但现在我想根据用户输入改变输出:玩家数量和每位玩家的牌数。
原始代码:
CardRun - main
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:黑桃王牌,2个红心小丑,红色小丑
球员2:8个心脏,10个俱乐部,9个心脏
玩家1拥有更好的牌局。
答案 0 :(得分: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
}
是的,我认为应该这样做,它仍然完全清洁和模块化。