Jump to content
  • Advertisement
Sign in to follow this  
matthew0786

Generate random from Array - C++

This topic is 4235 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi, im making my first game in C++. Im still a newbie. so far, i have defined these 4 arrays (all representing different suits) char spade[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'}; char diamond[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'}; char club[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'}; char heart[13] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'}; ok, what i want to know is how to generate any 13 random cards from any of the arrays. i tried rand() but it said "incompatible types in assignment of "int" to "char" thanks for your help.

Share this post


Link to post
Share on other sites
Advertisement
you should perhaps define two ints...

#define NUM_SUITS 4
#define NUM_CARDS 13

then have two ints defining the suit and card num

int suit = rand()% NUM_SUITS;
int card = rand()% NUM_CARDS;


however, i don't think your initial approach to this is ideal. For example, how will you store the card data? storing it as a char won't work since theres no difference between an ace of spades and an ace of hearts (both are 'A' in their respective arrays and would be 'A' in the players hand of cards).

I'd suggest maybe a 2d array of ints representing the deck and represent each card in a players hand with a 2 element int array.

Share this post


Link to post
Share on other sites
I believe you should take a step back and revise your code design.
Learning C++ means learning to incorporate the supported ways to solve problems.

Your card game could be solved nicely in an object oriented way.
You have nice (even physical) objects, your game cards. Those have properties, suit and value.

This is how your class for the card could look like:

class Card
{
public:

enum Suit { SPADE = 0, DIAMOND = 1, CLUB = 2, HEART = 3 };
enum Value { A = 1, T = 10, J = 11, Q = 12, K = 13 };

Card( int suit_id, char value )
: mSuit(suit_id),
mValue(value)
{}

char getValue()
{
return mValue;
}

int getSuit()
{
return mSuit;
}

private:
int mSuit;
char mValue;
};

// this function could generate random cards
Card generateRandomCard()
{
int random_suit = rand() % 4; // generates a random number between (including) 0 and 3
char random_value = static_cast<char>(rand() % 13 + 1); // // generates a random number between (including) 1 and 13
return Card(random_suit, random_value); // returns a card object with the random attributes set
}

// this is how you could call it in a console application
int main()
{
srand(GetTickCount()); // seeds the random generator with the current system time since last reboot

Card myCard = generateRandomCard(); // myCard will be a random Card

Card myOtherCard(Card::DIAMOND, Card::K); // this will be a user defined card

return 0;
}







This is just an idea of how it could be structured, you may come up with a better way.
The deck itself could be some container out of the STL, vector or set comes to mind depending on how you would want to work on it.

Share this post


Link to post
Share on other sites

like this?

const int ROWS = 4;
const int COLS = 13;

int val[ROWS][COLS] = {?,?,?,....
?,?,?
?,?,? }; // ? represents cards


ok, since im using int values, i can only input number values, how do i represent picture cards (J,Q,K,A) each picture card is worth (1,2,3,4) points respectively, while normal cards do not have value.

Do i represent the Picture cards as number? in the array?



Quote:
Original post by Winegums
you should perhaps define two ints...

#define NUM_SUITS 4
#define NUM_CARDS 13

then have two ints defining the suit and card num

int suit = rand()% NUM_SUITS;
int card = rand()% NUM_CARDS;


however, i don't think your initial approach to this is ideal. For example, how will you store the card data? storing it as a char won't work since theres no difference between an ace of spades and an ace of hearts (both are 'A' in their respective arrays and would be 'A' in the players hand of cards).

I'd suggest maybe a 2d array of ints representing the deck and represent each card in a players hand with a 2 element int array.


Share this post


Link to post
Share on other sites
Ha I just had to do a project like this for a class. To sum it up you just need 2 arrays, one to store your suits and one to store your numbers. Then you just randomly grab an element from each of the arrays, and there's your card.

Note some of it may seem unnecessary, but it's what the instructor wanted.

Here's the complete code:



#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;

int rand_0toN1(int n);
string draw_a_card();

const string suits[4] = {"hearts", "diamonds", "spades", "clubs"};
const string ranks[13] = {"ace", "two", "three", "four", "five",
"six", "seven", "eight", "nine",
"ten", "jack", "queen", "king" };
int main() {
int n;
string card;

srand(time(0)); // Set seed for random numbers.


cout << "Enter no. of cards to draw (c-d to exit): ";
cin >> n;

while(cin) {
for (int i = 1; i <= n; i++){
card = draw_a_card();
cout << card << endl;
}

cout << "Enter no. of cards to draw (c-d to exit): ";
cin >> n;
}

//exit
cout << endl << "Exiting.." << endl;
return 0;
}

// Draw-a-card function
// Performs one card-draw by getting a random 0-4 and a random
// 0-12. These are then used to index the string arrays, ranks
// and suits.
//
string draw_a_card() {
int r; // Random index (0 thru 12) into ranks array
int s; // Random index (0 thru 3) into suits array

r = rand_0toN1(13);
s = rand_0toN1(4);
return (ranks[r] + " of " + suits[s]);
}

// Random 0-to-N1 Function.
// Generate a random integer from 0 to N-1.
//
int rand_0toN1(int n) {
return rand() % n;
}


Share this post


Link to post
Share on other sites
thats a good example, Shakedown. Thanks

instead of asking the user to enter how many cards (cin >> n),
i put

n = 13;

so that a random selection of 13 cards will be given.

just a question, how do i assign values to "Ace", "Jack", "Queen", "King" giving them (1,2,3,4) respectively in the array?.
I want to assign them points so that after the cards have been generated for the player, the total jacks, queens, kings, aces are totaled.

ive tried rank[1] = 4; and so forth. Any help would be much appreciated



Quote:
Original post by Shakedown
Ha I just had to do a project like this for a class. To sum it up you just need 2 arrays, one to store your suits and one to store your numbers. Then you just randomly grab an element from each of the arrays, and there's your card.

Note some of it may seem unnecessary, but it's what the instructor wanted.

Here's the complete code:

*** Source Snippet Removed ***

Share this post


Link to post
Share on other sites
Off the top of my head, I would do something like the following (but there are probably better ways to do it):


enum SUIT
{
SPADES,
etc.
};

enum VALUE
{
ACE = 1,
TWO,
etc.
};

typedef std::pair<SUIT, VALUE> card;

typedef std::vector<card> deck;
typedef std::vector<card> hand;

int main()
{
deck MyDeck;

//fill deck with cards...(not shown)

//shuffle deck randomly
std::random_shuffle(MyDeck.begin(), MyDeck.end());

int numCards;
std::cin>>numCards;

assert(numCards <= MyDeck.size());

//create a hand out of the first numCards in the deck
hand MyHand(MyDeck.begin(), MyDeck.begin() + numCards);
}



Share this post


Link to post
Share on other sites
Quote:
Original post by matthew0786
thats a good example, Shakedown. Thanks

instead of asking the user to enter how many cards (cin >> n),
i put

n = 13;

so that a random selection of 13 cards will be given.

just a question, how do i assign values to "Ace", "Jack", "Queen", "King" giving them (1,2,3,4) respectively in the array?.
I want to assign them points so that after the cards have been generated for the player, the total jacks, queens, kings, aces are totaled.

ive tried rank[1] = 4; and so forth. Any help would be much appreciated



Quote:
Original post by Shakedown
Ha I just had to do a project like this for a class. To sum it up you just need 2 arrays, one to store your suits and one to store your numbers. Then you just randomly grab an element from each of the arrays, and there's your card.

Note some of it may seem unnecessary, but it's what the instructor wanted.

Here's the complete code:

*** Source Snippet Removed ***


Well if you want JUST the rank of the card (ace, two, three...jack, queen, king) then you could create a new array

int newarray[13] = { 0 }

Now this array can represent the amount of times a particular rank was generated. Each element ( newarray[0] represents Aces, newarray[1] represents Two's, etc. ) will represent a particular rank. Now when you make the call

r = rand_0toN1(13);
newarray[r] += 1; // Add this


So you call the function draw_a_card(), it randomly generates an int r between 0 and 12, and then it takes that number, say it was 4, and then goes to element 4 of the newarray[4] and increments the number there to 1 ( hence += 1 ). Now you can later use a for loop to go through each element of the newarray[] and display the int that is there. Say you got 4 three times during your 13 generated cards, that would make newarray[4] = 3, and 4 represents your Five's cards ( since newarray[0] is Aces, newarray[1] is Two's, newarray[2] is Three's, newarray[3] is Four's, newarray[4] is Five's, etc... )

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!