-
Notifications
You must be signed in to change notification settings - Fork 973
Expand file tree
/
Copy pathDeck.cs
More file actions
137 lines (114 loc) · 2.59 KB
/
Deck.cs
File metadata and controls
137 lines (114 loc) · 2.59 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using System;
#if DEBUG
using NUnit.Framework;
#endif
namespace CardGames.GameLogic
{
/// <summary>
/// A Deck of 52 cards from which cards can be drawn.
/// </summary>
public class Deck
{
private readonly Card[] _cards = new Card[52];
private int _topCard;
/// <summary>
/// Creates a new Deck with 52 Cards. The first card
/// will be the top of the Deck.
/// </summary>
public Deck ()
{
int i = 0;
for (Suit s = Suit.CLUB; s <= Suit.SPADE; s++)
{
for (Rank r = Rank.ACE; r <= Rank.KING; r++)
{
Card c = new Card(r, s);
_cards[i] = c;
i++;
}
}
_topCard = 0;
}
/// <summary>
/// Indicates how many Cards remain in the Deck.
/// </summary>
/// <value>The number of cards remaining.</value>
public int CardsRemaining
{
get
{
return 52 - _topCard;
}
}
/// <summary>
/// Returns all of the cards to the Deck, and shuffles their order.
/// All cards are turned so that they are face down.
/// </summary>
public void Shuffle()
{
for(int i = 0; i < 52; i++)
{
if(_cards[i].FaceUp) _cards[i].TurnOver();
}
Random rnd = new Random();
// for each card (no need to shuffle last card)
for(int i = 0; i < 52 - 1; i++)
{
// pick a random index
int rndIdx = rnd.Next(52 - i);
Card temp = _cards[i];
_cards[i] = _cards[i + rndIdx];
_cards[i + rndIdx] = temp;
}
_topCard = 0;
}
/// <summary>
/// Takes a card from the top of the Deck. This will return
/// <c>null</c> when there are no cards remaining in the Deck.
/// </summary>
public Card Draw()
{
if (_topCard < 52)
{
Card result = _cards[_topCard];
_topCard++;
return result;
}
else
{
return null;
}
}
}
#region Deck Unit Tests
#if DEBUG
public class DeckTests
{
[Test]
public void TestDeckCreation()
{
Deck d = new Deck();
Assert.AreEqual(52, d.CardsRemaining);
}
[Test]
public void TestDraw()
{
Deck d = new Deck();
Assert.AreEqual(52, d.CardsRemaining);
Card c = d.Draw();
Assert.AreEqual(51, d.CardsRemaining);
Assert.AreEqual(Rank.ACE, c.Rank);
Assert.AreEqual(Suit.CLUB, c.Suit);
int count = 51;
// Draw all cards from the deck
while ( d.CardsRemaining > 0 )
{
c = d.Draw();
count--;
Assert.AreEqual(count, d.CardsRemaining);
}
}
}
#endif
#endregion
}