Alessandro Pezzotta
Alessandro Pezzotta

Reputation: 43

Pick random Card from a "strange" Deck (Java)

I'm trying to implement a new card game in Java(didn't invent it, just have to), where the deck is kind of different from the traditional ones. Deck is made of 90 cards, divided this way: 13 orange cards, 13 white cards, 13 black cards, 13 blue cards, 13 grey cards, 13 purple cards and 12 jolly. All these cards are named "Political Cards".

I would like to represent the deck as an Array of 7 elements:

public class PoliticalDeck {
    private PoliticalCard[] deck; 

    public PoliticalDeck() {
        deck = new PoliticalCard[7]; 
    }

    //estrai una carta a caso
    public void pickRandomCard() {

    }
}

Could this be correct? How could I implement the card picking method?

Upvotes: 0

Views: 493

Answers (1)

David Conrad
David Conrad

Reputation: 16369

Put the cards in a List or a Deque (a double-ended queue), shuffle them with the Fisher-Yates shuffle, and deal them by removing them from the collection:

public enum Suit {
    ORANGE, WHITE, BLACK, BLUE, GREY, PURPLE, JOLLY;
}

Cards:

public class Card {
    private final Suit suit;
    private final int value;

    public Card(Suit suit, int value) {
        this.suit = suit;
        this.value = value;
    }

    public Suit getSuit() { return suit; }
    public int getValue() { return value; }
    @Override public String toString() { return value + " of " + suit; }
}

Deck:

import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;

public class Deck {
    private Deque<Card> deck;

    public Deck() {
        LinkedList<Card> cards = new LinkedList<>();
        for (Suit suit : Suit.values()) {
            int limit = suit == Suit.JOLLY? 12 : 13;
            for (int value = 1; value <= limit; ++value) {
                cards.add(new Card(suit, value));
            }
        }
        Collections.shuffle(cards);
        deck = cards;
    }

    public boolean isEmpty() { return deck.isEmpty(); }
    public int remaining() { return deck.size(); }
    public Card deal() { return deck.remove(); }
}

This leaves out a number of features you might want for your game, such as dealing a hand of n cards at a time instead of dealing them one-by-one, reshuffling the deck (to shuffle with this, just create a new deck), the concept of a "discard" pile (don't know if your game has that), and decent equals and hashCode methods on Card. You may also want to have Card implement Comparable<Card>. Those are left as an exercise for the reader.

Upvotes: 1

Related Questions