Question

I have a player class with two vectors for the cards in the deck and the cards in the players hand. I load the cards from an xml file, I've replaced all that with just loading ints to post here. For some reason, even though each player is a separate object and they each shuffle the deck separately, they both get the same hands. Each time you run it, you obtain different hands but they always have the same hand. I can't figure out why. Code requires C++11.

#include <iostream>
#include <vector>
#include <random>
#include <time.h>

// **Player.hpp**

class Player
{
public:
    Player(std::string name);
    std::string name;
    std::vector<int> hand;
    std::vector<int> deck;

    void draw(int numberOfCards);
    void loadDeck();
    void shuffleDeck();
};

// **Player.cpp**

Player::Player(std::string playerName)
{
    name = playerName;
    loadDeck();
    shuffleDeck();
}

void Player::draw(int numberOfCards)
{
    for(int i = 0; i < numberOfCards; i++)
    {
        if(!deck.empty() && hand.size() < 10)
        {
            hand.push_back(deck.front());
            deck.erase(deck.begin());
        }
    }
}

void Player::loadDeck()
{
    for(int i = 1; i < 30; i++)
    {
        deck.push_back(i);
    }
}

void Player::shuffleDeck()
{
    std::srand(time(0));
    for(int i = 1; i != 15; i++)
    {
        std::srand(static_cast<double>(std::rand()) / RAND_MAX * 4294967295);
        for(int i = 1; i < deck.size(); i++)
        {
            std::swap(deck[i], deck[static_cast<double>(std::rand()) / RAND_MAX * i]);
        }
    }
}

// **Main.cpp**

int main()
{
    Player* player1 = new Player("Player1");
    Player* player2 = new Player("Player2");

    player1->draw(7);
    player2->draw(7);

    std::vector<int>::iterator itr;

    std::cout << player1->name << "'s Hand:\n";
    for(itr = player1->hand.begin(); itr != player1->hand.end(); itr++)
    {
        std::cout << (*itr) << ", ";
    }

    std::cout << "\n\n\n" << player2->name << "'s Hand:\n";
    for(itr = player2->hand.begin(); itr != player2->hand.end(); itr++)
    {
        std::cout << (*itr) << ", ";
    }

    return 0;
}
Was it helpful?

Solution

When you call srand and give it what looks like a constant value you're setting the pseudo-random generator up to give the same "random" values each time through shuffleDeck.

Try seeding in main rather than in shuffleDeck() and using something that changes, like a pid or some aspect of the time so the game doesn't turn out the same each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top