Hello i am trying to create a game of Video Poker. This is part of what I have so far (I did not include enums, imports, variables, toStrings, etc. in order to save space):
My Card class defines our cards:
public Card(Value value, Suit suit) {
this.value = value;
this.suit = suit;
}
My Deck class creates a 52 card deck and returns a 5 card hand in the draw()
method:
private ArrayList<Card> deck = new ArrayList<Card>();
private ArrayList<Card> hand = new ArrayList<Card>();
private final int HANDSIZE = 5;
public Deck() {
for(Suit suit : Suit.values()) {
for(Value value : Value.values()){
Card card = new Card(value, suit);
deck.add(card);
}
}
}
public ArrayList<Card> draw() {
Random rng = new Random();
for(int i = 0; i < HANDSIZE; i++){
int getCard = rng.nextInt(deck.size());
Card addCard = deck.get(getCard);
hand.add(addCard);
deck.remove(getCard);
}
return hand;
}
My Player class lets gives information on our players.
public class Player extends Deck {
private String name;
private int chips;
public Player(String name, int chips) {
this.name = name;
this.chips = chips;
}
The problem is that every player uses their own deck, therefore sometimes two or more different players may have the same card. My question is how do I set up my program to have each player use the same deck? Thanks.
Example of an output:
Name: John Doe, Cash: 500 [Jack of Hearts, Ten of Hearts, Two of Diamonds, Ace of Clubs, Nine of Diamonds]
Name: Jane Doe, Cash: 500 [King of Spades, Two of Diamonds, Jack of Hearts, Ace of Spades, Seven of Diamonds]
You could use a singleton pattern if there is no other convenient place to hold your Deck:
private ArrayList<Card> deck = new ArrayList<Card>();
private final int HANDSIZE = 5;
private static Deck deck = new Deck();
public static Deck getInstance() {
return deck;
}
// Private Constructor
private Deck() {
for(Suit suit : Suit.values()) {
for(Value value : Value.values()){
Card card = new Card(value, suit);
deck.add(card);
}
}
}
public ArrayList<Card> draw() {
Random rng = new Random();
ArrayList<Card> hand = new ArrayList<Card>();
for(int i = 0; i < HANDSIZE; i++){
int getCard = rng.nextInt(deck.size());
Card addCard = deck.get(getCard);
hand.add(addCard);
deck.remove(getCard);
}
return hand;
}
}
And Player draws from the deck:
public class Player {
private String name;
private int chips;
public Player(String name, int chips) {
this.name = name;
this.chips = chips;
}
public ArrayList<Card> draw() {
Deck.getInstance().draw()
}