-
Notifications
You must be signed in to change notification settings - Fork 2
/
Deck.cs
67 lines (58 loc) · 1.19 KB
/
Deck.cs
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
// Deck.cs
/*
* This class represents a deck of cards, shuffled and then drawn
* without replacement.
*
*/
using System;
using System.IO;
namespace Rails
{
public class Deck
{
int count;
Random rand;
int[] cards;
int remaining;
public Deck(int count)
{
this.count = count;
rand = new Random();
cards = new int[count];
// remaining = 0; // already done by the runtime
}
public void Shuffle()
{
for (int i=0; i<count; i++)
cards[i] = i;
remaining = count;
}
public int Draw()
{
if (remaining <= 0)
Shuffle();
int i = rand.Next(remaining);
int temp = cards[i];
cards[i] = cards[--remaining];
return temp;
}
public void Save(BinaryWriter writer)
{
writer.Write((int) 0); // version
writer.Write(count);
writer.Write(remaining);
for (int i=0; i<remaining; i++)
writer.Write(cards[i]);
}
public Deck(BinaryReader reader)
{
reader.ReadInt32(); // version
count = reader.ReadInt32();
cards = new int[count];
remaining = reader.ReadInt32();
for (int i=0; i<remaining; i++)
cards[i] = reader.ReadInt32();
rand = new Random();
}
}
}