forked from prmr/DesignBook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeck.java
More file actions
95 lines (86 loc) · 1.96 KB
/
Copy pathDeck.java
File metadata and controls
95 lines (86 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*******************************************************************************
* Companion code for the book "Introduction to Software Design with Java"
* by Martin P. Robillard.
*
* Copyright (C) 2019 by Martin P. Robillard
*
* This code is licensed under a Creative Commons
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
*
* See http://creativecommons.org/licenses/by-nc-nd/4.0/
*******************************************************************************/
package chapter9;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
/**
* Models a deck of 52 cards.
*/
public class Deck
{
private CardStack aCards;
/**
* @return A new List that contains all the cards in this deck.
*/
public List<Card> getCards()
{
ArrayList<Card> result = new ArrayList<>();
for(Card card : aCards )
{
result.add(card);
}
return result;
}
public Stream<Card> stream()
{
return aCards.stream();
}
/**
* @return The card at the top of the deck.
*/
public Card peek()
{
return aCards.peek();
}
/**
* Creates a new deck of 52 cards, shuffled.
*/
public Deck()
{
shuffle();
}
/**
* Reinitializes the deck with all 52 cards, and shuffles them.
*/
public void shuffle()
{
List<Card> cards = new ArrayList<>();
for( Suit suit : Suit.values() )
{
for( Rank rank : Rank.values() )
{
cards.add( Card.get( rank, suit ));
}
}
Collections.shuffle(cards);
aCards = new CardStack(cards);
}
/**
* Draws a card from the deck and removes the card from the deck.
* @return The card drawn.
* @pre !isEmpty()
*/
public Card draw()
{
assert !isEmpty();
return aCards.pop();
}
/**
* @return True iff there are no cards in the deck.
*/
public boolean isEmpty()
{
return aCards.isEmpty();
}
}