Exemplo n.º 1
0
void System::spawnWave() {
    if(wave == 10) {
        std::cout << "Game completed" << std::endl;
    }

    wave++;
    double dAngle = 2 * M_PI / wave;
    double angle = 0.001;

     std::default_random_engine generator;
    generator.seed(wave);
    auto distribution = std::uniform_int_distribution<int>(0,1000);
    auto angleDist = std::uniform_real_distribution<double>(0.0015,0.005);
    std::function<double()> randGen = std::bind ( distribution, generator );

    while(angle < 2*M_PI) {
        ships.emplace_back(Tuple(cos(angle) * killRadius/2,sin(angle) * killRadius / 2),
                           randGen() / 5+10,randGen() /20 + 10, randGen()/70 + 15,randGen()/7 + 150
                           ,angleDist(generator)   );
        angle += dAngle;
    }
    if(wave > 3)
        for(auto &ship : ships)
            ship.cannibalizeWeapon(Crate::generateWeapon());
    if(wave > 5)
        for(int i = wave; i > 5; i--)
            ships[4].cannibalizeWeapon(Crate::generateWeapon());



}
Exemplo n.º 2
0
// Thread methods
void Scan( BufferManager* bm, uint32_t pagesOnDisk, bool& stop, uint32_t& fails )
{
	// Construct a random device to seed the random generator with true random numbers
	std::random_device rd;
	std::minstd_rand randGen( rd() );

	// scan all pages and check if the counters are not decreasing
	std::vector<uint32_t> counters( pagesOnDisk, 0 );

	while ( !stop )
	{
		uint32_t start = randGen() % (pagesOnDisk - 10);
		for ( uint32_t page = start; page < start + 10; page++ )
		{
			BufferFrame& bf = bm->FixPage( BufferManager::MergePageId( DB_TEST_SEGMENT, page), false );
			uint32_t newcount = reinterpret_cast<uint32_t*>(bf.GetData())[0];
			if (newcount < counters[page])
			{
				++fails;
			}
			counters[page] = newcount;
			bm->UnfixPage( bf, false );
		}
	}
}
Exemplo n.º 3
0
uint32_t ReadWrite( BufferManager* bm, uint32_t threadNum, uint32_t threadCount, uint32_t pagesOnDisk )
{
	// Construct a random device to seed the random generator with true random numbers
	std::random_device rd;
	std::minstd_rand randGen( rd() );
	std::normal_distribution<float> normalDist(0.0f, 0.2f);

	uint32_t count = 0;
	for ( uint32_t i = 0; i < 100000 / threadCount; i++ )
	{
		bool isWrite = randGen() % 128 < 10;
		BufferFrame& bf = bm->FixPage( 
			BufferManager::MergePageId( DB_TEST_SEGMENT, 
										RandomPage( normalDist( randGen ), pagesOnDisk ) ), isWrite );

		if ( isWrite )
		{
			++count;
			reinterpret_cast<uint32_t*>(bf.GetData())[0]++;
		}
		bm->UnfixPage( bf, isWrite );
	}

	return count;
}
Exemplo n.º 4
0
Challenge::Challenge(uint32_t challengeSeqNum, UserNumber_t num, 
                     HMACAlgorithm algorithm, ChallengeReason reason) :
  seqNum(challengeSeqNum), userNum(num), hmacAlgorithm(algorithm), 
  challengeReason(reason)
{
    randGen(challengeData, MIN_CHALLENGE_SIZE);
}
Exemplo n.º 5
0
void OPTICSFilter::extractDBSCANClustering(const std::string& seedString) {
    std::vector<OPTICSObject_Ptr> currentCluster;

    // needed for use of uniform dist
    typedef std::mt19937_64 RNG;
    std::seed_seq seed(seedString.begin(), seedString.end());
    std::unique_ptr<RNG> randGen(new RNG);
    randGen->seed(seed);

    // we start with cluster 1 and use 0 as noise
    int clusterID = 1;
    for (OPTICSObject_Ptr& obj : _orderedObjects) {
        if (obj->reachabilityDistance > _epsDBSCAN) {
            if (obj->coreDistance <= _epsDBSCAN) {
                // get random obj from currentCluster and append to locations
                if (currentCluster.empty() == false) {
                    std::uniform_int_distribution<int> elemDist(0, currentCluster.size() - 1);
                    OPTICSObject_Ptr randObj = currentCluster.at(elemDist(*randGen));
                    _locations->push_back(randObj->node);
                }
                currentCluster.clear();
                clusterID++;
                obj->clusterId = clusterID;
                currentCluster.push_back(obj);
            } else {
                obj->clusterId = 0;  // noise
                _locations->push_back(obj->node);
            }
        } else {
            obj->clusterId = clusterID;
            currentCluster.push_back(obj);
        }
    }
}
Exemplo n.º 6
0
void Solver::findPossibleSlots(
        const int box,
        std::vector<std::stack<std::pair<int,int>>>& backTrackStack,
        const int num) {
    int highestRow = (box/3)*3; //Row of upper-left box
    int highestCol = (box%3)*3; //Column of upper-left box

    std::vector<std::pair<int,int>> shuffleVec;
    /* Reversed the order so first item on stack is the upper-leftmost slot */
    for(int rowIter = 2; rowIter >= 0; --rowIter) {
        for(int colIter = 2; colIter >= 0; --colIter) {
            bool existsRow = checkRow(highestRow + rowIter, num);
            bool existsCol = checkColumn(highestCol + colIter, num);
            if(!existsRow && !existsCol) {
                shuffleVec.push_back(std::make_pair(rowIter,colIter));
#ifdef DEBUG
                std::cout << "Adding possible slot " << rowIter << "," <<
                    colIter << " for " << num << std::endl;
#endif
            }
            else if(existsRow) break;
            else continue;
        }
    }
    std::random_device seedGen;
    std::mt19937 randGen(seedGen());
    std::shuffle(shuffleVec.begin(), shuffleVec.end(), randGen);
    for(auto p : shuffleVec) backTrackStack[num-1].push(p);
}
//+--------------------------------------------------------------------------+
//|				From PFOperatorMaterialStaticState::IPFActionState				 |
//+--------------------------------------------------------------------------+
IOResult PFOperatorMaterialStaticState::Save(ISave* isave) const
{
	ULONG nb;
	IOResult res;

	isave->BeginChunk(IPFActionState::kChunkActionHandle);
	ULONG handle = actionHandle();
	if ((res = isave->Write(&handle, sizeof(ULONG), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkRandGen);
	if ((res = isave->Write(randGen(), sizeof(RandGenerator), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkData);
	float offset = cycleOffset();
	if ((res = isave->Write(&offset, sizeof(float), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkData2);
	TimeValue time = offsetTime();
	if ((res = isave->Write(&time, sizeof(TimeValue), &nb)) != IO_OK) return res;
	isave->EndChunk();

	return IO_OK;
}
Exemplo n.º 8
0
int main(int argc, char *argv[]){
	// too many or not enough
	if(argc < 2 || argc > 2){
		printf("usage:\n\tkeygen [keyLength]  //keyLength required\n");
		exit(0);
	}

	// bad number
	else if(atoi(argv[1]) < 1){
		printf("usage:\n\tkeygen [keyLength]  //keyLength must be > 0\n");
		exit(1);	
	}
	
	// just right
	else {
		int keysize = atoi((argv[1]));
		srand(time(NULL));
		int i;
		for(i = 0; i < keysize; i++){
			printf("%c", convertNumeric(randGen()));
		}
		printf("\n");
		return 0;
	}
}
//==================================================================
void HiderSampleCoordsBuffer::Init( u_int wd, u_int he, u_int subPixelDimLog2 )
{
	mWd = wd;
	mHe = he;
	mSubPixelDimLog2 = subPixelDimLog2;

	u_int	sampsPerPixel = 1 << (subPixelDimLog2*2);

	size_t	sampArrSize = (size_t)mWd * (size_t)mHe * sampsPerPixel;

	mpSampCoords = DNEW HiderSampleCoords [ sampArrSize ];
	mpBaseSampCoords = DNEW HiderBaseSampleCoords [ sampArrSize ];

	DUT::RandMT	randGen( (U32)0x11112222 );

	size_t sampsCnt = 0;
	for (u_int y=0; y < mHe; ++y)
	{
		for (u_int x=0; x < mWd; ++x, sampsCnt += sampsPerPixel)
		{
			initPixel(
				mpSampCoords + sampsCnt,
				mpBaseSampCoords + sampsCnt,
				subPixelDimLog2,
				randGen );
		}
	}
}
Exemplo n.º 10
0
//+--------------------------------------------------------------------------+
//|				From PFTestSplitByAmountState::IPFActionState				 |
//+--------------------------------------------------------------------------+
IOResult PFTestSplitByAmountState::Save(ISave* isave) const
{
	ULONG nb;
	IOResult res;

	isave->BeginChunk(IPFActionState::kChunkActionHandle);
	ULONG handle = actionHandle();
	if ((res = isave->Write(&handle, sizeof(ULONG), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkRandGen);
	if ((res = isave->Write(randGen(), sizeof(RandGenerator), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkData);
	int wT = wentThru();
	if ((res = isave->Write(&wT, sizeof(int), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkData2);
	int wTA = wentThruAccum();
	if ((res = isave->Write(&wTA, sizeof(int), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkData3);
	int wTT = wentThruTotal();
	if ((res = isave->Write(&wTT, sizeof(int), &nb)) != IO_OK) return res;
	isave->EndChunk();

	return IO_OK;
}
Exemplo n.º 11
0
Arquivo: P5.c Projeto: sargasso/public
/* Random Sleep Number */
int randSleep() {
	int factor = 100000;
	int sleep_time = 1;
	while (factor != 1) {
		sleep_time += factor * (randGen() - 1);
		factor /= 10;
	}
	return sleep_time;
}
Exemplo n.º 12
0
int
main()
{
	cout << "Beginning random number test.  No news is good news" << endl;

// Test UniformInt32, the basic generator method
	cout << std::setbase(16);
	JKLRand randGen( jKLInt32List[0] );
	JIndex i = 1;
	while (jKLInt32List[i] != 0)
		{
		JInt32 thisVal = randGen.UniformInt32();
		if (jKLInt32List[i] != thisVal)
			{
			cout << "   UniformInt32 failed on test value " << i << "; generated "
			     << thisVal << " instead of " << jKLInt32List[i] << endl;
			}
		i++;
		}

// Tests UniformClosedProb as well.
	cout << std::setbase(10);
	randGen.SetSeed( jKLLongList[0] );
	i=1;
	while (jKLLongList[i] != 0)
		{
		long thisVal = randGen.UniformLong(0, 10000);
		if (jKLLongList[i] != thisVal)
			{
			cout << "   UniformLong failed on test value " << i << "; generated "
			     << thisVal << " instead of " << jKLLongList[i] << endl;
			}
		i++;
		}

	for (i=1;i<=1000000;i++)
		{
		double thisVal = randGen.UniformClosedProb();
		if (thisVal < 0.0 || thisVal > 1.0)
			{
			cout << "   UniformClosedProb returned " << thisVal;
			}
		}

	for (i=1;i<=1000000;i++)
		{
		double thisVal = randGen.UniformDouble(-100.0, 100.0);
		if (thisVal < -100.0 || thisVal > 100.0)
			{
			cout << "   UniformDouble(-100.0, 100.0) returned " << thisVal;
			}
		}

	cout << "Finished random number test.  If nothing printed out, it passed" << endl;

	return 0;
}
vector<int> CountMin::returnHashFunctionsOfString(std::string word){
	// First we hash the string to generate seeds for a random number generator
	boost::hash<std::string> string_hash;
	boost::mt19937 randGen(string_hash(word));
	boost::uniform_int<> numrange(0, NUM_BINS-1);
	boost::variate_generator< boost::mt19937&, boost::uniform_int<> > GetRand(randGen, numrange);
	vector<int> hashes;
	for(int i =0;i<NUM_HASH;i++){
		hashes.push_back(GetRand());
	}
	return hashes;
}
Exemplo n.º 14
0
NTL::ZZ_pX YASHE::randomKeyPoly() {
  NTL::ZZ_pX output;
  output.SetLength(maxDegree + 1);

  for (long i = 0; i <= maxDegree; i++) {
    long choice = (randGen() % 3);
    choice -= 1; // choice is in {-1, 0, 1}
    output[i] = NTL::ZZ_p(choice);
  }

  return output;
}
//+--------------------------------------------------------------------------+
//|				From PFOperatorMaterialFrequencyState::IPFActionState				 |
//+--------------------------------------------------------------------------+
IOResult PFOperatorMaterialFrequencyState::Save(ISave* isave) const
{
	ULONG nb;
	IOResult res;

	isave->BeginChunk(IPFActionState::kChunkActionHandle);
	ULONG handle = actionHandle();
	if ((res = isave->Write(&handle, sizeof(ULONG), &nb)) != IO_OK) return res;
	isave->EndChunk();

	isave->BeginChunk(IPFActionState::kChunkRandGen);
	if ((res = isave->Write(randGen(), sizeof(RandGenerator), &nb)) != IO_OK) return res;
	isave->EndChunk();

	return IO_OK;
}
Exemplo n.º 16
0
void Solver::solveSemiSeed(const int semiSeed) {
    /* Create RNG */
    std::random_device seedGen;
    std::mt19937 randGen(seedGen());

    /* Generate semiSeed first */
    int highestRow = (semiSeed/3)*3; //Row of upper-left box
    int highestCol = (semiSeed%3)*3; //Column of upper-left box
    std::array<int, 9> nums = {1,2,3,4,5,6,7,8,9};
    std::shuffle(nums.begin(), nums.end(), randGen);
#ifdef DEBUG
    std::cout << "nums:" << std::endl;
    for(auto e : nums) std::cout << e << " ";
    std::cout << std::endl;
#endif
    for(int valIter = 0; valIter < 9; valIter++) {
        for(int boxIter = 0; boxIter < 9; boxIter++) {
            int currentRow = highestRow+boxIter/3;
            int currentCol = highestCol+boxIter%3;
            bool rowExists = checkRow(currentRow,nums[valIter]);
            bool colExists = checkColumn(currentCol,nums[valIter]);
            if(!rowExists && !colExists) {
                if(
                        !sudokuBoard[semiSeed].addNumber(
                            boxIter/3,
                            boxIter%3,
                            nums[valIter])
                  ) {
#ifdef DEBUG
                    std::cout << "Did not add " << nums[valIter] << " to semiSeed at "
                        << boxIter/3 << "," << boxIter%3 << std::endl;
#endif
                }
                else break;
            }
            else if(rowExists) boxIter+=2;
            else continue;
        }
    }

#ifdef DEBUG
    std::cout << "semiSeed values:" << std::endl;
    sudokuBoard[semiSeed].debugPrint();
#endif

}
Exemplo n.º 17
0
void NodeImporter::importCities(const std::string& seedString) {
    /*
      READ CITY POSITIONS ON EARTH SURFACE
    */
    Config_Ptr config(new Config);

    Config_Ptr cityFilterConfig(config->subConfig("cityfilter"));
    int populationThreshold = cityFilterConfig->get<int>("citysizethreshold");

    auto lr = std::make_shared<SQLiteLocationReader>(_dbFilename, populationThreshold);

    typedef std::map<std::string, std::vector<CityNode>> CountryMap;
    std::unique_ptr<CountryMap> countries(new CountryMap);

    while (lr->hasNext()) {
        CityNode next = lr->getNext();
        (*countries)[next.country()].push_back(next);
    }

    std::unique_ptr<InternetUsageStatistics> stat(new InternetUsageStatistics(_dbFilename));

    typedef std::mt19937_64 RNG;
    std::seed_seq seed(seedString.begin(), seedString.end());
    std::unique_ptr<RNG> randGen(new RNG);
    randGen->seed(seed);
    std::uniform_real_distribution<double> dist(0.0, 1.0);

    // filter cities
    for (auto country : *countries) {
        std::string countryName = country.first;
        auto& cityVec = country.second;
        double percentInetUsers = (*stat)[countryName] / 100.0;

        for (auto city : cityVec)
            if (dist(*randGen) <= percentInetUsers) {
                city.setId(_nodenumber);
                ++_nodenumber;
                GeographicNode_Ptr np(new CityNode(city));
                addNode(np);
            }
    }
}
Exemplo n.º 18
0
Arquivo: P5.c Projeto: sargasso/public
/* Producer Thread */
void * T1(void *t) {
	printf("Producer Started\n");
	struct LList *ll = (struct LList*) t;
	int value;
	while (!done) {
		usleep(randSleep());
		pthread_mutex_lock(&count_mutex);
		if (size == 10) {
			printf("Queue is full\n");
		} else {
			/* Add to Queue */
			value = randGen();
			AddEntry(ll, value);
			size++;
			printf("Producer added %d to queue, size = %d\n", value, size);
			/* Wake up Threads and Mutex Locks */
			pthread_cond_broadcast(&count_cond);
		}
		pthread_mutex_unlock(&count_mutex);
	}
	pthread_exit(NULL);
}
Exemplo n.º 19
0
	float GenFloatRandom(float fMin, float fMax) 
	{
		static boost::random::mt19937 rng((uint32_t)std::time(0));
		boost::random::uniform_real_distribution<> randGen(fMin, fMax);
		return randGen(rng);
	}
Exemplo n.º 20
0
// perform classification in separate threads
void Classifier::runThread(FastaReader &reader)
{
    DnaSequence seq;
    boost::mt19937 randGen(0);
    RandomGen generator(randGen);

    while(seq = reader.readSequence())
    {
        // reproducible randomness
        randGen.seed(reader.numRead());

        // get a query sequence and convert to kmers
        KmerSequence fwdSeq = kmerizer_.kmerize(seq);
        
        // and the reverse complement
        KmerSequence revSeq = kmerizer_.revComp(fwdSeq);
        
        // search against database using both forward and reverse sequences
        searchHit fwdHit = referenceData_.search(fwdSeq);
        searchHit revHit = referenceData_.search(revSeq);

        // use the direction which gave the highest scoring hit
        KmerSequence &querySeq = fwdHit.score > revHit.score ? fwdSeq : revSeq;
        searchHit &hit = fwdHit.score > revHit.score ? fwdHit : revHit;

        std::vector<float> bootstraps(referenceData_.numLevels(), 0.f);
        std::vector<std::string> annotations(referenceData_.numLevels(), "AMBIGUOUS");
       
        // make each level annotations into a list of uniques
        for (unsigned int i=0; i< hit.annotationIds.size(); i++)
        {
            std::sort(hit.annotationIds[i].begin(), hit.annotationIds[i].end());
            std::vector<unsigned int>::iterator it;
            it = std::unique(hit.annotationIds[i].begin(), hit.annotationIds[i].end());
            hit.annotationIds[i].resize(std::distance(hit.annotationIds[i].begin(), it));
            if (hit.annotationIds[i].size() == 1)
                annotations[i] = referenceData_.annotationFromId(*hit.annotationIds[i].begin());
        }

        // bootstrap
        if(numBootstrap_ > 0)
            bootstraps = getBootstrap(querySeq, generator, hit);
       
        // output        
        std::stringstream s;
        s << std::setprecision(2) << std::fixed;
        s << querySeq.header.substr(0, querySeq.header.find("\t")) << "\t";
        s << hit.score << "\t";

        //for(unsigned int i=0; i<bootstraps.size(); i++)
        unsigned int i=bootstraps.size();
        while(i--)
        {
            s << annotations[i] << "\t";
            s << bootstraps[i];
            if(i>0)
            {
                s <<  "\t";
            }
            else
            {
                // dump ambiguous species
                if (hit.annotationIds[i].size() > 1 && outputAmbiguous_)
                { 
                    s << "\t";
                    for(std::vector<unsigned int>::iterator it = hit.annotationIds[i].begin(); it != hit.annotationIds[i].end(); ++it)
                    {
                        if (it != hit.annotationIds[i].begin())
                            s << ",";
            
                        s << referenceData_.annotationFromId(*it);
                    }
                }
            
                s << std::endl;
            }
        }
      
        boost::mutex::scoped_lock lock(mutex_);
        std::cout << s.str();
    }
}
Exemplo n.º 21
0
bool Solver::solve(const int box) {

    /* Create RNG */
    std::random_device seedGen;
    std::mt19937 randGen(seedGen());

    std::array<int, 9> nums = {1,2,3,4,5,6,7,8,9};
    std::shuffle(nums.begin(), nums.end(), randGen);
    bool isSolved = true;

#ifdef DEBUG
    std::cout << "solve2() random array" << std::endl;
    for(auto e : nums) std::cout << e << " ";
    std::cout << std::endl;
#endif

    /* Create backtrack stack */
    std::vector<std::stack<std::pair<int,int>>> backTrackStack(9);
    /* Find possible slots for each value */
    for(int number = 1; number <= 9; ++number) findPossibleSlots(box, backTrackStack, number);

    for(int numsIter = 0; numsIter < 9; ++numsIter) {
        int number = nums[numsIter]-1;

        if(backTrackStack[number].empty()) {
#ifdef DEBUG
            std::cout << "Empty at " << number+1 << std::endl;
#endif
            findPossibleSlots(box, backTrackStack, number+1);
            numsIter--;
            if(numsIter == -1) {
#ifdef DEBUG
                std::cout << "No solution possible for box " << box << std::endl;
#endif
                isSolved = false;
                break;
            }
            number = nums[numsIter]-1; //Since numsIter is already decremented
            auto slot = backTrackStack[number].top();
            int row = std::get<0>(slot);
            int col = std::get<1>(slot);
            sudokuBoard[box].removeNumber(row,col,number+1);
            backTrackStack[number].pop();
            numsIter--; //Decrement even further
            continue;
        }
        auto slot = backTrackStack[number].top();
        int row = std::get<0>(slot);
        int col = std::get<1>(slot);
#ifdef DEBUG1
        std::cout << "Adding " << number+1 << " at " << row << "," << col << std::endl;
#endif

        if(!sudokuBoard[box].addNumber(row, col, number+1)) {
#ifdef DEBUG1
            std::cout << "Rejected " << number+1 << " at " << row << "," << col << std::endl;
#endif
            /* Remove invalid slots */
            backTrackStack[number].pop();
            numsIter--;
            if(backTrackStack[number].empty()) {
#ifdef DEBUG
                std::cout << "Empty at " << number+1 << std::endl;
#endif
                findPossibleSlots(box, backTrackStack, number+1);
                number = nums[numsIter]-1; //Since numsIter is already decremented
                slot = backTrackStack[number].top();
                row = std::get<0>(slot);
                col = std::get<1>(slot);
                sudokuBoard[box].removeNumber(row,col,number+1);
                backTrackStack[number].pop();
                numsIter--; //Decrement even further
                if(numsIter <= -1) {
#ifdef DEBUG
                    std::cout << "No solution possible for box " << box << std::endl;
#endif
                    isSolved = false;
                    break;
                }
            }
        }
#ifdef DEBUG1
        else std::cout << "Added!" << std::endl;
#endif
    } //End of for-loop

    return isSolved;
}
void fi::VPDetectionCloud::ClusterKDirectionPatches(const pcl::PointCloud<pcl::PointXYZ>::Ptr &_InCloud, Eigen::VectorXf &fRobustEstimatedVP)
{

	unsigned int fNumOfNormals = _InCloud->points.size() * m_ModelParams->fPercentageOfNormals / 100;
	unsigned int fNumOfCrossProducts = m_ModelParams->fNumOfCrossProducts;
	unsigned  int fNumberOfRansacIterations = m_ModelParams->fNumOfIterations;
	unsigned int m_k = m_ModelParams->m_k;

	if ( m_k == 0)
	{
		m_k = 5;
	}

	double fEPS = m_ModelParams->fEPSInDegrees;
	Eigen::Vector4f fEstimatedVP1;


	//// Create the normal estimation class, and pass the input dataset to it
	//pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimation;
	//normal_estimation.setInputCloud (cloud);

	//// Create an empty kdtree representation, and pass it to the normal estimation object.
	//// Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
	//pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
	//normal_estimation.setSearchMethod (tree);

	//// Output datasets
	//pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);

	//PtCloudDataPtr InPclDataPtr1(new PtCloudData());
	///*pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(pclData);*/
	//boost::shared_ptr<PtCloudData> InPclDataPtr(new PtCloudData(pclData));
	int nPointCandidates = _InCloud->points.size();

		// Consider using more precise timers such as gettimeofday on *nix or
		// GetTickCount/timeGetTime/QueryPerformanceCounter on Windows.
		boost::mt19937 randGen(std::time(0));

		// Now we set up a distribution. Boost provides a bunch of these as well.
		// This is the preferred way to generate numbers in a certain range.
		// initialize a uniform distribution between 0 and the max=nPointCandidates

		boost::uniform_int<> uInt8Dist(0, nPointCandidates);

		// Finally, declare a variate_generator which maps the random number
		// generator and the distribution together. This variate_generator
		// is usable like a function call.
		boost::variate_generator< boost::mt19937&, boost::uniform_int<> > 
			GetRand(randGen, uInt8Dist);

		//sample random points and compute their normals
		pcl::IndicesPtr indices(new  std::vector<int>());
		for (unsigned int i = 0; i < fNumOfNormals; i++)
		{
			indices->push_back(GetRand() % nPointCandidates);      
		}

		/*pcl::NormalEstimationOMP fd;*/ // 6-8 times faster ?
		pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
		ne.setInputCloud (_InCloud);
		ne.setSearchMethod (pcl::search::KdTree<pcl::PointXYZ>::Ptr (new pcl::search::KdTree<pcl::PointXYZ>));
		ne.setKSearch (m_k);
		//ne.setRadiusSearch (fRadius); //////toDo Set Cloud and radius hier correctly!
		//ne.setSearchSurface(source.surface);
		ne.setIndices(indices);

		pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>());
		ne.compute (*normals);

		//typedef boost::scoped_ptr<Eigen::Vector4f> fXProds;

		std::vector<boost::shared_ptr<Eigen::Vector4f> > fVPHypothesis;
		std::vector<boost::shared_ptr<Eigen::Vector4f> > fVPHypothesisInliers;

		//sample random points and compute their normals
		for (unsigned int i = 0; i < fNumOfCrossProducts; i++)
		{
			unsigned int fIndexA = GetRand() % fNumOfNormals;
			unsigned int fIndexB = GetRand() % fNumOfNormals;

			pcl::Normal &fnormalA = normals->points.at(fIndexA);
			pcl::Normal &fnormalB = normals->points.at(fIndexB);

			Eigen::Vector4f fA(fnormalA.normal_x, fnormalA.normal_y, fnormalA.normal_z, 0); 
			Eigen::Vector4f fB(fnormalB.normal_x, fnormalB.normal_y, fnormalB.normal_z, 0);
			Eigen::Vector4f fC = fA.cross3(fB);

			boost::shared_ptr<Eigen::Vector4f> ftmpRes(new Eigen::Vector4f(fC));
			/*fXProds faVPHypothesis(new Eigen::Vector4f(fC));*/
			fVPHypothesis.push_back(ftmpRes);
			//tmpdistances = sqrt ((line_pt - fPlaneB->points[j].getVector4fMap ()).cross3 (line_dir).squaredNorm ());
		}

		//The Cross products are then the direction we are looking. Find the majority w.r.t a ref Direction!
		Eigen::Vector4f fRefDir (1.0, 0.0, 0.0, 0);

		//Validate the best using RANSAC w.r.t refDir
		unsigned int counterMax = 0;
		unsigned int iBest;
		for (unsigned int g = 0; g < fNumberOfRansacIterations; g++)
		{

			unsigned int gIndex = GetRand() % fNumOfCrossProducts;

			Eigen::Vector4f &fu1 = *fVPHypothesis.at(gIndex);
			double fAnglesInRadians = pcl::getAngle3D(fu1, fRefDir);
			double fAngleInDegrees = pcl::rad2deg(fAnglesInRadians);

			//score the selected hypothesis
			unsigned int sCounter = 0 ;
			for (unsigned int l = 0; l < fNumOfCrossProducts; l++)
			{
				//const float sAnglesInRadianstmp = Math3d::Angle(*((*crosProds)[l]), sRefDir);
				//const float sAnglesInDegreestmp = sAnglesInRadianstmp * 180.0f / CV_PI;

				Eigen::Vector4f &fu1tmp = *fVPHypothesis.at(l);
				double fAnglesInRadianstmp = pcl::getAngle3D(fu1tmp, fRefDir);
				double fAngleInDegreestmp = pcl::rad2deg(fAnglesInRadianstmp);

				if (fabsf(fAngleInDegreestmp - fAngleInDegrees) <= fEPS) //Tolerance of 2 Degress!!!
				{
					sCounter++;

				}
			}
			if (sCounter > counterMax)
			{	
				counterMax = sCounter;
				iBest = gIndex;
			}
		}

		//Insert the Estimated VP!
		//fEstimatedVP1 = *fVPHypothesis.at(l);
		/*delete m_pclDataPtr;*/
		//collect all the inliers and do WLeastSquaresFit
		Eigen::Vector4f &fBestModel = *fVPHypothesis.at(iBest);
		double fAnglesInRadiansBest = pcl::getAngle3D(fBestModel, fRefDir);
		double fAngleInDegreesBest = pcl::rad2deg(fAnglesInRadiansBest);

		pcl::PointCloud<pcl::PointXYZ>::Ptr fVPCandidates(new pcl::PointCloud<pcl::PointXYZ>);
		fVPCandidates->width = counterMax;
		fVPCandidates->height = 1;
		fVPCandidates->resize(fVPCandidates->width * fVPCandidates->height);
		unsigned int ii = 0;

		for (unsigned int l = 0; l < fNumOfCrossProducts; l++)
		{
			Eigen::Vector4f &fu1tmp = *fVPHypothesis.at(l);
			double fAnglesInRadianstmp = pcl::getAngle3D(fu1tmp, fRefDir);
			double fAngleInDegreestmp = pcl::rad2deg(fAnglesInRadianstmp);

			if (fabsf(fAngleInDegreestmp - fAngleInDegreesBest) <= fEPS) //Tolerance of 2 Degrees!!!
			{
				fVPCandidates->points[ii].x = fu1tmp(0);
				fVPCandidates->points[ii].y = fu1tmp(1);
				fVPCandidates->points[ii].z = fu1tmp(2);

				/*boost::scoped_ptr<Eigen::Vector4f> ftmpInliers(new Eigen::Vector4f(fu1tmp));
				fVPHypothesisInliers.push_back(ftmpInliers);*/

				if (ii > counterMax)
				{
					std::cout<<" Something went really wrong!..."<<std::endl;
					return;
				}
				ii++;
			}
		}

		//Robust fitting the inliers using WleastSquears fit
		//Eigen::VectorXf optimized_vp_coefficients;
		LSLineFitting(fVPCandidates, fRobustEstimatedVP);
	   //collect data for 
}
int main(int argc, char *argv[])
{
	/*local variable for choice*/
	int choice = 1;

	/* initialize random seed */
	srand(time(NULL));

	/* create struct, modify size */
	struct name user;
	user.size = 16;

	/* menu prompt */
	printf("Hello, please choose 1 or 2. \n");
	while (choice != 0)
	{
		/* menu options */
		printf("1. Enter your name. \n");
		printf("2. Generate a random name. \n");
		scanf("%i", &choice);

		/* option 1 for user defined name */
		if (choice == 1)
		{
			printf("Enter your name(15 characters maximum) \n");
			printf("Any entry beyond 15 characters will be truncated. \n");
			scanf("%15s", user.userName);
			break;
			
		}
		
		/* option 2 for randomly generated name */
		if (choice == 2)
		{
			/* generate initial random 0-12 */
			int initRand = rand() % 13;

			/* 
			 *  add 3 to initial random value so range is now
			 *  3-15. I figure random names should have at least
			 *  3 characters, and the cap is 15.
			 */
			int count = initRand + 3;

			/* ticker used to concat string */
			int tick = 0;

			/* loop for string generation */
			while (count > 0)
			{
				/* 
				 *  index is random number corresponding to
				 *  the alphabet, 0-25.
				 */
				int index = rand() % 26;

				/* to store the char received from randGen */
				char inputter = randGen(index);

				/* if no chars added, copy to userName */
				if (tick == 0)
				{
					strcpy(user.userName, &inputter);
				}

				/* if character added, then concat string */
				if (tick > 0)
				{
					strcat(user.userName, &inputter);
				}

				tick++;
				count--;
			}
			break;


		}

		/* error checking for invalid input */
		else if (choice < 1 || choice > 2)
		{
			printf("Invalid Entry! Try again please. \n");
		}


	}

	/* Print name */
	printf("Your name is... %s", user.userName);
	printf("\n");

	return 0;
}
Exemplo n.º 24
0
int main (int argc, char *argv[]){
    
    //Print user info
    printf("\nAuthor : Bresia Prudente\n"
           "ACCC ID: bprude2\n\n");
    
    /**********************/
    /* PARSE COMMAND LINE */
    /**********************/
    if (argc < 7 && argc < 5) {
        printf("Usage: ./raceTest nBuffers nWorkers sleepMin sleepMax [randSeed] [-lock | -nolock]\n\n");
        exit(-1);
    }//end if
    
    //Declare and initialize variables
    int nBuffers = atoi(argv[1]);
    int nWorkers = atoi(argv[2]);
    float sleepMin = atof(argv[3]);
    float sleepMax = atof(argv[4]);
    int randSeed;
    double randomized;
    bool semLock = FALSE;
    int semid;
    int bufArr[nBuffers];  //local array initialized to zero
    double nWorkerArr[nWorkers];    //for sorting array of rand numbers

    //initializing local array
    int tmp1;
    for (tmp1 = 0; tmp1 < nBuffers; tmp1++){
        bufArr[tmp1] = 0;
    }//end for

    printf("Running simulation for %d workers accessing %d buffers, ", nWorkers, nBuffers);
    
    //Check if user enables lock or nolock
    if (argc == 7) {
        if (strcmp(argv[6], "-lock") == 0) {
            semLock = TRUE;
            printf("with locking.\n");   //sanity test
        }//end if
        else if (strcmp(argv[6], "-nolock") == 0){
            semLock = FALSE;
            printf("without locking.\n");    //sanity test
        }//end else if
    }//end if
    //if user doesn't enter a value, default to unlock
    if (argc < 7){
        semLock = FALSE;
        printf("without locking (default).\n");   //sanity test
    }//end if
    
    //Min and Max must be positive real numbers
    //min cannot be greater than max
    if (sleepMin > sleepMax) {
        printf("sleepMin cannot be greater than sleepMax!\n\n");
        exit(-1);
    }//end if
    else if((sleepMin < 0) || (sleepMax < 0)){
        printf("sleepMin and/or sleepMax values must be POSITIVE\n\n");
        exit(-1);
    }//end else if

    printf("Sleeping from %f to %f seconds.\n", sleepMin, sleepMax);
    
    //To check randSeed
    if (argc >= 5)
        randSeed = atoi(argv[5]);
    else
        randSeed = -1;  //if user enters nothing
    
    //nBuffers must be a positive prime integer less than 32
    if (nBuffers < 0) {
        printf("nBuffers must be POSITIVE\n\n");
        exit(-1);
    }//end if
    else if (nBuffers > 32){
        printf("nBuffers must be less than 32\n\n");
        exit(-1);
    }//end else if
    else if (nBuffers % 2 == 0){
        printf("%d is NOT a prime number\n\n", nBuffers);
        exit(-1);
    }//end else if

    //nWorkers must be a positive integer less than nBuffers
    if (nWorkers > nBuffers){
        printf("nWorkers must be less than nBuffers!\n\n");
        exit(-1);
    }//end if
    else if (nWorkers < 0){
        printf("nWorkers must be POSITIVE\n\n");
        exit(-1);
    }//end else if
    
    /**********************/
    /*   SET UP WORKERS   */
    /**********************/

    if (semLock){
        semid = semget(IPC_PRIVATE, nBuffers, IPC_CREAT|0600);
        if (semid < 0){
            perror("semget");
            exit(-1);
        }//end if
        union semun argVal;
        argVal.val = 1;
        int c;
        for (c = 0; c < nBuffers; c++){
            if(semctl(semid, c, SETVAL, argVal) < 0){
                perror("semctl");
                exit(-1);
            }//end if(semctl...)
        }//end for (c = 0...)
    }//end if (semLock...)
    else
        semid = -1;

    //Give each worker a random value
    printf("\n");
    int x;
    for (x = 0; x < nWorkers; x++) {
        randomized = randGen(sleepMin, sleepMax, randSeed);
        nWorkerArr[x] = randomized;
        printf("sleepTime [ %d ] = %f\n", x, randomized);    //sanity test
    }//end for
    printf("\n");
    
    struct threadStruct strand[nWorkers];   //array of M structs

    //fill up these values
    int a;
    for ( a = 0; a < nWorkers; a++){
        strand[a].nBuffers = nBuffers;
        strand[a].workerID = a + 1;
        strand[a].sleepTime = nWorkerArr[a];
        strand[a].semID = semid;
        //strand[a].semID = -1;
        strand[a].mutexID = -1;
        strand[a].buffers = bufArr;
        strand[a].nReadErrors = 0;
    }//end for

    /**********************/
    /*      THREADS       */
    /**********************/

    pthread_t isThread[nWorkers];   //create nWorker threads
    struct threadStruct *structPtr; //struct pointer
    long b;
    int rErrorCounter = 0, wErrorCounter = 0;
    
    for (b = 0; b < nWorkers; b++){
        structPtr = &strand[b]; //assign a pointer to each struct

        //create M threads
        if(pthread_create(&isThread[b], NULL, worker, (void *)structPtr) != 0){
            perror("pthread_create");
            exit(-1);
        }//end if

    }//end for

    for (b = 0; b < nWorkers; b++){
        //join threads
        if(pthread_join(isThread[b], NULL) != 0){
            perror("pthread_join");
            exit(-1);
        }//end if

        //have main increment read error counter
        if (strand[b].nReadErrors != 0){
            rErrorCounter += strand[b].nReadErrors;
        }//end if
    }//end for

    /**********************/
    /*  MAIN PRINTS MSGS  */
    /**********************/

    //examine the contents of each buffer element
    int noErrors = (int)(pow(2, nWorkers) - 1);  //no errors contains (2^nWorkers)-1
    int d;
    printf("\nAll buffers should hold %d\n\n", noErrors);   //sanity test
    for (d = 0; d < nBuffers; d++){
        printf("Buffer %d holds %d\n", d, strand->buffers[d]);  //sanity test
        if (*(strand->buffers) != noErrors){
            wErrorCounter++;
        }//end if
    }//end for
    printf("\n");

    //save the bad bits counter into an array index
    int *badBitsArr; //initialize array with write error counter as its index
    badBitsArr = (int *)malloc(sizeof(int)*wErrorCounter);
    int badBitsIndex = 0;
    int e;
    for (e = 0; e < nBuffers; e++){
        if (*(strand->buffers) != noErrors){
            badBitsArr[badBitsIndex] = e; //save into the array
            badBitsIndex++;   //increment accordingly
            //break out of it once it reaches value of write error counter
            if (badBitsIndex == wErrorCounter){
                break;
            }//end if (badBitsIndex...
        }//end if (*(strand...
        else if(wErrorCounter == 0)
            break;
    }//end for

    //now actually make error reports
    int isBadBits, shiftBadBits;
    int wErrCount = 0;
    int *badBitsArr2; 
    badBitsArr2 = (int *)malloc(sizeof(int)*32);    //calling a 32 bit int array to store some values

    //initialize unused index to -1
    int y;
    for (y = 0; y < 32; y++){
        badBitsArr2[y] = -1;
    }//end for

    //Make error reports for each buffer
    int f, g;
    for (f = 0; f < wErrorCounter; f++){
        g = badBitsArr[f];
        isBadBits = strand->buffers[g];   //put contents of found bad bits into array

        printf("Error in buffer %d. ", g); 
    
        //examine the bad bits
        shiftBadBits = (isBadBits ^ noErrors);
        int z, h = 0;;
        for (z = 0; z < 32; z++){
            if(shiftBadBits & (1 << z)){    //tests which bits are lost to overwriting
                badBitsArr2[h] = z;
                h++;
            }//end if ((shiftBadBits...
        }//end for (z = 0...

        //print out the bad bits
        int i = 0;
        printf("( Bad bits = ");
        while(i < h){
            if (i < (h-1))  //beautify it up
                printf("%d, ", badBitsArr2[i]);
            else
                printf("%d", badBitsArr2[i]);
            wErrCount++;
            i++;
        }
        printf(" )\n");

    }//end for
    printf("\n");

    //main prints the total number of errors
    printf("%d read errors and %d write errors encountered.\n\n", rErrorCounter, wErrCount);

    //detach semaphores
    if(semLock){
        if (semctl(semid, 0, IPC_RMID)){
            perror("semctl");
            exit(-1);
        }//end if (semctl...)
    }//end if(semLock)

    printf("Program exiting...\n\n");
    sleep(1);
    return 0;
    
}//end main
Exemplo n.º 25
0
int main(void) {
	

	int r = 5; //player positions
	int c = 4;
	int r2 = 80; //first ball positions
	int c2 = 120;
	int human_speed = 2; //guess what this is?
	int width = 2; //dont bother, this is the frame width
	int human_size = 10; //duh
	int size = 10; //size of computer
	int dr = 3; //speed of player
	int dc = 3; //should = dr
	int agression; //not being used right now
	int inRange = 0; //a random count variable
	int human_health = 100; //human starting health
	int comp_health = 100; //computer starting health
	int newgame = 1; //another count var
	int loopCount = 0; 
	int numAttacks = 0; //number of times human attacks
	int justAttacked; //count var for computer attacks
	int result; //count var
	int death_radius = 4; //this is how many pixels the radius around the computer is that you have to be in to attack/be attacked
	int next_var1 = 0;
	int retreat = 0;
	int retreat_length = 100; //how long it is after going in to retreat mode that you win
	int next_var2 = 0;
	int junkVar = 0;

	//prebuild the binary search tree
	//make the data in each node be a pointer to a function, then the output of that function
	//decides which node is next

	
NaryNode *root = NULL;
root = createNaryNode(createIntData(0), 0); //make the root node (check health)
  appendChild(root, createNaryNode(createIntData(1), 0)); //make the first child (if health is ok)
  appendChild(root, createNaryNode(createIntData(2), 0)); //make the second child (if health is bad)
  appendChild(root->child[0], createNaryNode(createIntData(3), 0)); //treat the first child as the root and add another child
  appendChild(root->child[1], createNaryNode(createIntData(4), 0)); //treat the first child as the root and add another child
  appendChild(root->child[1]->child[4], createNaryNode(createIntData(5), 0)); //add another child on right parent

int *tree1;
int *tree2;
int *tree3;
tree1 = (int*)(root->child[1]);
(int*)(root->child[1]) = 4;
(int*)(root->child[0]) = 2;
(int*)(root->child[1]->child[4]) = 1;

//tree1 = root->child[1];

  /*
		[root]
		/	\
	[child1] ----------child 2]
	/	   \           \      \
 [child3]  [child4]	   [child5] [child6] 
  /			/	   \
[child7]   [child8] [child9]
			|			|
		  [child9]	   [child10]
  
  
  */
  

Junk first;
first.margin = 40; //the margin for death for the computer
first.comp_health_rate = 1; //how fast the you kill the computer
first.human_health_rate = 2; //how fast the computer kills you



	while(keepGoing()) {
		

		waitForVBlank(ON);
		switch (gameState) {
			case START:
				//start mode 4
				initializeGBA(MODE_4);
				FlipPage(ON);
				paintBackground(PressEnterBitmap);
				FlipPage(OFF);
				
				
				//in to mode 3
				GBASetup();
				initializeGBA(MODE_3);
				drawBackground(6);
				while(!keyHit(BUTTON_START)){
				
					while(keyHit(BUTTON_START)){
						break;}
				}
					
				//reset all the count vars and such
					newgame = 1;
					numAttacks = 0;
					loopCount = 0;
					justAttacked = 0;
					human_health = 100; //human starting health
					comp_health = 100; //computer starting health
					next_var1 = 0;
					next_var2 = 0;
					r = 5; //player positions
					c = 4;
					r2 = 80; //first ball positions
					c2 = 120;
					gameState = PLAY;
					retreat = 0;
				
				break;
			case PLAY:

				//start mode 3
				FlipPage(OFF);
				GBASetup();

				waitForVBlank(ON);
				loopCount++;
				drawRectDMA(0, 0, 160, 240, COLOR(0,0,0)); //the black background
				
				//nary tree usage
				tree3 = (int*)(root->child[1]);
				if(tree3){
					junkVar++;
				}


				if(comp_health < first.margin){
					gameState = WIN;
				}
				
				//frame
				drawRectDMA(1, 1, 240, 1, COLOR(0,0,31)); //left bar
				drawRectDMA(159, 1, 1, 240, COLOR(0,0,31));//bottom bar
				drawRectDMA(1, 1, 240, 1, COLOR(0,0,31));//bottom bar
				drawRectDMA(159, 1, 1, 240, COLOR(0,0,31));//bottom bar
				

				//draw health bars
				if(human_health == 100){
				drawRectDMA(5, 4, 1, 1, COLOR(0,0,31)); //human starting health
				drawRectDMA(5, 6, 1, 1, COLOR(0,0,31));
				drawRectDMA(5, 8, 1, 1, COLOR(0,0,31));
				}

				if(comp_health == 100){
				drawRectDMA(5, 230, 1, 1, COLOR(31,0,0)); //computer starting health
				drawRectDMA(5, 232, 1, 1, COLOR(31,0,0));
				drawRectDMA(5, 234, 1, 1, COLOR(31,0,0));
				//newgame = 0;
				}
				
				if((human_health < 100) && (human_health > 66)){
				drawRectDMA(5, 4, 1, 1, COLOR(0,0,31)); //human health 2/3
				drawRectDMA(5, 6, 1, 1, COLOR(0,0,31));
				drawRectDMA(5, 8, 1, 1, COLOR(0,0,0));
				}

				if((human_health < 66) && (human_health >33)){
				drawRectDMA(5, 4, 1, 1, COLOR(0,0,31)); //human health 1/3
				drawRectDMA(5, 6, 1, 1, COLOR(0,0,0));
				drawRectDMA(5, 8, 1, 1, COLOR(0,0,0));
				}

				if((human_health < 33) && (human_health >0)){
				drawRectDMA(5, 4, 1, 1, COLOR(0,0,0)); //human health 0/3
				drawRectDMA(5, 6, 1, 1, COLOR(0,0,0));
				drawRectDMA(5, 8, 1, 1, COLOR(0,0,0));
				}

				
				if((comp_health < 100) && (comp_health > 66)){
				drawRectDMA(5, 230, 1, 1, COLOR(31,0,0)); //computer health 2/3
				drawRectDMA(5, 232, 1, 1, COLOR(31,0,0));
				drawRectDMA(5, 234, 1, 1, COLOR(0,0,0));
				}

				if((comp_health < 66) && (comp_health > 33)){
				drawRectDMA(5, 230, 1, 1, COLOR(31,0,0)); //computer health 1/3
				drawRectDMA(5, 232, 1, 1, COLOR(0,0,0));
				drawRectDMA(5, 234, 1, 1, COLOR(0,0,0));
				}

				if((comp_health < 33) && (comp_health > 0)){
				drawRectDMA(5, 230, 1, 1, COLOR(0,0,0)); //computer health 0/3
				drawRectDMA(5, 232, 1, 1, COLOR(0,0,0));
				drawRectDMA(5, 234, 1, 1, COLOR(0,0,0));
				}

				waitForVBlank(ON);

			
			
				//player control
				//controls the boundries and the speed
				drawRectDMA( r, c, width, width, COLOR(0,0,0));
				
				if(keyHit(BUTTON_UP)) {
					r = r - human_speed;
					if(r <= 1) r = 2;
				}
				if(keyHit(BUTTON_DOWN)) {
					r = r + human_speed;
					if(r >= 159+human_size) r = 159;
				}
				if(keyHit(BUTTON_LEFT)) {
					c = c - human_speed;
					if(c <= 1) c = 2;
				}
				if(keyHit(BUTTON_RIGHT)) {
					c = c + human_speed;
					if(c >= 239+human_size) c = 239;
				}
			
						
				//start ball code (makes ball move)
				drawRectDMA( r2, c2, size, size, COLOR(0,0,0) );
				drawRectDMA( r2, c2, size, size, COLOR(0,0,31) );
				
				//collision detection
				//walls (make ball bounce)
			
				//computer bouncing
				
			if((r2+size) > 156) dr = -dr; //top
			if((c2+size) > 236) dc = -dc; //bottom and right
			if((c2+size) < 15) dc = -dc; //left
			if(((r2) <= 3) || ((r2) >= 158)) dr = -dr; //top and bottom
			

				
				//draw player square
				
				drawRectDMA( r, c, human_size, human_size, COLOR(0,0,0));
				
	
				drawRectDMA( r, c, human_size, human_size, COLOR(0,0,31) ); //the actual square

						
				//draw bouncing ball
				drawRectDMA( r2, c2, size, size, COLOR(31,0,0));
				

				//right wall
				drawRectDMA( 1, 238, 72 , width - 1, COLOR(0,0,31) ); 
				drawRectDMA( 87, 238, 73,  width - 1, COLOR(0,0,31) ); 
				
				//keep player in boundries
				if(r < 2) {
					r = 2;
				}
				if(r+size > (159)) {
					r = (148);
				}
				if((c+size > 239)) {
					c = 228;
				}

				if((c < 2)) {
					c = 2;
				}

				//keep computer in boundries
				//the computer boundry is smaller so he doesn't get stuck in corners
				if(r2 < 10) {
					r2 = 10;
				}
				if(r2+size >= (149)) {
					r2 = (138);
				}
				
				if((c2 < 10)) {
					c2 = 10;
				}
				
				if((c2+size > 229)) {
					c2 = 218;
				}


				//BEGIN AI
				

				//if the health is low	
				if((retreatCheck(comp_health,(first.margin)))){
					//retreat
					(int*)(root->child[1]) = 1;
	
				if(r < r2){
					r2 = r2 + 1;
				}

				if(r > r2){
					r2 = r2 - 1;
				}

				if(c < c2){
					c2 = c2 + 1;
				}

				if(c > c2){
					c2 = c2 - 1;
				}
				if(keyHit(BUTTON_A)){
			retreat = retreat + 1;
				}
			}


			//nary tree usage
			tree2 = (int*)(root->child[1]);
				if(tree2){
					junkVar++;
				}



				if(attackCheck(comp_health)){ //if health is ok
					//attack
						(int*)(root->child[0]) = 1;

					if(r < r2){
						r2 = r2 - 1;
					}

					if(r > r2){
						r2 = r2 + 1;
					}

					if(c < c2){
						c2 = c2 - 1;
					}

					if(c > c2){
						c2 = c2 + 1;
					}
				
				
					//see how aggressive the human is being
					agression = numAttacks/inRange;
					//see if the human is within striking distance
						if(inRadius(c2, death_radius, c, human_size, r2, r, size)){ //this function took forever to write

						inRange++;
						result = randGen();
						if(result){
						human_health = human_health - (first.human_health_rate);
						justAttacked++;
						}
					
						//If I ever get around to implementing this, this will allow the computer to retreat
						//when the human gets too aggressive

						/*
						if(agression > .15){
				

				//retreat
					if(r < r2){
						r2 = r2 + 1;
					}

					if(r > r2){
						r2 = r2 - 1;
					}

					if(c < c2){
						c2 = c2 + 1;
					}

					if(c > c2){
						c2 = c2 = 1;
					}

				}
				
			
*/
		
				//set up the health
				//computer (computer loses health under these conditions
					
				if(keyHit(BUTTON_A)){
						comp_health = (comp_health - (first.comp_health_rate));
						numAttacks++;
						
					}
				
			}
				}

				
				if(inRadius(c2, death_radius, c, human_size, r2, r, size)){
						if(retreat >= retreat_length){
					gameState = WIN;
				break;}
						if(human_health < 33){
							gameState = DIE;
							next_var2 = 1;
							break;
						}
				}
				
				break;

			case WIN: //if they make it past level 5, display a win screen and reset some variables
					drawBackground(7);
					if(junkVar){
						newgame = 1;
					}
				retreat = 0;
				if(keyHit(BUTTON_START)) {
					gameState = CREDITS; //next stop is the credits
				
				}
				while(keyHit(BUTTON_START)) {
					while(!keyHit(BUTTON_START)) {
						
					break; }
				next_var1 = 1;}
				
			
			break;

		case CREDITS: //display the Pony Shrapnel logo
				
			if(next_var1 == 1){
				
					drawBackground(8);
					
				
				if(keyHit(BUTTON_START)) {
					gameState = START; //next stop is the start screen
				
				}
				while(keyHit(BUTTON_START)) {
					while(!keyHit(BUTTON_START)) {
					break; }
				}
				}

			

		

		
			case DIE: //if they die, then display a death screen, reset some variables, and go back to the start screen
				
				if(next_var2){
				drawBackground(1);
					if(junkVar){
						newgame = 0;
					}
				
				if(keyHit(BUTTON_START)) {
					gameState = CREDITS2; //next stop is the credits2
				
				}
				while(keyHit(BUTTON_START)) {
					while(!keyHit(BUTTON_START)) {
						
					break; }
				}
				human_health = 100;}
				
			break;


		case CREDITS2: //display the Pony Shrapnel logo
				
			while(next_var2){
				
					drawBackground(8);
					
				
				if(keyHit(BUTTON_START)) {
					gameState = START; //next stop is the start screen
					next_var2 = 0;
				}
				while(keyHit(BUTTON_START)) {
					while(!keyHit(BUTTON_START)) {
					break; }
				}
				break;}

			



				//end switch statements


		
		}

	}
	return 0;
}
Exemplo n.º 26
0
FitterResults SwarmFitterInterface::runFitter(ModelTuningParameters * startPoint) {

	int numberOfFlies = (int)(10.0+2.0*sqrt((double)toInt(fixedParams["Dimensions"])));

	showMessage("Running Swarm Optimization with " + str(numberOfFlies) + " flies\n",3,fixedParams); 

	vector< ModelTuningParameters > results; 

	int maxInformed = 3;
	double w = 1.0/(2.0*log(2.0));
	double c = 0.5 + log(2.0);
	
	double tempBestValue = 0;
	///True if tempBestValue is initialized
	bool initBest = false; 

	int numberOfRuns = toInt(fixedParams["NumberOfRuns"]);
	if (numberOfRuns < 0) crash("SwarmFitterInterface","Negative number of runs !!");

	MTRand randGen( toInt(fixedParams["Seed"]) );

	vector< SwarmFly > swarm(numberOfFlies, SwarmFly(w, c, &randGen, FixedParameters(fixedParams.getGlobals(),true)));

	vector< ModelTuningParameters > startPoints(numberOfFlies,ModelTuningParameters(*startPoint));

	ModelTuningParameters startX;
	ModelTuningParameters startY;

	//////////////////////////////////
	/// Initialize the swarm flies ///
	//////////////////////////////////
	for (int i = 0; i < numberOfFlies; i++) {
		startPoints[i] = swarm[i].calculateRandomPosition();				
	}
	
	errorValue->calculateParallelErrorValue(startPoints);
	results.insert(results.end(),startPoints.begin(),startPoints.end()); 


	for (int i = 0; i < numberOfFlies; i++) {
		swarm[i].setNewPositionErrorValue(startPoints[i]);
	}

	///////////////////////////
	/// Initialize topology ///
	///////////////////////////
	randomizeTopology(swarm, maxInformed, randGen);
	
	/////////////////////
	/// Run Algorithm ///
	/////////////////////
	vector< ModelTuningParameters > flyPositions(numberOfFlies);

	for (int i = 0; i < numberOfRuns; i++) {		
		for (int j = 0; j < numberOfFlies; j++) {
			flyPositions[j] = swarm[j].calculateNewPosition();
		}

		errorValue->calculateParallelErrorValue(flyPositions);
		results.insert(results.end(),flyPositions.begin(),flyPositions.end()); 

		for (int j = 0; j < numberOfFlies; j++) {
			swarm[j].setNewPositionErrorValue(flyPositions[j]);
		}
		showMessage( "Best solution after run " + str(i) + " : " + SwarmFly::bestGlobalSolution.toString() + " : " + str(SwarmFly::bestGlobalSolution.getErrorValue()) + "\n",2,fixedParams);
		if (SwarmFly::bestGlobalSolution.getErrorValue() < tempBestValue || !initBest) {
			tempBestValue = SwarmFly::bestGlobalSolution.getErrorValue();
			initBest = true;
		}
		else {
			showMessage("No better solution found in the last run: Randomizing swarm topology\n",3,fixedParams); 
			//randomizeWorst(swarm);
			randomizeTopology(swarm, maxInformed, randGen);
		}

	}

	return FitterResults(results);
}
Exemplo n.º 27
0
	uint32_t GenRandom(uint32_t uMin, uint32_t uMax)
	{
		static boost::random::mt19937 rng((uint32_t)std::time(0)); 
		boost::random::uniform_int_distribution<> randGen(uMin, uMax);
		return randGen(rng);
	}