0
\$\begingroup\$

I am creating a card matching game. I have a vector that stores 16 unique cards. I am trying to randomize the order and select only the first 12 cards, then setup in a 4x6 grid for a total of 24 matching pairs. I'm having trouble randomizing it and displaying it in the grid. Also, I am using Cocos2d-x 3.2. Thanks for any advice.

std::vector<Sprite*> cards;
std::vector<std::string> cardNames = { "0.png", "1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png", "8.png", "9.png", "10.png", "11.png", "12.png", "13.png", "14.png", "15.png" };

for (int n = 0; n < cardNames.size(); n++)
{
    auto sprite = Sprite::create(cardNames.at(n));

    sprite->setPosition(cocos2d::Point((50 * (n + 1)), 20));
    sprite->setTag(n);

    cards.push_back(sprite);

    addChild(sprite);
}

std::random_shuffle(cards.begin(), cards.end());

for (int n = 0; n <= 11; n++) // select forst 12 cards to display in the grid
{
    // logic to create grid
    // set position of each card

    addChild(cards); // error here
}
\$\endgroup\$
  • \$\begingroup\$ Probably you wrote addChild(cards) as an example? You should use addChild(cards.at(n)) \$\endgroup\$ – Jose M Pan Nov 7 '14 at 13:54
1
\$\begingroup\$

To do random numbers in C++ you need to #include <random> and #include<time.h> then create a seed using:

srand(time(NULL))

Then you must create a random number like so.

int randNum = rand() % 10 + 1;

This will create a random number in the range of 0-9 but then we add 1 and it will be somewhere between 1-10.

Keep in mind it's not the only way to generate a random number.

As for your program just assign all the the cards a number, then create another array of random numbers, and those will be your random positions in the vector. (Don't forget to prevent repeats.)

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.