Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning deck of cards based on user input for player and cards per player in java

Tags:

java

I have the deck of card shuffling and returning results but now i want to alter the output based on the user input: Number of players and the number of cards per player.

Original code:

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

}

Deck Class

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

}

Card Class

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;
}
}

Output Deck of cards: 54
Number of players: 4 (entered by user)
Number of cards per user: 5 (entered by user)
Player 1: Ace of Spades, 2 of Hearts, Red Joker
Player 2: 8 of Hearts, 10 of Clubs, 9 of Hearts
Player 1 has the better hand.

like image 995
Masriyah Avatar asked Nov 13 '22 09:11

Masriyah


1 Answers

As I see, you let every player draw cards cards from the deck:

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
}

Yep, I think that should do it and it still is perfectly clean and modular.

like image 120
poitroae Avatar answered Nov 15 '22 06:11

poitroae