C includes a random number generation function called rand() which returns a random number from 0 to (MAXINT - 1). For example:
To have different number sequences each time you run your program, you need to use a function called srand:
To use these functions, you must include the libraries:
The file name parameter to the open function is just a character
array (string). You may use a variable rather than a literal
string. For example:
How can I represent a deck of cards?
There are several ways to represent a deck of cards. The first issue is how to represent the value of 1 card. Assume you have the following declarations (can be global, should not be part of a class):
So how would you represent an individual card? Although you might use a 2D array for this purpose (related to the two dimensions of suit and face), you can also use a single value in the range of 0-51. The algorithm to convert from a card's numeric value to the card representation is:
A deck of cards would be just an array of 52 of these card
values. For example:
Index Card
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
....
would be a deck of cards that are sorted.
To shuffle, take each card in order and randomly swap it with one
other card in the deck (see rand() function above). The
result would be something like:
Index Card
0 14
1 23
2 8
3 45
4 21
5 0
6 37
7 32
8 10
9 41
10 51
...
In this example, the top card in the deck is now the Jack of Hearts.
To deal, you need an integer that keeps track of the next card to be dealt, and arrays of integers that represent the players' hands. For example, to deal two cards to two players from the above shuffled deck, you would have
Player1 Player2
14 23
8
45
You may want to put the hands in a 2D array, so that each player can be represented by a player number.
Additional information will be added to this document as questions
arise.