Exemplo n.º 1
0
void ParticleSystem::addParticles(int min, int max, Vector position, Vector direction, int spread, int minSpeed, int maxSpeed, int minTTL, int maxTTL, sf::Color color, int size, Vector baseVelocity)
{
	int count = randomRange(min,max);

	while(count > 0){
		--count;

		//Calculating the spread dir
		direction.rotate( randomRange(-spread,spread) );
		float speed = randomRange(minSpeed, maxSpeed);

		for(int i = 0;i < PARTICLE_MAX_COUNT; ++i)
		{
			if(particles[i].ttl < 1)
			{
				particles[i].velocity = baseVelocity;
				particles[i].velocity += direction * speed;
				particles[i].ttl = randomRange(minTTL,maxTTL);
				particles[i].position = position;
				particles[i].color = color;
				particles[i].size = size;
				break;
			}
		}

	}
}
Exemplo n.º 2
0
void Enemy::move( std::vector<SDL_Rect>& otherColliders )
{
	mVelY++;

    //Move the dot left or right
    mPosX += mVelX;
    shiftColliders();

    //If the dot collided or went too far to the left or right
    if( ( mPosX < 0 ) || ( mPosX + ENEMY_WIDTH > SCREEN_WIDTH ) || checkCollision( mColliders, otherColliders ) )
    {
        //Move back
		POINTS +=100;
       mPosX = randomRange(0, SCREEN_WIDTH);
	   mVelX = 0;
	   shiftColliders();

    }

    //Move the dot up or down
    mPosY += mVelY - mPosY/2;
	shiftColliders();

    //If the dot collided or went too far up or down
    if( ( mPosY < 0 ) || ( mPosY + ENEMY_HEIGHT > SCREEN_HEIGHT ) || checkCollision( mColliders, otherColliders ) )
    {
        //Move back
		POINTS +=100;
        mPosY = randomRange(0, SCREEN_HEIGHT);
		mVelY = 0;
		shiftColliders();
    }

}
Exemplo n.º 3
0
void MainWindow::ais(void){

    TotalFitness = 0;
    ais_population.clear();

    for(int i = 0; i < COUNT; i++){
        float x = randomRange(MINX, MAXX);
        float y = randomRange(MINY, MAXY);
        this->ais_population.push_back({x, y, getFitness(x, y, false)});
        //cout << this->population[i].fitness << endl;
    }

    //sort by fitness
    sort(this->ais_population.begin(), this->ais_population.end(), by_fitness());

    int j = 0;
    while(j < COUNT){

        //clone half of population
       vector<data> ais_newpopulation(this->ais_population.begin(),(this->ais_population.begin()+(COUNT/2)));

        //mutation
        for(int i = 0; i < (COUNT/2); i++){
            float mutate = randomRange(-0.05, 0.05);
            if(mutate < 0)
                ais_newpopulation[i].fitness = ais_newpopulation[i].fitness + ((1/ais_newpopulation[i].fitness) * mutate);
            else
                ais_newpopulation[i].fitness = ais_newpopulation[i].fitness + ((1/ais_newpopulation[i].fitness) * mutate);
    //        this->ais_population.push_back({x, y, getFitness(x, y, false)});

        }

        for(int i = 0; i < 3; i++){
            float x = randomRange(MINX, MAXX);
            float y = randomRange(MINY, MAXY);
            ais_newpopulation.push_back({x, y, getFitness(x, y, false)});
            //cout << this->population[i].fitness << endl;
        }

        //merge new with old population
        ais_population.insert(ais_population.end(), ais_newpopulation.begin(), ais_newpopulation.end());

        //sort by fitness
        sort(ais_population.begin(), ais_population.end(), by_fitness());

        // erase unecessary elements/population:
        ais_population.erase(ais_population.begin()+COUNT,ais_population.end());

        //best
        ais_best.push_back(ais_population[0].fitness);

        //best
        ais_avg.push_back(ais_population[COUNT/2].fitness);

        j++;
        TotalFitness = 0;
    }

}
Exemplo n.º 4
0
void MainWindow::generatePopulations(bool isRBS){
    for(int i = 0; i < COUNT; i++){
        float x = randomRange(MINX, MAXX);
        float y = randomRange(MINY, MAXY);
        this->population.push_back({x, y, getFitness(x, y, isRBS)});
        //cout << this->population[i].fitness << endl;
    }
}
void crossover(Chromosome& chromosome1, Chromosome& chromosome2)
{
	float randomVal = randomRange(0.0f, 1.0f);
	if (randomVal < CROSSOVER_RATE) {

		int count = std::min(chromosome1.getGeneCount(), chromosome2.getGeneCount());
		int start = randomRange(0, count - 1);
		for (int i = start; i < count; ++i) {
			geneSwap(chromosome1[i], chromosome2[i]);
		}
	}
}
void mutate(Chromosome& chromosome1, Chromosome& chromosome2)
{
	for (auto& gene : chromosome1.getGeneList()) {
		if (randomRange(0.0f, 1.0f) < MUTATION_RATE) {
			gene.randomize();
		}
	}

	for (auto& gene : chromosome2.getGeneList()) {
		if (randomRange(0.0f, 1.0f) < MUTATION_RATE) {
			gene.randomize();
		}
	}
}
Exemplo n.º 7
0
 int randomRange(int rng, Range<int> range)
 {
     if(range.min == range.max)
     {
         return range.min;
     }
     return randomRange(rng, range.min, range.max, range.minInclusive, range.maxInclusive);
 }
Exemplo n.º 8
0
int Randomizer::randomBound( int lower, int upper )
{
    if ( lower > upper ) {
        int t = upper;
        upper = lower;
        lower = t;
    }
    int range = upper - lower;
    return lower + randomRange(range);
}
Individual& select(Population& population)
{
	float totalFitness = population.getTotalFitness();
	float ballPos = randomRange(0.0f, totalFitness);
	float sum = 0;
	for (auto& ind : population.getIndividualList()) {
		sum += ind.getFitness();
		if (ballPos <= sum) {
			return ind;
		}
	}
}
Exemplo n.º 10
0
static void test(FBMState state, unsigned n) {
  Addr base, limit;
  unsigned i;
  Size size;
  Bool high;
  FindDelete findDelete = FindDeleteNONE;

  BTSetRange(state->allocTable, 0, ArraySize); /* Initially all allocated */
  check(state);
  for(i = 0; i < n; i++) {
    switch(fbmRnd(3)) {
    case 0:
      randomRange(&base, &limit, state);
      allocate(state, base, limit);
      break;
    case 1:
      randomRange(&base, &limit, state);
      deallocate(state, base, limit);
      break;
    case 2:
      size = fbmRnd(ArraySize / 10) + 1;
      high = fbmRnd(2) ? TRUE : FALSE;
      switch(fbmRnd(6)) {
      case 0:
      case 1:
      case 2: findDelete = FindDeleteNONE; break;
      case 3: findDelete = FindDeleteLOW; break;
      case 4: findDelete = FindDeleteHIGH; break;
      case 5: findDelete = FindDeleteENTIRE; break;
      }
      find(state, size, high, findDelete);
      break;
    default:
      fail();
      return;
    }
    if ((i + 1) % 1000 == 0)
      check(state);
  }
}
Exemplo n.º 11
0
int Random::randomNegative(int lower)
{
	assert( lower < 0 );
	return randomRange( lower, 0 );
}
Exemplo n.º 12
0
int Random::randomPositive(int higher)
{
	assert( higher > 0 );
	return randomRange( 0, higher );
}
Exemplo n.º 13
0
//http://www.mnemstudio.org/particle-swarm-introduction.htm
//http://www.swarmintelligence.org/tutorials.php
void MainWindow::pso(void){

    //initialize particles
    this->gbest = {{0, 0}, 0};
    for(int i = 0; i < COUNT; i++){
        float x = randomRange(MINX, MAXX);
        float y = randomRange(MINY, MAXY);
        this->particle.push_back({{x, y}, NULL});
        this->lbest.push_back({{0, 0}, 0});
        this->present.push_back({{0, 0}, 0});
        //cout << "particle x:" << this->v[i].x << "particle y:" << this->v[i].y << endl;
    }


    //    While maximum iterations or minimum error criteria is not attained
    int k = 0;
    while(k < COUNT){

        for(int i = 0; i < COUNT; i++){
//            Calculate Data fitness value
              this->present[i].fitness = getFitness(this->present[i].v.x, this->present[i].v.y, false);
//            If the fitness value is better than pBest
//            {
//                Set pBest = current fitness value
//            }
              if(this->present[i].fitness > lbest[i].fitness){
//                  cout << "change in lbest" << endl;
                  lbest[i] = this->present[i];
              }
//            If pBest is better than gBest
//            {
//                Set gBest = pBest
//            }
              if(lbest[i].fitness > gbest.fitness){
//                  cout << "change in gbest" << endl;
                  gbest = lbest[i];
              }
        }

        cout << "gbest" << gbest.fitness << endl;
        pso_best.push_back(gbest.fitness);

        //problem values obtaining is bigger than limit
        for(int i = 0; i < COUNT; i++){
    //            Calculate particle Velocity
//            cout << "old v.x" << v[i].x << endl;
              particle[i].v.x = particle[i].v.x + C1 * randomRange(0, 1) * (gbest.v.x - present[i].v.x) + C2 * randomRange(0, 1) * (lbest[i].v.x - present[i].v.x);
              particle[i].v.y = particle[i].v.y + C1 * randomRange(0, 1) * (gbest.v.y - present[i].v.y) + C2 * randomRange(0, 1) * (lbest[i].v.y - present[i].v.y);

              if(particle[i].v.x < MINX)
                  particle[i].v.x = MINX;
              else if(particle[i].v.x > MAXX)
                  particle[i].v.x = MAXX;

              if(particle[i].v.y < MINY)
                  particle[i].v.y = MINY;
              else if(particle[i].v.y > MAXY)
                  particle[i].v.y = MAXY;

//              cout << "new particle.v.x" << particle[i].v.x << "new particle.v.y" << particle[i].v.x << endl;
    //            Use gBest and Velocity to update particle Data
              present[i].v.x = present[i].v.x + particle[i].v.x;
              present[i].v.y = present[i].v.y + particle[i].v.y;

              if(present[i].v.x < MINX)
                  present[i].v.x = MINX;
              else if(present[i].v.x > MAXX)
                  present[i].v.x = MAXX;

              if(present[i].v.y < MINY)
                  present[i].v.y = MINY;
              else if(present[i].v.y > MAXY)
                  present[i].v.y = MAXY;
        }


        k++;
    }


}
Exemplo n.º 14
0
void MainWindow::mutation(float x1, float y2, float x2, float y1, bool isRBS){

    float val, fit1, fit2;

    fit1 = getFitness(x1, y2, isRBS);
    fit2 = getFitness(x2, y1, isRBS);

    //for x1
    if(x1 > 0.2){
//    val = randomRange(0, 1);
//    if(val > 0.2){
        val = randomRange(-0.5, 0.5);
        if(val+x1 > MAXX)
            x1 = MAXX;
        else if(val+x1 < MINX)
            x1 = MINX;
        else
            x1 = val+x1;
    }

    //for y2
    if(y2 > 0.2){
//    val = randomRange(0, 1);
//    if(val > 0.2){
        val = randomRange(-0.5, 0.5);
        if(val+y2 > MAXY)
            y2 = MAXY;
        else if(val+y2 < MINY)
            y2 = MINY;
        else
            y2 = val+y2;
    }

    //for x2
    if(x2 > 0.2){
//    val = randomRange(0, 1);
//    if(val > 0.2){
        val = randomRange(-0.5, 0.5);
        if(val+x2 > MAXX)
            x2 = MAXX;
        else if(val+x2 < MINX)
            x2 = MINX;
        else
            x2 = val+x2;
    }

    //for y1
    if(y1 > 0.2){
//    val = randomRange(0, 1);
//    if(val > 0.2){
        val = randomRange(-0.5, 0.5);
        if(val+y1 > MAXY)
            y1 = MAXY;
        else if(val+y1 < MINY)
            y1 = MINY;
        else
            y1 = val+y1;
    }

//    newpopulation.push_back({x1, y2, fit1});
//    newpopulation.push_back({x2, y1, fit2});

    newpopulation.push_back({x1, y2, getFitness(x1, y2, isRBS)});
    newpopulation.push_back({x2, y1, getFitness(x2, y1, isRBS)});

}
Exemplo n.º 15
0
void MainWindow::on_FPS_clicked()
{

    //initial graph
    graphs gr;
    gr.setModal(true);

    int k = 0;
    while(k < COUNT){

        TotalFitness = 0;
        population.clear();
        newpopulation.clear();

        generatePopulations(false);

        //sort by fitness
        sort(this->population.begin(), this->population.end(), by_fitness());

        int j = 0;
        while(j < COUNT){

            calc_prob_ranges(false);

            //offsprings
            for(int i=0; i<((COUNT/2)/2); i++){
                float val = randomRange(0, 1);
                temp = generateOffspring(val);

                offsprint_x1 = temp.x;
                offsprint_y1 = temp.y;

                val = randomRange(0, 1);
                temp = generateOffspring(val);

                offsprint_x2 = temp.x;
                offsprint_y2 = temp.y;

                //mutation process
                mutation(offsprint_x1, offsprint_y2, offsprint_x2, offsprint_y1, false);
            }

            //merge new with old population
            population.insert(population.end(), newpopulation.begin(), newpopulation.end());

            //clear new population
            newpopulation.clear();

            //sort by compute
            sort(population.begin(), population.end(), by_fitness());

            // erase unecessary elements/population:
            population.erase(population.begin()+COUNT,population.end());

            //cout << "population for new iteration" << endl;
            TotalFitness = 0;
            for(int i=0; i < population.size(); i++ ){
                TotalFitness = TotalFitness + population[i].fitness;
                //cout << population[i].x << "," << population[i].y << "," << population[i].fitness << endl;
            }

            //best of iteration
            best.push_back(population[0].fitness);
            //cout << "fps best" << population[0].fitness << endl;
            //avg of iteration
            avg.push_back(population[(COUNT/2)-1].fitness);

            j++;

        }
        k++;
        TotalFitness = 0;
        pso();
        ais();
        gr.data.push_back({best, avg, pso_best, ais_best, ais_avg,COUNT});
        reverse(pso_best.begin(), pso_best.end());
        reverse(ais_best.begin(), ais_best.end());
        reverse(ais_avg.begin(), ais_avg.end());
        reverse(best.begin(), best.end());
        reverse(avg.begin(), avg.end());
        best_best.push_back(best[0]);
        avg_avg.push_back(avg[0]);
        ais_avg_avg.push_back(ais_avg[0]);
        pso_bb.push_back(pso_best[0]);
        pso_best.clear();
        ais_bb.push_back(ais_best[0]);
        ais_best.clear();
        ais_avg.clear();
        best.clear();
        avg.clear();
    }

    gr.data.push_back({best_best,avg_avg, pso_bb, ais_bb, ais_avg_avg,COUNT});
    best_best.clear();
    avg_avg.clear();
    ais_bb.clear();
    pso_bb.clear();
    ais_avg_avg.clear();

//    for(int i=0; i < COUNT; i++ ){
//        gr.best.push_back({best[i].fitness});
//        gr.avg.push_back({avg[i].fitness});
//    }
//        cout << gr.best.size() << endl;

//    gr.generation = COUNT;


    gr.makePlot(0);

    gr.exec();

}
Exemplo n.º 16
0
extern int main(int argc, char *argv[])
{
  unsigned i;
  Addr base, limit;
  mps_arena_t mpsArena;
  Arena arena; /* the ANSI arena which we use to allocate the BT */
  CBSStruct cbsStruct;
  CBS cbs;
  void *p;
  Addr dummyBlock;
  BT allocTable;
  Size size;
  Bool high;
  CBSFindDelete findDelete = CBSFindDeleteNONE;

  randomize(argc, argv);

  NAllocateTried = NAllocateSucceeded = NDeallocateTried =
    NDeallocateSucceeded = NNewBlocks = NDeleteBlocks =
    NGrowBlocks = NShrinkBlocks = 0;

  clearExpectations();

  die(mps_arena_create(&mpsArena, mps_arena_class_vm(), testArenaSIZE),
      "mps_arena_create");
  arena = (Arena)mpsArena; /* avoid pun */

  die((mps_res_t)BTCreate(&allocTable, arena, ArraySize),
      "failed to create alloc table");

  die((mps_res_t)CBSInit(arena, &cbsStruct, NULL, &cbsNewCallback,
                         &cbsDeleteCallback, &cbsGrowCallback,
                         &cbsShrinkCallback, MinSize,
                         Alignment, TRUE, TRUE),
      "failed to initialise CBS");
  cbs = &cbsStruct;

  BTSetRange(allocTable, 0, ArraySize); /* Initially all allocated */

  /* We're not going to use this block, but I feel unhappy just */
  /* inventing addresses. */
  die((mps_res_t)ControlAlloc(&p, arena, ArraySize * Alignment,
                              /* withReservoirPermit */ FALSE),
      "failed to allocate block");
  dummyBlock = (Addr)p; /* avoid pun */

  printf("Allocated block [%p, %p)\n", (void*)dummyBlock,
         (char *)dummyBlock + ArraySize);

  checkCBS(cbs, allocTable, dummyBlock);
  for(i = 0; i < NOperations; i++) {
    switch(cbsRnd(3)) {
    case 0: {
      randomRange(&base, &limit, allocTable, dummyBlock);
      allocate(cbs, dummyBlock, allocTable, base, limit);
    } break;
    case 1: {
      randomRange(&base, &limit, allocTable, dummyBlock);
      deallocate(cbs, dummyBlock, allocTable, base, limit);
    } break;
    case 2: {
      size = cbsRnd(ArraySize / 10) + 1;
      high = cbsRnd(2) ? TRUE : FALSE;
      switch(cbsRnd(6)) {
      case 0:
      case 1:
      case 2: findDelete = CBSFindDeleteNONE; break;
      case 3: findDelete = CBSFindDeleteLOW; break;
      case 4: findDelete = CBSFindDeleteHIGH; break;
      case 5: findDelete = CBSFindDeleteENTIRE; break;
      }
      find(cbs, dummyBlock, allocTable, size, high, findDelete);
    } break;
    }
    if (i % 5000 == 0)
      checkCBS(cbs, allocTable, dummyBlock);
  }

  checkExpectations();

  /* CBSDescribe prints a very long line. */
  /* CBSDescribe(cbs, mps_lib_get_stdout()); */

  printf("\nNumber of allocations attempted: %ld\n", NAllocateTried);
  printf("Number of allocations succeeded: %ld\n", NAllocateSucceeded);
  printf("Number of deallocations attempted: %ld\n", NDeallocateTried);
  printf("Number of deallocations succeeded: %ld\n", NDeallocateSucceeded);
  printf("Number of new large blocks: %ld\n", NNewBlocks);
  printf("Number of deleted large blocks: %ld\n", NDeleteBlocks);
  printf("Number of grown large blocks: %ld\n", NGrowBlocks);
  printf("Number of shrunk large blocks: %ld\n", NShrinkBlocks);
  printf("\nNo problems detected.\n");
  return 0;
}
int main(void)
{
  srand( time( NULL ) );
  char op;
  double double1;
  double double2;
  int int1;
  int int2;

  printf( "%s\n", "add          ( + )   + double double" );
  printf( "%s\n", "subtract     ( - )   - double double" );
  printf( "%s\n", "multiply     ( * )   * double double" );
  printf( "%s\n", "divide       ( / )   / double double" );
  printf( "%s\n", "power        ( ^ )   ^ double int" );
  printf( "%s\n", "exponential  ( e )   e int" );
  printf( "%s\n", "factorial    ( ! )   ! int" );
  printf( "%s\n", "random range ( r )   r int int" );
  printf( "%s\n", "sum range    ( s )   s int int" );
  printf( "%s\n", "round        ( ~ )   ~ double" );
  printf( "%s\n", "roundup      ( ' )   ` double" );
  printf( "%s\n", "rounddown    ( _ )   _ double" );
  printf( "%s\n", "minimum      ( < )   < double double" );
  printf( "%s\n", "maximum      ( > )   > double double" );
  printf( "%s\n", "quit         ( q )   q" );
  
  do
  {
    scanf( " %c", &op );
    switch ( op )
    {
      case '+':
        scanf( "%lf%lf", &double1, &double2 );
        printf( "%.2f\n", double1 + double2 );
        break;
      
      case '-':
        scanf( "%lf%lf", &double1, &double2 );
        printf( "%.2f\n", double1 - double2 );
        break;

      case '*':
        scanf( "%lf%lf", &double1, &double2 );
        printf( "%.2f\n", double1 * double2 );
        break;
      
      case '/':
        scanf( "%lf%lf", &double1, &double2 );
        if ( double2 != 0 )
        {
          printf( "%.2f\n", double1 / double2 );
        }
        else
        {
          printf( "%s\n", "Error: Dividing by 0" );
        }
        break;
      
      case '^':
        scanf( "%lf%d", &double1, &int1 );
        printf( "%.4f\n", power( double1, int1 ) );
        break;

      case 'e':
        scanf( "%d", &int1 );
        printf( "%lf\n", power( 2.71828182846, int1 ) );
        break;
      
      case '!':
        scanf( "%d", &int1 );
        printf( "%d\n", factorial( int1 ) );
        break;

      case 'r':
        scanf( "%d%d", &int1, &int2 );
        printf( "%d\n", randomRange( int1, int2 ) );
        break;

      case 's':
        scanf( "%d%d", &int1, &int2 );
        printf( "%d\n", sumRange( int1, int2 ) );
        break;      

      case '~':
        scanf( "%lf", &double1 );
        printf( "%d\n", roundDouble( double1 ) );
        break;

      case '`':
        scanf( "%lf", &double1 );
        printf( "%d\n", (int) double1 + 1 );
        break;

      case '_':
        scanf( "%lf", &double1 );
        printf( "%d\n", (int) double1 );
        break;

      case '<':
        scanf( "%lf%lf", &double1, &double2 );
        if ( double1 < double2 )
        {
          printf( "%.2f\n", double1 );
        }
        else
        {
          printf( "%.2f\n", double2 );
        }
        break;

      case '>':
        scanf( "%lf%lf", &double1, &double2 );
        if ( double1 > double2 )
        {
          printf( "%.2f\n", double1 );
        }
        else
        {
          printf( "%.2f\n", double2 );
        }
        break;

      case 'q':
        printf( "%s\n", "Good-bye." );
        break;

      default:
        printf( "%s\n", "Invalid input." );
        break; 
    }
  }
  while(op !='q');
}
void HelloWorld::updateGame(float dt) {

    _gameTime += dt; //Add dt to game time

    //Background Scrolling
    if (_accelerate) { //accelerate
        //Move the scroll axis at scroll speed
        _scrollAxis -= _scrollSpeed;

        //if we have scrolled through both backgrounds reset scroll axis
        if (_scrollAxis <= -_winHeight) {
            _scrollAxis = 0;
        }

        //update positions for the background sprites as per the scrollAxis
        _background1->setPosition(ccp(0.0f,_scrollAxis));
        _background2->setPosition(ccp(0.0f,_scrollAxis+_winHeight));

        //Keep increasing the scroll speed until we approach the max
        if (_scrollSpeed < MAX_SCROLL_SPEED) {
            _scrollSpeed += 0.1;
        }
    } else { //decelerate
        //Move the scroll axis at scroll speed
        _scrollAxis -= _scrollSpeed;

        //if we have scrolled through both backgrounds reset scroll axis
        if (_scrollAxis <= -_winHeight) {
            _scrollAxis = 0;
        }
        //Keep decreasing the scroll speed until we approach reach 0
        if (_scrollSpeed > 0) {
            _scrollSpeed -= 0.1;
            _background1->setPosition(ccp(0.0f,_scrollAxis));
            _background2->setPosition(ccp(0.0f,_scrollAxis+_winHeight));
        }
    }

    //Update player position based on accelerometer values
        CCPoint location;
        location = ccp(_player->getPositionX()+_aX * ACC_ADJUST_FACTOR,_player->getPositionY());

        //Bound the ship location to size of the screen width so we don't go off the screen
        if (location.x> (_origin.x + _player->getContentSize().width/2 * _player->getScaleX()) && location.x < (_winWidth - _player->getScaleX()*_player->getContentSize().width/2)){
            _player->setPosition(location);

        }


        //Spawn Asteroids
        _asteroidSpawnTime +=dt;
        if (_asteroidSpawnTime > ASTEROID_SPAWN_INTERVAL && _gameTime>ASTEROID_SPAWN_START && _gameTime<ASTEROID_SPAWN_END) {
        	_asteroidSpawnTime = 0;
        	//Scale the asteroid randomly before spawning it
        	float randnum = randomRange(0.1f,0.25f);
        	_asteroids[_asteroidCount]->setScaleX(randnum);
        	_asteroids[_asteroidCount]->setScaleY(randnum);

        	//Spawn at a random X position based on the screen width
        	float positionX = randomRange(_asteroids[_asteroidCount]->getContentSize().width/2 * _asteroids[_asteroidCount]->getScaleX(),_winWidth-_asteroids[_asteroidCount]->getContentSize().width/2 * _asteroids[_asteroidCount]->getScaleX());
        	_asteroids[_asteroidCount]->stopAllActions();
        	_asteroids[_asteroidCount]->setPosition(ccp(positionX,(_winHeight+_asteroids[_asteroidCount]->getScaleY()*_asteroids[_asteroidCount]->getContentSize().height)));
        	_asteroids[_asteroidCount]->setVisible(true);

        	//Create a random time [2.0,8.0] seconds move action for the asteroid
        	_asteroids[_asteroidCount]->runAction(CCSequence::create(CCMoveTo::create(randomRange(2.0f,8.0f), ccp(_asteroids[_asteroidCount]->getPositionX(),_origin.y-_asteroids[_asteroidCount]->getContentSize().height)),CCCallFuncN::create(this,callfuncN_selector(HelloWorld::spriteMoveFinished)),NULL));
        	++_asteroidCount;

        	//If have used up all available sprites reset the count to reuse the sprites
        	if (_asteroidCount>=NUM_ASTEROIDS) {
        		_asteroidCount = 0;
        	}
        }

        //Spawn Enemy 5 seconds after spawning the last asteroid
        if (_gameTime>ASTEROID_SPAWN_END+5.0f && !_spawnEnemy) {
        	//Stop backgrond scrolling
        	//_accelerate = false;
        	CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("enemy_background_music.ogg",true);
        	_enemy->setVisible(true);

        	//Reposition Player
        	CCMoveTo *playerMove = CCMoveTo::create(1.5, ccp(_winWidth/2, _winHeight/2+_player->getContentSize().height*_player->getScaleY()));
        	_player->runAction(CCSequence::create(playerMove,NULL));

        	//Bring in the Enemy with a move action
        	CCMoveTo *enemyMove = CCMoveTo::create(1.5, ccp(_winWidth/2, _origin.y+_enemy->getContentSize().height*_enemy->getScaleY()/2));
        	_enemy->runAction(CCSequence::create(enemyMove,CCCallFuncN::create(this,callfuncN_selector(HelloWorld::enemyMoveFinished)),NULL));
        	_spawnEnemy = true;
        }


        //Collision detection Asteroid<->Player, Asteroid<->Player projectiles
		for (int i = 0; i < NUM_ASTEROIDS; ++i) {            //We only need to check collisions if the current Asteroid and Player are visible
			if (_asteroids[i]->isVisible() && _player->isVisible()) {
				if (_asteroids[i]->boundingBox().intersectsRect(_player->boundingBox())) {
					--_playerHealth;
					CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("explode.wav");
					if (_playerHealth <=0) {
						_player->stopAllActions();
						_player->setVisible(false);
						//Destroy Player spaceship with a sound effect and a custom exploding ring particle effect
						ccColor4F startColor = {0.4f, 0.5f, 1.0f, 1.0f};
						createParticleEffect("Particles/ExplodingRing.plist",_player->getPositionX(),_player->getPositionY(),startColor,1.0f,100.0f);
						CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("explode_ship.wav");
					} else {
						_asteroids[i]->setVisible(false);
						//Create an exploding ring particle effect for the Asteroid destruction
						createParticleEffect("Particles/ExplodingRing.plist",_asteroids[i]->getPositionX(),_asteroids[i]->getPositionY());
						//Create a blinking effect signifying player ship damage
						CCBlink *blinkAction = CCBlink::create(1.0f,10);
						CCShow *showAction = CCShow::create();
						CCSequence *action = CCSequence::create(blinkAction,showAction,NULL);
						_player->runAction(action);
					}
				}

				//For each Player projectile check for collision with the current asteroid
				for (int j = 0; j < MAX_PLAYER_PROJECTILES; ++j) {
					if (_playerProjectiles[j]->isVisible()) {
						if (_playerProjectiles[j]->boundingBox().intersectsRect(_asteroids[i]->boundingBox())) {
							_asteroids[i]->setVisible(false);
							_playerProjectiles[j]->setVisible(false);
							createParticleEffect("Particles/ExplodingRing.plist",_asteroids[i]->getPositionX(),_asteroids[i]->getPositionY());
							CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("explode.wav");
						}
					}
				}
			}
		}

}
Exemplo n.º 19
0
void World::updateFixed() {
	//This update function is run at a fixed rate

	//Check if player is dead
	b2Vec2 playerPos = playerBody->GetPosition();
	playerPos *= M2P;

	if (playerPos.x < DEATH_WALL_SPACE) {
		lost = true;
	}

	//If not game over
	if (!lost) {
		//Update puzzles
		if (!inProgress) {
			//If too far on right side
			float scale = 1920.0 / screenwidth;
			int speedBorder = (-camOffX) + (CAMERA_SPEEDUP_RANGE / scale);
			if (playerPos.x >= speedBorder) {
				//Speedup camera
				cameraSpeed += 0.1;
			}
			else {
				//Use normal speed
				cameraSpeed = newSpeed;
			}

			if (startPuzzle()) {
				inProgress = true;
			}
		}
		else {
			if (endPuzzle()) {
				inProgress = false;
				puzzlesSolved++;

				//Spawn new
				int randomPuzzleId = randomRange(1, 4);
				setPuzzle(randomPuzzleId);

				//Spawn particles for bonus
				//int offX = puzzles->at(puzzleId)->getSpawn() + 200;
				//int offY = 150;
				//spawnGroundParticles(10, b2Vec2(offX, offY), 30);
			}
		}

		//Add camera movement
		if (cameraSpeed) {
			b2Vec2 cameraPos = b2Vec2(cameraSpeed, 0);
			cameraPos *= P2M;
			world->ShiftOrigin(cameraPos);
		
			//Update spawn orgin
			spawnX -= cameraSpeed;

			if (puzzlesSolved) {
				score++;
			}

			//Update puzzle orgin
			puzzles->at(puzzleId)->shiftOrginX(-cameraSpeed);
		}

		//Refresh position of pushwall
		b2Body *invWall = platforms->at(0);
		int invX = (DEATHWALL_SIZE / 2) + 100;
		int invY = (-camOffY) + (FLOOR / 2);
		b2Vec2 moveTo = b2Vec2(invX, invY);
		moveTo *= P2M;
		invWall->SetTransform(moveTo, 0.0);
	}
}