コード例 #1
0
ファイル: DrunkenWalk.cpp プロジェクト: pcgben/pcg_basics
void generateWalk(int width){

    std::random_device randomDevice;
    std::mt19937 mt(randomDevice());

    int Xwalk = 1;
    int Ywalk = MAPSIZE / 2;

    Map[Xwalk][Ywalk] = '~';

    std::uniform_int_distribution<int> walkRoll(1, 100);

    do{
        int walkDirection = walkRoll(mt);
        if(walkDirection < 10){
            Xwalk--; // west
        }
        else if(walkDirection < 40){
            Ywalk--; // south
        }
        else if(walkDirection < 70){
            Ywalk++; // north
        }
        else{
            Xwalk++; // east
        }
        if(Xwalk > 0 && Ywalk < MAPSIZE - 2 && Ywalk > 1){
            for(int i = 0; i < width; ++i){
                Map[Xwalk][Ywalk + i] = '~';
                Map[Xwalk][Ywalk - i] = '~';
            }
        }
    }
    while(Xwalk < MAPSIZE - 2);
}
コード例 #2
0
void SoaringLayer::enter()
{
//    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point visibleOrigin = Director::getInstance()->getVisibleOrigin();
    
    // random obstacle
    auto action1 = DelayTime::create(OBSTACLE_GENERATE_TIME);
    auto action2 = CallFunc::create([this](){
        
        std::random_device randomDevice;
        std::mt19937 generator(randomDevice());
        int count = static_cast<int>(Obstacle::Type::COUNT);
        std::uniform_int_distribution<> distibution(0, count - 1);
        Obstacle::Type type = static_cast<Obstacle::Type>(distibution(generator));
        Obstacle *obstacle = Obstacle::create(type);
        this->addChild(obstacle);
    });
    auto action3 = Sequence::create(action1, action2, nullptr);
    auto action4 = RepeatForever::create(action3);
    this->runAction(action4);
    
    // fly plant setttings
    _flyPlant->refreshStatus();
    
    // physics
    _contactListener = EventListenerPhysicsContact::create();
    _contactListener->onContactBegin = CC_CALLBACK_1(SoaringLayer::onContactBegin, this);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_contactListener, this);
    
    // touch
    _touchListener = EventListenerTouchOneByOne::create();
    _touchListener->setSwallowTouches(true);
    _touchListener->onTouchBegan = CC_CALLBACK_2(SoaringLayer::onTouchBegan, this);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_touchListener, this);
}
コード例 #3
0
void Key::spawn(World& world, PointLight * p)
{
    std::random_device randomDevice;
    std::mt19937 gen(randomDevice());
    std::uniform_int_distribution<> random(0, keySpawnPoints.size() - 1);

    spawnID = random(gen);
    point = p;
    taken = false;

    auto mat = glm::mat4(1.0);
    mat = glm::translate(mat, keySpawnPoints[spawnID]);
    mat = glm::rotate(mat, -90.0f, glm::vec3(1.0f, 0.0f, 0.0f));

    point->setPosition(keySpawnPoints[spawnID]);

    world.onHit(keyModel->createbox(mat), [&](Camera * c, SolidBox * b) {
        if (point != nullptr) {
            pickup.reset();
            pickup.play();
            point->turnOff();
            taken = true;
        }
    });
}
コード例 #4
0
ファイル: knmusicnowplaying.cpp プロジェクト: guoyu07/Mu
KNMusicNowPlaying::KNMusicNowPlaying(QObject *parent) :
    KNMusicNowPlayingBase(parent),
    m_backend(nullptr),
    m_playingProxyModel(nullptr),
    m_shadowPlayingModel(new KNMusicProxyModel(this)),
    m_temporaryProxyPlaylist(new KNMusicProxyModel(this)),
    m_temporaryPlaylist(new KNMusicTemporaryPlaylistModel(this)),
    m_playingTab(nullptr),
    m_loopState(NoRepeat),
    m_playingIndex(QPersistentModelIndex()),
    m_playingAnalysisItem(KNMusicAnalysisItem()),
    m_manualPlayed(false)
{
    //Set the temporary playlist to the proxy model.
    m_temporaryProxyPlaylist->setSourceModel(m_temporaryPlaylist);
    //Initial the random device and random generator.
    QVector<int> seedData;
    //Generate the random device.
    std::random_device randomDevice;
    //Get the seed array size.
    const int seedCount=(int)std::mt19937::state_size;
    //Resize the seed data.
    seedData.resize(seedCount);
    //Set the data to the seed data.
    for(int i=0; i<seedCount; ++i)
    {
        //Replace the seed data.
        seedData.replace(i, randomDevice());
    }
    //Transform list to seed sequence.
    std::seed_seq seedSequence(std::begin(seedData), std::end(seedData));
    //Initial the Mersenne twister seeds.
    m_mersenneSeed=std::mt19937(seedSequence);
}
コード例 #5
0
ファイル: OctreeQuery.cpp プロジェクト: AndrewMeadows/hifi
OctreeQuery::OctreeQuery(bool randomizeConnectionID) {
    if (randomizeConnectionID) {
        // randomize our initial octree query connection ID using random_device
        // the connection ID is 16 bits so we take a generated 32 bit value from random device and chop off the top
        std::random_device randomDevice;
        _connectionID = randomDevice();
    }
}
コード例 #6
0
void MultiJittered::generate_samples(void)
{
    std::random_device randomDevice;
    std::mt19937 generator(randomDevice());
    std::uniform_real_distribution<float> distribution(0, 1);

    // num_samples needs to be a perfect square
    int n = (int) sqrt((float) numSamples);
    float subcell_width = 1.0f / ((float) numSamples);

    // fill the samples array with dummy points to allow us to use the [ ] notation when we set the
    // initial patterns
    glm::vec2 fill_point;
    for (int j = 0; j < numSamples * numSets; j++)
        samples.push_back(fill_point);

    // distribute points in the initial patterns
    for (int p = 0; p < numSets; p++)
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                samples[i * n + j + p * numSamples].x =
                        (i * n + j) * subcell_width +
                        multiJitteredRandomFloat(distribution(generator), 0, subcell_width);
                samples[i * n + j + p * numSamples].y =
                        (j * n + i) * subcell_width +
                        multiJitteredRandomFloat(distribution(generator), 0, subcell_width);
            }
        }
    }
    // shuffle x coordinates
    for (int p = 0; p < numSets; p++)
    {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                int k = multiJitteredRandomInt(distribution(generator), j, n - 1);
                float t = samples[i * n + j + p * numSamples].x;
                samples[i * n + j + p * numSamples].x = samples[i * n + k + p * numSamples].x;
                samples[i * n + k + p * numSamples].x = t;
            }
    }

	// shuffle y coordinates
	for (int p = 0; p < numSets; p++)
    {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            {
                int k = multiJitteredRandomInt(distribution(generator), j, n - 1);
                float t = samples[j * n + i + p * numSamples].y;
                samples[j * n + i + p * numSamples].y = samples[k * n + i + p * numSamples].y;
                samples[k * n + i + p * numSamples].y = t;
            }
    }
}
コード例 #7
0
std::vector<CPoint> generatePoints(size_t pointsAmount, CPoint centerPoint, double deviation)
{
    std::random_device randomDevice;
    std::mt19937 generator(randomDevice());
    std::normal_distribution<> x(centerPoint.x, deviation);
    std::normal_distribution<> y(centerPoint.y, deviation);
    std::vector<CPoint> points;
    for (size_t i = 0; i < pointsAmount; ++i)
    {
        points.push_back(CPoint(x(generator), y(generator)));
    }
    return points;
}
コード例 #8
0
AudioMixerClientData::AudioMixerClientData(const QUuid& nodeID, Node::LocalID nodeLocalID) :
    NodeData(nodeID, nodeLocalID),
    audioLimiter(AudioConstants::SAMPLE_RATE, AudioConstants::STEREO),
    _outgoingMixedAudioSequenceNumber(0),
    _downstreamAudioStreamStats()
{
    // of the ~94 blocks in a second of audio sent from the AudioMixer, pick a random one to send out a stats packet on
    // this ensures we send out stats to this client around every second
    // but do not send all of the stats packets out at the same time
    std::random_device randomDevice;
    std::mt19937 numberGenerator { randomDevice() };
    std::uniform_int_distribution<> distribution { 1, (int) ceil(1.0f / AudioConstants::NETWORK_FRAME_SECS) };

    _frameToSendStats = distribution(numberGenerator);
}
コード例 #9
0
ファイル: Jittered.cpp プロジェクト: lejonmcgowan/RayTracer
void Jittered::generate_samples(void)
{
    std::random_device randomDevice;
    std::mt19937 generator(randomDevice());
    std::uniform_real_distribution<float> distribution(0,1);

	int n = (int) sqrt((float)numSamples);
	
	for (int p = 0; p < numSets; p++)
    {
		for (int j = 0; j < n; j++)		
			for (int k = 0; k < n; k++)
				samples.push_back(glm::vec2((k + distribution(generator)) / n, (j + distribution(generator)) / n));
    }
}
コード例 #10
0
ファイル: OctreeQuery.cpp プロジェクト: ZappoMan/hifi
OctreeQuery::OctreeQuery(bool randomizeConnectionID) :
    _cameraFov(DEFAULT_FOV),
    _cameraAspectRatio(DEFAULT_ASPECT_RATIO),
    _cameraNearClip(DEFAULT_NEAR_CLIP),
    _cameraFarClip(DEFAULT_FAR_CLIP),
    _cameraCenterRadius(DEFAULT_FAR_CLIP)
{
    _maxQueryPPS = DEFAULT_MAX_OCTREE_PPS;

    if (randomizeConnectionID) {
        // randomize our initial octree query connection ID using random_device
        // the connection ID is 16 bits so we take a generated 32 bit value from random device and chop off the top
        std::random_device randomDevice;
        _connectionID = randomDevice();
    }
}
コード例 #11
0
ファイル: trainer.cpp プロジェクト: maxoodf/word2vec
    void trainer_t::operator()(std::vector<float> &_trainMatrix) noexcept {
        // input matrix initialized with small random values
        std::random_device randomDevice;
        std::mt19937_64 randomGenerator(randomDevice());
        std::uniform_real_distribution<float> rndMatrixInitializer(-0.005f, 0.005f);
        _trainMatrix.resize(m_matrixSize);
        std::generate(_trainMatrix.begin(), _trainMatrix.end(), [&]() {
            return rndMatrixInitializer(randomGenerator);
        });

        for (auto &i:m_threads) {
            i->launch(_trainMatrix);
        }

        for (auto &i:m_threads) {
            i->join();
        }
    }
コード例 #12
0
void Test::uniqueRandomFill(std::vector<int>& vec, std::size_t amount)
{
	std::random_device randomDevice;	
	std::default_random_engine generator(randomDevice());
	std::uniform_int_distribution<int> distribution(0,INT_MAX);
	int rand = 0;
	std::size_t numAdded = 0;

	while(numAdded < amount)
	{
		rand = distribution(generator);
		if( std::find(vec.begin(), vec.end(), rand) == vec.end() )
		{
			vec.push_back(rand);
			numAdded++;
		}
	}
}
コード例 #13
0
ファイル: main.cpp プロジェクト: HariSeldon/coarsening_pass
//-----------------------------------------------------------------------------
void hostMemoryAlloc() {
  int bufferSize = std::accumulate(globalWorkSize.begin(), globalWorkSize.end(),
                                   1, std::multiplies<int>());

  std::random_device randomDevice;
  std::mt19937_64 gen(randomDevice());
  std::uniform_real_distribution<float> distribution;

  aHost.assign(bufferSize, 0.f);
  bHost.assign(bufferSize, 0.f);
  std::generate_n(aHost.begin(), bufferSize, [&] {
    return (distribution(gen));
  });
  std::generate_n(bHost.begin(), bufferSize, [&] {
    return (distribution(gen));
  });
  outputHost.assign(bufferSize, 0.f);
  width = new cl_int(globalWorkSize[0]);
  height = new cl_int(globalWorkSize[1]);
}
コード例 #14
0
ファイル: oauth.cpp プロジェクト: kmurp/SocialService
//--------------------------------------------------------------------------------------------------
static std::string GenerateNonce
(
    const std::string& timestamp  ///< [IN]
)
//--------------------------------------------------------------------------------------------------
{
    static const char alphNum[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    std::string result = timestamp;

    std::random_device randomDevice;
    std::mt19937 gen(randomDevice());
    std::uniform_int_distribution<> dis(0, sizeof(alphNum) - 1);

    for (int i = 0; i < 8; i++)
    {
        result.append(1, alphNum[dis(gen)]);
    }

    return result;
}
コード例 #15
0
ファイル: RoboCrypt.cpp プロジェクト: paralect/robomongo
    void RoboCrypt::initKey() 
    {
        using MongoSeverity = mongo::logger::LogSeverity;
        auto addToRoboCryptLogs = [](std::string msg, MongoSeverity severity) {
            _roboCryptLogs.push_back({ msg, severity });
        };

        const auto KEY_FILE = QString("%1/.3T/robo-3t/robo3t.key").arg(QDir::homePath()).toStdString();
        QString fileContent;
        QFileInfo const fileInfo{ QString::fromStdString(KEY_FILE) };
        if (fileInfo.exists() && fileInfo.isFile()) {   // a) Read existing key from file
            QFile keyFile{ QString::fromStdString(KEY_FILE) };
            if (!keyFile.open(QIODevice::ReadOnly))
                addToRoboCryptLogs("RoboCrypt: Failed to open key file: " + KEY_FILE, MongoSeverity::Error());

            QTextStream in{ &keyFile };
            fileContent = in.readAll();
            if(fileContent.isEmpty())
                addToRoboCryptLogs("RoboCrypt: Key file is empty: " + KEY_FILE, MongoSeverity::Error());

            _KEY = fileContent.toLongLong();
        }
        else {  // b) Generate a new key and save it into file
            addToRoboCryptLogs("RoboCrypt: No key found, generating a new key and saving it into file", 
                                MongoSeverity::Warning());
            // Generate a new key
            std::random_device randomDevice;
            std::mt19937_64 engine{ randomDevice() };
            std::uniform_int_distribution<long long int> dist{ std::llround(std::pow(2,61)), 
                                                               std::llround(std::pow(2,62)) };
            _KEY = dist(engine);
            // Save the key into file
            QFile file{ QString::fromStdString(KEY_FILE) };
            if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
                addToRoboCryptLogs("RoboCrypt: Failed to save the key into file: " + KEY_FILE, MongoSeverity::Error());
                            
            QTextStream out(&file);
            out << QString::number(_KEY);
        }
    }
コード例 #16
0
int main(int argc, char **argv) {
  std::random_device randomDevice; // used for seeding
  std::default_random_engine generator(randomDevice());
  std::uniform_int_distribution<unsigned> distribution(0,RandomSpread);

  swift::SuccessorMap<unsigned, unsigned> map;
  std::map<unsigned, unsigned> stdMap;

  if (argc < 0) map.dump(); // force this to be used

  auto next = [&] { return distribution(generator); };
  auto nextUnmappedKey = [&] {
    unsigned key;
    do {
      key = next();
    } while (stdMap.find(key) != stdMap.end());
    return key;
  };

  while (true) {
    auto operation = next();

    // Find.
    if (operation >= .7 * RandomSpread) {
      unsigned key = nextUnmappedKey();
      auto iter = stdMap.upper_bound(key);
      auto stdResult = (iter == stdMap.end() ? nullptr : &iter->second);

      llvm::outs() << "  EXPECT_EQ(";
      if (stdResult) {
        llvm::outs() << *stdResult << ", *";
      } else {
        llvm::outs() << "InvalidValue, ";
      }
      llvm::outs() << "map.findLeastUpperBound(" << key << "));\n";

      auto result = map.findLeastUpperBound(key);
      if (result && stdResult && *result != *stdResult) {
        llvm::outs() << "FAILURE: found " << *result
                     << ", but should have found " << *stdResult << "\n";
        abort();
      } else if (!result && stdResult) {
        llvm::outs() << "FAILURE: found nothing, but should have found "
                     << *stdResult << "\n";
        abort();
      } else if (result && !stdResult) {
        llvm::outs() << "FAILURE: found " << *result
                     << ", but should have found nothing\n";
        abort();
      }

    } else if (operation >= .05 * RandomSpread) {
      unsigned key = nextUnmappedKey();
      unsigned value = next();

      llvm::outs() << "  map.insert(" << key << ", " << value << ");\n";

      map.insert((unsigned) key, (unsigned) value);
      stdMap.insert(std::make_pair(key, value));
    } else {
      llvm::outs() << "  map.clear();\n";
      map.clear();
      stdMap.clear();
    }

    llvm::outs() << "  map.validate();\n";
    map.validate();
  }
}
コード例 #17
0
/**
 * Initializes the Random Number Generator with a Random Seed.
 *
 */
void SimulatorGlobals::initializeRandomGeneratorRandomSeed() {
	std::random_device randomDevice; // Moved from class member variable to here; it seems this must be instantiated and the class constructor is not doing it.
	this->seed = randomDevice();
	this->randomEngine.seed(this->seed); // Seeds Random Engine with random seed.
}
コード例 #18
0
RandomCheckersAi::RandomCheckersAi() {
	generator = make_unique<mt19937>(randomDevice());
}
コード例 #19
0
/**
  * I'm fully aware that this code looks terrible. 
  */
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	int selection = 0;
	QTextStream io(stdin);
	do
	{
		qDebug() << "Select Task:\n1 - Task 1\n2 - Task 2";
		selection = io.readLine().toInt();
	} while (!(selection == 1 || selection == 2));

	QVector<double>& sample = QVector<double>();
	QVector<double> sample1;
	QVector<double> sample2;

	sample1	<< 0.0 << 0.0 << 0.0 << 0.0 << 0.0
			<< 0.0 << 1.0 << 1.0 << 0.0 << 0.0
			<< 0.0 << 0.0 << 1.0 << 0.0 << 0.0
			<< 0.0 << 0.0 << 1.0 << 0.0 << 0.0
			<< 0.0 << 0.0 << 1.0 << 0.0 << 0.0;

	sample2	<< 0.0 << 1.0 << 1.0 << 1.0 << 0.0
			<< 0.0 << 1.0 << 0.0 << 1.0 << 0.0
			<< 0.0 << 1.0 << 0.0 << 1.0 << 0.0
			<< 0.0 << 1.0 << 0.0 << 1.0 << 0.0
			<< 0.0 << 1.0 << 1.0 << 1.0 << 0.0;

	switch (selection)
	{
		case 1:
			sample = sample1;
		case 2:
			sample = sample2;
		default:
			sample = sample1;
	}

	//Correct way of using randoms in C++. Might be a bit overkill for {0; 1} set.
	std::random_device randomDevice;
	std::mt19937 randomGenerator(randomDevice());
	std::uniform_int_distribution<int> uniformDistribution(0, 1);

	//initialization
	QVector<double> results;
	for (int i = 0; i < 25; i++)
	{
		results.push_back((double)uniformDistribution(randomGenerator));
	}

	QVector<double> weights;
	QVector<double> theta;

	{
		QVector<double> C;
		for (int i = 0; i < 25; i++) for (int j = 0; j < 25; j++)
		{
			if (i == j)
			{
				C.push_back(0.0);
			}
			else
			{
				C.push_back((sample[i] - 0.5) * (sample[j] - 0.5));
			}
		}

		QVector<double> D;
		for (int i = 0; i < 25; i++) for (int j = 0; j < 25; j++)
		{
			if (selection == 2)
			{
				if (i == j)
				{
					D.push_back(0.0);
				}
				else
				{
					D.push_back((sample2[i] - 0.5) * (sample2[j] - 0.5));
				}
			}
			else
			{
				D.push_back(0.0);
			}
		}

		for (int i = 0; i < 25; i++) for (int j = 0; j < 25; j++)
		{
			weights.push_back(2.0 * (C[25 * i + j] + D[25 * i + j]));
		}
		
		for (int i = 0; i < 25; i++)
		{
			theta.push_back(0.0);
			for (int j = 0; j < 25; j++)
			{
				theta[i] += C[25 * i + j] + D[25 * i + j];
			}
		}
	}

	QString line;
	std::system("cls");
	qDebug() << "Initialized values";
	for (int j = 1; j <= 25; j++)
	{
		if (results[j - 1] == 1.0)
		{
			line += "*";
		}
		else
		{
			line += " ";
		}
		if (j % 5 == 0)
		{
			qDebug() << line;
			line.clear();
		}
	}
	qDebug() << "Press Enter.";
	io.readLine();

	//Learning
	for (int iteration = 1; iteration <= 25; iteration++)
	{
		QVector<double> resultsCopy = results;
		
		//Setting new values
		for (int j = 0; j < 25; j++)
		{
			double u = 0.0;
			for (int k = 0; k < 25; k++)
			{
				u += weights[k * 25 + j] * resultsCopy[k];
			}
			u = u - theta[j];

			if (u > 0.0)
			{
				results[j] = 1.0;
			}
			else
			{
				if (u < 0.0)
				{
					results[j] = 0.0;
				}
			}
		}
		//Printing effects on the screen
		std::system("cls");	//Qt equivalent does not work.
		qDebug() << "Iteration " + QString::number(iteration);
		for (int j = 1; j <= 25; j++)
		{
			if (results[j - 1] == 1.0)
			{
				line += "*";
			}
			else
			{
				line += " ";
			}
			if (j % 5 == 0)
			{
				qDebug() << line;
				line.clear();
			}
		}
		qDebug() << "Press Enter.";
		io.readLine();
	}

	return a.exec();
}
コード例 #20
0
ファイル: WebAPI.cpp プロジェクト: popoklopsi/MessageBot
WebAPIResult_t WebAPI::SendSteamMessage(Message message) {
    this->debugEnabled = message.config.debugEnabled;
    this->requestTimeout = message.config.requestTimeout;


    std::vector<uint64_t> recipientsCopy(message.config.recipients);
    if (message.config.shuffleRecipients) {
        std::random_device randomDevice;
        std::mt19937 randomEngine(randomDevice());

        std::shuffle(recipientsCopy.begin(), recipientsCopy.end(), randomEngine);
        Debug("[DEBUG] Shuffled recipient list");
    }

    Debug("[DEBUG] Trying to send a message to user '%s' with password '%s' and message '%s'", message.config.username.c_str(), message.config.password.c_str(), message.text.c_str());

    WebAPIResult_t result;

    // No recipient?
    if (recipientsCopy.size() == 0) {
        Debug("[DEBUG] Couldn't send message, as no recipients are defined");

        result.type = WebAPIResult_NO_RECEIVER;
        result.error = "No receiver was configurated";
        return result;
    }

    Json::Value loginSteamCommunityResult = this->LoginSteamCommunity(message.config.username, message.config.password);
    if (!loginSteamCommunityResult["success"].asBool()) {
        LogError(loginSteamCommunityResult["error"].asString().c_str());

        result.type = WebAPIResult_LOGIN_ERROR;
        result.error = loginSteamCommunityResult["error"].asString();
        return result;
    }

    std::string accessToken = loginSteamCommunityResult["oauth_token"].asString();
    std::string steamid = loginSteamCommunityResult["steamid"].asString();
    std::string sessionid = this->GetCookie(this->steamCommunityClient, "sessionid");

    Json::Value loginWebAPIResult = this->LoginWebAPI(accessToken);
    if (!loginWebAPIResult["success"].asBool()) {
        LogError(loginWebAPIResult["error"].asString().c_str());

        result.type = WebAPIResult_LOGIN_ERROR;
        result.error = loginSteamCommunityResult["error"].asString();
        return result;
    }

    std::string umqid = loginWebAPIResult["umqid"].asString();

    // Get friend list
    Json::Value friendListResult = this->GetFriendList(accessToken);
    if (!friendListResult["success"].asBool()) {
        LogError(friendListResult["error"].asString().c_str());

        result.type = WebAPIResult_API_ERROR;
        result.error = loginSteamCommunityResult["error"].asString();
        return result;
    }

    // Accept all friends
    Json::Value friendValue = friendListResult.get("friends", "");

    for (int i = 0; friendValue.isValidIndex(i); i++) {
        std::string steam = friendValue[i].get("steamid", "").asString();
        std::string relation = friendValue[i].get("relationship", "").asString();

        if (relation == "requestrecipient") {
            // Accept the friend if there is a request
            this->AcceptFriend(sessionid, steamid, steam);

            // Add a second timeout, as otherwise two consecutive requests can fail!
            sleep_ms(1000);
        }
    }

    // Get user stats
    Json::Value userStatsResult = this->GetUserStats(accessToken, recipientsCopy);
    if (!userStatsResult["success"].asBool()) {
        LogError(userStatsResult["error"].asString().c_str());

        result.type = WebAPIResult_API_ERROR;
        result.error = loginSteamCommunityResult["error"].asString();
        return result;
    }

    // Check if there is valid recipient which is online
    Json::Value userValues = userStatsResult.get("players", "");
    for (auto recipient = recipientsCopy.begin(); recipient != recipientsCopy.end(); recipient++) {
        for (int i = 0; userValues.isValidIndex(i); i++) {
            std::string steam = userValues[i].get("steamid", "").asString();
            int online = userValues[i].get("personastate", 0).asInt();

            if (steam == std::to_string(*recipient) && online) {
                // Send the message to the recipient
                Json::Value sendMessageResult = this->SendSteamMessage(accessToken, umqid, *recipient, message.text);
                if (!sendMessageResult["success"].asBool()) {
                    LogError(sendMessageResult["error"].asString().c_str());
                    this->LogoutWebAPI();

                    // Wait after logout, as steam needs a few seconds until logout is complete
                    sleep_ms(message.config.waitAfterLogout);

                    result.type = WebAPIResult_API_ERROR;
                    result.error = loginSteamCommunityResult["error"].asString();
                    return result;
                }

                // Wait between messages, as the user may occur some limitations on how much messages he can send
                sleep_ms(message.config.waitBetweenMessages);
                break;
            }
        }
    }

    // Logout on finish
    this->LogoutWebAPI();

    // Wait after logout, as steam needs a few seconds until logout is complete
    sleep_ms(message.config.waitAfterLogout);

    Debug("[DEBUG] Sent message");

    result.type = WebAPIResult_SUCCESS;
    result.error = std::string();
    return result;
}
コード例 #21
0
void VoronoiSeedsGenerator::generateSeeds(
	std::vector<Seed>& listOfSeeds
)
{
	/*
	 * In order to retain the current number of seeds by subdivision of the
	 * grid, we use a bi-dimensional array.
	 */
	int** nbSeedsBySub = new int* [m_nbOfHeightSubdivisions];
	for (int i = 0; i < m_nbOfHeightSubdivisions; i++) {
		nbSeedsBySub[i] = new int[m_nbOfWidthSubdivisions];
        for (int j = 0; j < m_nbOfWidthSubdivisions; j++) {
            nbSeedsBySub[i][j] = 0;
        }
	}

    /*
     * So as to retain the repartition of the inserted seeds, we need to allocate another array.
     * This one is dynamically allocated since it will be necessary to use it as an argument
     * for a function.
     */
    std::vector<Seed>** seedsBySub = new std::vector<Seed>* [m_nbOfHeightSubdivisions];
    for (int i = 0; i < m_nbOfHeightSubdivisions; i++) {
        seedsBySub[i] = new std::vector<Seed> [m_nbOfWidthSubdivisions];
    }

	/*
	 * Initializing the random generator which is going to be used in order to
	 * generate the seeds.
	 */
    std::random_device randomDevice;
	std::mt19937 generator(randomDevice());
	std::normal_distribution<float> widthDistrib(m_width/2.0, m_width/5.0);
	std::normal_distribution<float> heightDistrib(m_height/2.0, m_height/5.0);

	/*
	 * Main loop of the function in which the seeds are generated.
     * On top of that, in order to ease the implementation of the "Whittaker
     * step", the seeds have to be sorted according to their distance to the
     * center of the map.
     * So as to do so, the seeds are sorted by "insertion" in a temporary list,
     * and then pushed back in the given vector.
	 */
    std::list<Seed> tmpList;
	int currentNbOfSeeds = 0;
	while (currentNbOfSeeds < m_nbOfSeeds) {
		float wPosition = widthDistrib(generator);
		float hPosition = heightDistrib(generator);
		/*
		 * Testing if the subdivision which is going to contain the new seed
		 * is "full".
		 */
		int widthID = (int)(floor(wPosition/m_width*m_nbOfWidthSubdivisions));
		int heightID = (int)(floor(hPosition/m_height*m_nbOfHeightSubdivisions));

        if (
                (widthID >= 0) && (widthID < m_nbOfWidthSubdivisions) 
            &&  (heightID >=0) && (heightID < m_nbOfHeightSubdivisions)
        ) {
            if (nbSeedsBySub[heightID][widthID] < m_maxNbOfSeedsBySubdivision) {
                Seed seed(wPosition, hPosition);

                /*
                 * Inserting only if the new seed is at a minimal distance 
                 * of the other ones previously inserted.
                 */
                if (isMinDistVerified(seedsBySub, widthID, heightID, seed)) {
                    insertIntoList(tmpList, seed);
                    currentNbOfSeeds++;
                    nbSeedsBySub[heightID][widthID]++;
                    seedsBySub[heightID][widthID].push_back(seed);
                }
            }
        }
	}

    /*
     * Freeing the allocated memory zone related to seeds' repartition.
     */
    for (int i = 0; i < m_nbOfHeightSubdivisions; i++) {
		seedsBySub[i]->clear();
        delete [] seedsBySub[i];
		delete[] nbSeedsBySub[i];
    }
    delete [] seedsBySub;
	delete[] nbSeedsBySub;


    /*
     * Finally, we just have to insert the content of the list into the
     * given vector.
     */
    for (
        auto iterator = tmpList.begin();
        iterator != tmpList.end();
        iterator++
    ) {
        listOfSeeds.push_back(*iterator);
    }
}
コード例 #22
0
int UsherBase::attemptToInsertParticlesInRegion
(
    int numberOfParticlesToInsert,
    double targetPotential, 
    double regionXMin,
    double regionYMin,
    double regionZMin,
    double regionXMax,
    double regionYMax,
    double regionZMax
)
{
    // Random number generator (see
    // cppreference.com/w/cpp/numeric/random/uniform_real_distribution)
    std::random_device randomDevice;
    std::mt19937 randomNumberGenerator (randomDevice());
    std::uniform_real_distribution<> randomX (regionXMin, regionXMax);
    std::uniform_real_distribution<> randomY (regionYMin, regionYMax);
    std::uniform_real_distribution<> randomZ (regionZMin, regionZMax);

    int insertedParticlesCount = 0;

    for (int n = 0; n < numberOfParticlesToInsert; ++n)
    {
        for (int attempt = 0; attempt < maxAttempts; ++attempt)
        {

            try
            {
                auto startX = randomX (randomNumberGenerator);
                auto startY = randomY (randomNumberGenerator);
                auto startZ = randomZ (randomNumberGenerator);


                Vector3D r = findPositionWithPotential 
                (
                    targetPotential, startX, startY, startZ
                );

                if 
                (
                    r.x >= regionXMin && r.x <= regionXMax && 
                    r.y >= regionYMin && r.y <= regionYMax && 
                    r.z >= regionZMin && r.z <= regionZMax
                )
                {
                    insertOneAtPosition (r.x, r.y, r.z); 
                    ++insertedParticlesCount;
                    break;
                }

            }
            catch (UsherTryAgain& e)
            {
                // Debug: std::cout << e.what() << std::endl;
            }

        }  
    }

    if (insertedParticlesCount < numberOfParticlesToInsert)
    {
        throw UsherFailToInsertAll 
        (
            numberOfParticlesToInsert,
            insertedParticlesCount
        );
    }

    return insertedParticlesCount;

}
コード例 #23
0
ファイル: Obstacle.cpp プロジェクト: WalterShih/GameJamClass
bool Obstacle::init(Obstacle::Type type)
{
    if (!Node::init())
    {
        return false;
    }
    
    this->setTag(OBSTACLE_TAG);
    bool isHorizontal = false;
    
    // type to params
    std::string fileName;
    switch (type)
    {
        case Type::BANANA:
            fileName = "banana.png";
            break;
        case Type::BIRD:
            fileName = "bird_01.png";
            isHorizontal = true;
            break;
        case Type::METER:
            fileName = "meteor_01.png";
            break;
        case Type::UFO:
            fileName = "ufo_01.png";
            isHorizontal = true;
            break;
        case Type::Role1:
            fileName = "b0010.png";
            break;
        case Type::Role2:
            fileName = "b0011.png";
            isHorizontal = true;
            break;
        case Type::Role3:
            fileName = "b0023.png";
            break;
        case Type::Role4:
            fileName = "b0059.png";
            isHorizontal = true;
            break;
        case Type::Role5:
            fileName = "b0061.png";
            break;
            
        default: break;
    }
    fileName = StringUtils::format("obstacles/%s", fileName.c_str());
    
    _sprite = Sprite::create(fileName);
    this->addChild(_sprite);
    runAnimation();
    
    // collider
    Size colliderSize = _sprite->getContentSize() * 0.6f;
    auto physicsBody = PhysicsBody::createBox(colliderSize);
    physicsBody->setCategoryBitmask(OBSTACLE_BITMASK);
    physicsBody->setCollisionBitmask(FLYPLANT_BITMASK);
    physicsBody->setContactTestBitmask(FLYPLANT_BITMASK);
    physicsBody->setDynamic(true);
    physicsBody->setMass(10);
    this->setPhysicsBody(physicsBody);
    
    // random
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point visibleOrigin = Director::getInstance()->getVisibleOrigin();
    std::random_device randomDevice;
    std::mt19937 generator(randomDevice());
    std::uniform_int_distribution<> distibution1(0, visibleSize.width);
    std::uniform_int_distribution<> distibution2(visibleSize.height/3.0f, visibleSize.height * 2.0f/3.0f);
    float width = distibution1(generator);
    float height = distibution2(generator);
    
    bool isLeft = true;
    std::uniform_int_distribution<> distibution3(0, 1);
    if (distibution3(generator) > 0)
    {
        isLeft = false;
    }
    
    if (!isHorizontal)
    {
        this->setPosition(visibleOrigin + Vec2(width, visibleSize.height));
        physicsBody->setVelocity(Vect(0, -OBSTACLE_VELOCITY));
    }
    else
    {
        if (isLeft)
        {
            this->setPosition(visibleOrigin + Vec2(0, height));
            physicsBody->setVelocity(Vect(OBSTACLE_VELOCITY, -20));
        }
        else
        {
            this->setPosition(visibleOrigin + Vec2(visibleSize.width, height));
            physicsBody->setVelocity(Vect(-OBSTACLE_VELOCITY, -20));
        }
    }
    
    return true;
}
コード例 #24
0
ファイル: rng.cpp プロジェクト: WingBot/pedsim_ros
RandomNumberGenerator::RandomNumberGenerator()
{
    std::random_device randomDevice;
    uint seed = randomDevice();
    randomEngine.seed ( seed );
}