Make a Deck of Cards:
To create an array, the C++ code is something like the following:
string cards[52];
cards[0] = "ace of spades";
cards[1] = "deuce of spades";
cards[2] = "trey of spades";
// etc. note that arrays are zero-based. The index starts at zero.
Once we have created the deck, we can shuffle it by creating a function which we will put up at the top of our code BETWEEN the "myrandom" function and the "main" function:
To create an array, the C++ code is something like the following:
- int numbers[100]; //make an array with room for a hundred integers
- string cards[52]; //make an array with room for 52 strings
- float rate[20] = {5.25}; //make an array with twenty floats all initialized to 5.24
string cards[52];
cards[0] = "ace of spades";
cards[1] = "deuce of spades";
cards[2] = "trey of spades";
// etc. note that arrays are zero-based. The index starts at zero.
Once we have created the deck, we can shuffle it by creating a function which we will put up at the top of our code BETWEEN the "myrandom" function and the "main" function:
void shuffle(std::string deckOfCards[]) {
int position = 0;
string card = "";
//we are going to swap a pair of cards 52 times
for (int ii=0 ; ii < 52 ; ++ii) {
//swap two cards in the array
position = myrandom(0,51);
card = deckOfCards[ii];
deckOfCards[ii] = deckOfCards[position];
deckOfCards[position] = card;
}
}
If you want to draw two random cards, then this code could do it.
Notice the counter variable keeps track of where you are in the deck. If
counter gets all the way to 51, you would probably want to call the
shuffle function again and reset the counter variable back to zero:srand(time(0)); string cards[52]; //define our deck of cards as above shuffle(cards); counter = 0; cout << cards[counter] << endl; counter += 1; cout << cards[counter] << endl;
0 comments:
Post a Comment