// Banner: Deck class for managing a standard 52-card deck.
public class Deck {
private Card[] cards;
private int top; // Tracks the top of the deck
public Deck() {
cards = new Card[52];
int index = 0;
for (int suit = 1; suit <= 4; suit++) {
for (int rank = 1; rank <= 13; rank++) {
cards[index++] = new Card(suit, rank);
}
}
top = 0;
}
public void shuffle() {
List<Card> cardList = Arrays.asList(cards);
Collections.shuffle(cardList);
cards = cardList.toArray(new Card[0]);
}
public Card deal() {
if (top < cards.length) {
return cards[top++];
}
throw new IllegalStateException("No cards left in the deck!");
}
public void resetDeck() {
top = 0;
shuffle();
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter