Пример #1
0
protected func FlyProcess() {
	Smoke(0, 0, 7 + Random(5));
	if (Stuck() || (GetActTime() > 150))
		return(Hit());
}
Пример #2
0
void DistributionBranch::MutateAttributes()
{
	Random(1);
	return;
}
Пример #3
0
int main(int argc, char **argv) {

//Initialization: Read in particle locations.  Also add function for random init, latttice init, and lattice init with perturb. Add velocities!

    FILE* input_file;

    if ((input_file = fopen(argv[1],"r"))==NULL) {
        printf("Error opening %s\n",argv[1]);
        return 1;
    }

//open file -> change to read initial configuration from LAMMPS or XYZ files

    fscanf(input_file,"%d %*[^\n]", &N); //number of particles
    fscanf(input_file,"%d %*[^\n]", &init_type); //initialization type
    fscanf(input_file,"%lf %*[^\n]", &L); //length of box  - box extends in 3 dim from -L/2 to +L/2
    fscanf(input_file,"%d %*[^\n]", &ntypes); //number of particle types
    fscanf(input_file,"%lf %*[^\n]", &timestep); //delta t
    fscanf(input_file,"%d %*[^\n]", &nsteps); //number of timesteps
    fscanf(input_file,"%lf %*[^\n]", &epsilon_scale); //epsilon_scale
    fscanf(input_file,"%lf %*[^\n]", &T_in); //initial tempertaure

    L2 = L/2;

    double* epsilontemp;
    double* sigmatemp;

    if((p = (struct atom*)malloc(N*sizeof(struct atom)))==NULL) {
        printf("Could not allocate array of particles\n");
        return 1;
    }

    if((npertype = (int*)malloc(ntypes*sizeof(int)))==NULL) {
        printf("Could not allocate array of type counts\n");
        return 1;
    }

    if((epsilontemp = (double*)malloc(ntypes*sizeof(double)))==NULL) {
        printf("Could not allocate array of epsilons\n");
        return 1;
    }

    if((epsilon = (double**)malloc(ntypes*sizeof(double*)))==NULL) {
        printf("Could not allocate array of epsilons\n");
        return 1;
    }

    if((sigmatemp = (double*)malloc(ntypes*sizeof(double)))==NULL) {
        printf("Could not allocate array of sigmas\n");
        return 1;
    }

    if((sigma2 = (double**)malloc(ntypes*sizeof(double*)))==NULL) {
        printf("Could not allocate array of sigmas\n");
        return 1;
    }

    int i=0;

    for (i=0; i<ntypes; i++) {
        if((epsilon[i] = (double*)malloc(ntypes*sizeof(double)))==NULL) {
            printf("Could not allocate array of epsilons\n");
            return 1;
        }
        if((sigma2[i] = (double*)malloc(ntypes*sizeof(double)))==NULL) {
            printf("Could not allocate array of sigmas\n");
            return 1;
        }
    }

    if((m = (double*)malloc(ntypes*sizeof(double)))==NULL) {
        printf("Could not allocate array of masses\n");
        return 1;
    }


    int j,k=0;
    double mave = 0.0;//average mass

    for (i=0; i<ntypes; i++) {
        fscanf(input_file,"%d %*[^\n]", &npertype[i]);
        fscanf(input_file,"%lf %*[^\n]", &sigmatemp[i]);
        fscanf(input_file,"%lf %*[^\n]", &epsilontemp[i]);
        fscanf(input_file,"%lf %*[^\n]", &m[i]);
        mave+=npertype[i]*m[i];

        for(j=0; j<npertype[i]; j++) {
            p[k].type = i;
            k++;
        }
    }

    for (i=0; i<ntypes; i++) {
        for (j=0; j<ntypes; j++) {
            sigma2[i][j] = pow((sigmatemp[i]+sigmatemp[j])/2.0,2);
            epsilon[i][j] = (sqrt(epsilontemp[i]*epsilontemp[j]));
        }
    }

    free(sigmatemp);
    free(epsilontemp);

    mave = mave/N;

    printf("Initializing positions...");

    if (init_type == 0 ) { //Test on one particle - put it in the middle of the box.
        for(i=0; i<N; i++) {
            p[i].x=0.0;
            p[i].y=0.0;
            p[i].z=0.0;
        }
    }

    if(init_type == 1) { //Complete this for LAMMPS - style frame

        printf("Initialization type not yet implemented");
        return 1;
        FILE* input_coords_file;

        if ((input_coords_file = fopen(argv[1],"r"))==NULL) {
            printf("Error opening %s\n",argv[1]);
            return 1;
        }
        fclose(input_coords_file);

    }

    if(init_type == 2) { //Random
        initializeRand(N,L);
    }

    if(init_type == 3) { //Lattice
        initializeLattice(N,L);
    }

    if(init_type == 4) { //LAttice plus perturb.

        printf("Initialization type not yet implemented");
        return 1;
    }


    //Initialize forces

    for (i=0; i<N; i++) {
        p[i].fx = 0.0;
        p[i].fy = 0.0;
        p[i].fz = 0.0;
    }

    printf("Initializing velocities...");


    //Randomly assign velocities from continous distribution [-vrange,+vrange], compute total velocity and correct momentum.

    //Calculate vrange from input T assuming uniform distribution


    T = T_in/epsilon_scale; //some base epsilon, all epsilons in epsilon array are multiples of this epsilon_scale.
    double vrange = sqrt(T*2.0/mave); //Vrange is range of the uniform distribution with rms v^2, solve using KE = 3NT/2 = 3Nmvrange^2/4 from v_ave = (2vrange)^2/12. Using averge mass: is this correct?

    double mass, vx, vy, vz, sumpx, sumpy, sumpz;
    sumpx = 0.0;
    sumpy = 0.0;
    sumpz = 0.0;

    for (i=0; i<N; i++) {
        mass = m[(p[i].type)];

        vx = (Random()*vrange*2.0) - vrange;
        p[i].xold = p[i].x-(vx*timestep);
        sumpx+=vx*mass;

        vy = (Random()*vrange*2.0) - vrange;
        p[i].yold = p[i].y-(vy*timestep);
        sumpy+=vy*mass;

        vz = (Random()*vrange*2.0) - vrange;
        p[i].zold = p[i].z-(vz*timestep);
        sumpz+=vz*mass;

    }

    //The following obviously does not work for 1 particle test simulation or it will not move. Rather, it does work and the particle therefore does not move.

    if (fabs(sumpx)>ptol) { //If total momentum is not zero, correct all velocities by v_tot/N
        sumpx = sumpx/N;
        for(i=0; i<N; i++) {
            vx = ((p[i].x - p[i].xold)/timestep) - sumpx;
            p[i].xold = p[i].x-(vx*timestep);
        }
    }

    if (fabs(sumpy)>ptol) {
        sumpy = sumpy/N;
        for(i=0; i<N; i++) {
            vy = ((p[i].y - p[i].yold)/timestep) - sumpy;
            p[i].yold = p[i].y-(vy*timestep);
        }
    }

    if (fabs(sumpz)>ptol) {
        sumpz = sumpz/N;
        for(i=0; i<N; i++) {
            vz = ((p[i].z - p[i].zold)/timestep) - sumpz;
            p[i].zold = p[i].z-(vz*timestep);
        }
    }

    FILE* xyz_file;

    if ((xyz_file = fopen(argv[2],"w"))==NULL) {
        printf("Error opening xyz file\n");
        return 1;
    }

    fprintf(xyz_file, "%d\n Initial configuration\n", N);

    for(i=0; i<N; i++) {
        fprintf(xyz_file,"%5d %13lf %13lf %13lf\n", p[i].type, p[i].x, p[i].y, p[i].z);
    }

    //Contents of main loop

    printf("Beginning simulation...");

    int iter;

    for (iter = 0; iter<nsteps; iter++) { //run for desired number of time steps

        printf("%d\t",iter);

        //Force Computation (function), using minimum image, with cutoff rc(?). Compute P in here, but separate function. Compute U in here. Put in a function.

        double pix, piy, piz, pifx, pify, pifz, xij, yij, zij, rij, rij2, epsilonij, sr2, sr6, sr12, fij, factor, PE=0.0;
        int ptype;
        for (i=0; i<N; i++) {
            pix = p[i].x;
            piy = p[i].y;
            piz = p[i].z;
            pifx = 0.0; //add to force for particle i
            pify = 0.0;
            pifz = 0.0;
            ptype = p[i].type;


            for (j=i+1 ; j<N; j++) {

                xij = pix - p[j].x;
                if (xij>L2) { //Minimum image condition -> Need to use absolute value here! But also maintain sign of vector
                    xij = xij - L;
                }
                else if (xij<-L2) {
                    xij = xij + L;
                }
                yij = piy - p[j].y;
                if (yij>L2) {
                    yij = L-yij;
                }
                else if (yij<-L2) {
                    yij = yij + L;
                }
                zij = piz - p[j].z;
                if (zij>L2) {
                    zij = L-zij;
                }
                else if (zij<-L2) {
                    zij = zij + L;
                }

                rij2 = (xij*xij)+(yij*yij)+(zij*zij);
                rij = sqrt(rij2);
                epsilonij = epsilon[(p[i].type)][(p[j].type)];
                sr2 = sigma2[(p[i].type)][(p[j].type)]/rij2;
                sr6 = sr2*sr2*sr2;
                sr12 = sr6*sr6;
                fij = (-24.0*epsilonij/rij2)*(2*sr12-sr6); //magnitude of force

                PE = PE + epsilonij*(sr12 - sr6); //add potential to total potential

                factor = fij/rij;
                xij = factor*xij; //get vectors
                yij = factor*yij;
                zij = factor*zij;
                pifx+=xij; //add to force for particle i
                pify+=yij;
                pifz+=zij;
                p[j].fx -= pifx; //add negative force to force on jth particle since fij = -fji -> DO need to "double-count" forces
                p[j].fy -= pify;
                p[j].fz -= pifz;
            }
            p[i].fx += pifx;
            p[i].fy += pify;
            p[i].fz += pifz;
        }

        PE = 4.0*PE;


        //Integration: Verlet integrator.  Compute KE in here and T in here.

        double xnew, ynew, znew, mass, vx, vy, vz, KE, KEsumm=0.0, sumvsq;
        double dtsq = timestep*timestep;
        double dt2 = 2*timestep;

        sumpx = 0.0;
        sumpy = 0.0;
        sumpz = 0.0;
        sumvsq = 0.0;

        for (i=0; i<N; i++) {
            mass = m[(p[i].type)];
            factor = dtsq/mass;
            xnew = 2.0*p[i].x - p[i].xold + factor*p[i].fx;
            ynew = 2.0*p[i].y - p[i].yold + factor*p[i].fy;
            znew = 2.0*p[i].z - p[i].zold + factor*p[i].fz;

            vx = (xnew - p[i].xold)/dt2;
            vy = (ynew - p[i].yold)/dt2;
            vz = (znew - p[i].zold)/dt2;

            sumvsq = sumvsq + mass*(vx*vx + vy*vy + vz*vz);

            sumpx+=vx*mass;
            sumpy+=vy*mass;
            sumpz+=vz*mass;

            //PBC


            while (xnew < -L2) {
                xnew = xnew + L;
            }
            while (xnew>L2) {
                xnew = xnew - L;
            }

            while (ynew < -L2) {
                ynew = ynew + L;
            }
            while (ynew>L2) {
                ynew = ynew - L;
            }

            while (znew < -L2) {
                znew = znew + L;
            }
            while (znew>L2) {
                znew = znew - L;
            }

            p[i].xold = p[i].x;
            p[i].yold = p[i].y;
            p[i].zold = p[i].z;

            p[i].x = xnew;
            p[i].y = ynew;
            p[i].z = znew;
        }

        //Compute KE and T

        KE = 0.5*sumvsq; //reduced energy = KE/epsilon
        KEsumm += KE; //To get ensemble average?
        T = 2.0*KE/(3.0*N); //reduced temperature = kbT/epsilon


        //Output (positions for frame)

        fprintf(xyz_file, "%5d\n%5d\n", N, iter);

        for(i=0; i<N; i++) {
            fprintf(xyz_file,"%5d %13lf %13lf %13lf\n", p[i].type, p[i].x, p[i].y, p[i].z);
        }

        // fprintf(output, "%5d %13lf %13lf %13lf %13lf", iter, KE_out, PE_out, T_out, pressure_out);

    }

    printf("\nWrapping up...");

    fclose(xyz_file);
    //Final output here


    free(p);
    free(epsilon);
    free(sigma2);
    free(m);

    return 0;
}
Пример #4
0
protected func Shiver()
{
    // Bewegung
    SetXDir(Random(21) - 10);
    return(1);
}
Пример #5
0
int main () {

  int i, j, n, r, p, deckCount, discardCount, handCount, handPos, randomCard, randomHandCount;

  int k[10] = {adventurer, council_room, feast, gardens, mine,
	       remodel, smithy, village, baron, great_hall};

  struct gameState G;

  printf ("Testing CARD SMITHY.\n");

  SelectStream(2);
  PutSeed(3);

  for (n = 0; n < 1; n++) {
    for (i = 0; i < sizeof(struct gameState); i++) {
      ((char*)&G)[i] = floor(Random() * 256);
    }
    p = floor(Random() * 2);
    randomHandCount = floor(Random() * MAX_HAND);

    G.deckCount[p] = floor(Random() * MAX_DECK);
    G.discardCount[p] = floor(Random() * MAX_DECK);
    G.handCount[p] = randomHandCount;

    /* initialize hand */

    // give the player real cards
    for ( j=0; j< randomHandCount; j++)
    {
      G.hand[p][j] = 0;
      randomCard = floor(Random() * 3);
      switch (randomCard) {
        case 0:
          G.hand[p][j] = copper;
          break;
        case 1:
          G.hand[p][j] = silver;
          break;
        case 2:
          G.hand[p][j] = gold;
          break;
      }
    }
    /* player two now has real cards */
    for ( j=0; j< randomHandCount; j++)
    {
      G.hand[1-p][j] = 0;
      randomCard = floor(Random() * 3);
      switch (randomCard) {
        case 0:
          G.hand[1-p][j] = copper;
          break;
        case 1:
          G.hand[1-p][j] = silver;
          break;
        case 2:
          G.hand[1-p][j] = gold;
          break;
      }
    }
    G.whoseTurn = 0;
    handPos = 0;

    handPos = 5;

    G.deckCount[p] = 40;
    G.discardCount[p] = 10;
    G.handCount[p] = 8;
    G.discard[p][G.discardCount[p]] = 100;
    G.playedCardCount = 3;
    G.playedCards[ G.playedCardCount ] = G.hand[p][handPos-1];

    r = checkSmithy(&G, handPos, p);


  }
  printf ("ALL TESTS OK FOR SMITHY \n\n");
  exit(0);
  return 0;
}
Пример #6
0
  void 
  ReptationMC::moveReptile(){
    
    //RealType oneovertau = 1.0/Tau;
    //RealType oneover2tau = 0.5*oneovertau;
    RealType tauover2 = 0.5*Tau;
    RealType g = sqrt(Tau);
    
    typedef MCWalkerConfiguration::PropertyContainer_t PropertyContainer_t;
    if(!UseBounce && Random()<0.5) {
      Reptile->flip(); 	  
      NumTurns++;
    }

    Walker_t* anchor = Reptile->makeEnds();
      
    //save the local energies of the anchor and tails
    //eloc_xp = the energy of the front
    //eloc_yp = the energy of the proposed move
    //eloc_x = the energy of the tail
    //eloc_y = the energy of the tail-1
    RealType eloc_xp = anchor->Properties(LOCALENERGY);
    RealType eloc_x =  Reptile->tails[0]->Properties(LOCALENERGY);
    RealType eloc_y =  Reptile->tails[1]->Properties(LOCALENERGY);

    NumCuts = Reptile->NumCuts;
    RealType Wpolymer=0.0;

    for(int i=0; i<NumCuts; ) {

      Walker_t* head=Reptile->heads[i];
      
      //create a 3N-Dimensional Gaussian with variance=1
      makeGaussRandom(deltaR);
      W.R = anchor->R + g*deltaR + Tau* anchor->Drift;
      
      //update the distance table associated with W
      //DistanceTable::update(W);
      W.update();
      
      //evaluate wave function
      ValueType logpsi(Psi.evaluateLog(W));
      
      //update the properties of the front chain
      //RealType eloc_yp = head->Properties(LOCALENERGY) = H.evaluate(W);
      //H.copy(head->getEnergyBase());
      //head->Properties(LOCALPOTENTIAL) = H.getLocalPotential();
      RealType eloc_yp = H.evaluate(W);
      head->resetProperty(logpsi,Psi.getSign(),eloc_yp);
      H.saveProperty(head->getPropertyBase());
      
      head->R = W.R;
      
      //ValueType vsq = Dot(W.G,W.G);
      //ValueType scale = ((-1.0+sqrt(1.0+2.0*Tau*vsq))/vsq);
      //head->Drift = scale*W.G;
      head->Drift = W.G;
      
      //\f${x-y-\tau\nabla \ln \Psi_{T}(y))\f$
      //deltaR = anchor->R - W.R - heads[i]->Drift;
      //Gdrift *= exp(-oneover2tau*Dot(deltaR,deltaR));
      /* 
         \f$ X= \{R_0, R_1, ... , R_M\}\f$
         \f$ X' = \{R_1, .., R_M, R_{M+1}\}\f$
         \f[ G_B(R_{M+1}\leftarrow R_{M}, \tau)/G_B(R_{0}\leftarrow R_{1}, \tau)
         = exp\(-\tau/2[E_L(R_{M+1})+E_L(R_M)-E_L(R_1)-E_L(R_0)]\)\f]
         *
         -  eloc_yp = \f$E_L(R_{M+1})\f$
         -  eloc_xp = \f$E_L(R_{M})\f$
         -  eloc_y = \f$E_L(R_{1})\f$
         -  eloc_x = \f$E_L(R_{0})\f$
      */ 
      //Wpolymer *= exp(-oneover2tau*(eloc_yp+eloc_xp-eloc_x-eloc_y));
      Wpolymer +=(eloc_yp+eloc_xp-eloc_x-eloc_y);

      //move the anchor and swap the local energies for Wpolymer
      anchor=head;
      
      //increment the index
      i++;
      if(i<NumCuts) {
        eloc_xp  = eloc_yp;
        eloc_x = eloc_y;
        eloc_y = Reptile->tails[i+1]->Properties(LOCALENERGY);
      }
    }

    Wpolymer = exp(-tauover2*Wpolymer);
    double accept = std::min(1.0,Wpolymer);
    if(Random() < accept){//move accepted
      Reptile->updateEnds();
      ++nAccept;
    } else {
      ++nReject; 
      if(UseBounce) {
        NumTurns++;
        Reptile->flip();
      }
    }
    //RealType Bounce =  UseBounce ? 1.0-accept: 0.5;
    //if(Random()<Bounce) {
    //  Reptile->flip();
    //  LogOut->getStream() << "Bounce = " << Bounce << " " << NumTurns << " " << polymer.MoveHead << endl;
    //  NumTurns++;//increase the number of turns
    //}
  }
Пример #7
0
public func Initialize() {
  SetGamma(RGB(0,0,0),RGB(68,68,83),RGB(147,147,173));
  for(var y=0; y<LandscapeHeight(); (y+=510) && (x=0))
	for(var x=0; x<LandscapeWidth(); x+=530)
		ObjectSetAction(CreateObject(_CSN,x,y,-1),Format("Wait%d",Random(4)));
}
Пример #8
0
void cSSAOWorker::doWork()
{
	int quality = threadData->quality;
	int startLine = threadData->startLine;
	int width = image->GetWidth();
	int height = image->GetHeight();

	double *cosine = new double[quality];
	double *sine = new double[quality];
	for (int i = 0; i < quality; i++)
	{
		sine[i] = sin((double)i / quality * 2.0 * M_PI);
		cosine[i] = cos((double)i / quality * 2.0 * M_PI);
	}

	double scale_factor = (double)width / (quality * quality) / 2.0;
	double aspectRatio = (double)width / height;

	params::enumPerspectiveType perspectiveType = params->perspectiveType;
	double fov = params->fov;

	double intensity = params->ambientOcclusion;

	int listIndex = 0;

	int step = threadData->progressive;
	if (step == 0) step = 1;

	for (int y = startLine; y < height; y += threadData->noOfThreads)
	{
		if (threadData->list)
		{
			if (listIndex >= threadData->list->size())
			{
				continue;
			}
			if (y < threadData->list->at(listIndex))
			{
				continue;
			}
			else
			{
				listIndex++;
			}
		}
		for (int x = 0; x < width; x += step)
		{
			double z = image->GetPixelZBuffer(x, y);
			unsigned short opacity16 = image->GetPixelOpacity(x, y);
			double opacity = opacity16 / 65535.0;
			double total_ambient = 0;

			if (z < 1e19)
			{
				// printf("SSAO point on object\n");
				double x2, y2;
				if (perspectiveType == params::perspFishEye)
				{
					x2 = M_PI * ((double)x / width - 0.5) * aspectRatio;
					y2 = M_PI * ((double)y / height - 0.5);
					double r = sqrt(x2 * x2 + y2 * y2);
					if (r != 0.0)
					{
						x2 = x2 / r * sin(r * fov) * z;
						y2 = y2 / r * sin(r * fov) * z;
					}
				}
				else if (perspectiveType == params::perspEquirectangular)
				{
					x2 = M_PI * ((double)x / width - 0.5) * aspectRatio;
					y2 = M_PI * ((double)y / height - 0.5);
					x2 = sin(fov * x2) * cos(fov * y2) * z;
					y2 = sin(fov * y2) * z;
				}
				else
				{
					x2 = ((double)x / width - 0.5) * aspectRatio;
					y2 = ((double)y / height - 0.5);
					x2 = x2 * z * fov;
					y2 = y2 * z * fov;
				}

				double ambient = 0;
				double angleStep = M_PI * 2.0 / (double)quality;
				int maxRandom = 62831 / quality;
				double rRandom = 1.0;

				if (params->SSAO_random_mode) rRandom = 0.5 + Random(65536) / 65536.0;

				for (int angleIndex = 0; angleIndex < quality; angleIndex++)
				{
					double ca, sa;
					if (params->SSAO_random_mode)
					{
						double angle = angleStep * angleIndex + Random(maxRandom) / 10000.0;
						ca = cos(angle);
						sa = sin(angle);
					}
					else
					{
						ca = cosine[angleIndex];
						sa = sine[angleIndex];
					}

					double max_diff = -1e50;

					for (double r = 1.0; r < quality; r += rRandom)
					{
						double rr = r * r * scale_factor;
						double xx = x + rr * ca;
						double yy = y + rr * sa;

						if ((int)xx == x && (int)yy == y) continue;
						if (xx < 0 || xx > width - 1 || yy < 0 || yy > height - 1) continue;
						double z2 = image->GetPixelZBuffer((int)xx, (int)yy);

						double xx2, yy2;
						if (perspectiveType == params::perspFishEye)
						{
							xx2 = M_PI * (xx / width - 0.5) * aspectRatio;
							yy2 = M_PI * (yy / height - 0.5);
							double r2 = sqrt(xx2 * xx2 + yy2 * yy2);
							if (r != 0.0)
							{
								xx2 = xx2 / r2 * sin(r2 * fov) * z2;
								yy2 = yy2 / r2 * sin(r2 * fov) * z2;
							}
						}
						else if (perspectiveType == params::perspEquirectangular)
						{
							xx2 = M_PI * (xx / width - 0.5) * aspectRatio;
							yy2 = M_PI * (yy / height - 0.5);
							xx2 = sin(fov * xx2) * cos(fov * yy2) * z2;
							yy2 = sin(fov * yy2) * z2;
						}
						else
						{
							xx2 = (xx / width - 0.5) * aspectRatio;
							yy2 = (yy / height - 0.5);
							xx2 = xx2 * (z2 * fov);
							yy2 = yy2 * (z2 * fov);
						}

						double dx = xx2 - x2;
						double dy = yy2 - y2;
						double dz = z2 - z;
						double dr = sqrt(dx * dx + dy * dy);
						double diff = -dz / dr;

						if (diff > max_diff) max_diff = diff;
					}
					double max_angle = atan(max_diff);

					ambient += -max_angle / M_PI + 0.5;
				}

				total_ambient = ambient / quality;
				if (total_ambient < 0) total_ambient = 0;
			}

			for (int xx = 0; xx < step; xx++)
			{
				if (xx >= width - 1) break;
				sRGB8 colour = image->GetPixelColor(x + xx, y);
				sRGB16 pixel = image->GetPixelImage16(x + xx, y);
				double shadeFactor = (65535.0 / 256.0) * total_ambient * intensity * (1.0 - opacity);
				pixel.R = (unsigned short)min(pixel.R + (int)(colour.R * shadeFactor), 65535);
				pixel.G = (unsigned short)min(pixel.G + (int)(colour.G * shadeFactor), 65535);
				pixel.B = (unsigned short)min(pixel.B + (int)(colour.B * shadeFactor), 65535);
				image->PutPixelImage16(x + xx, y, pixel);
			}
		}

		threadData->done++;

		if (threadData->stopRequest) break;
	}
	delete[] sine;
	delete[] cosine;

	// emit signal to main thread when finished
	emit finished();
	return;
}
Пример #9
0
/**
 * Build a piece of canal.
 * @param tile end tile of stretch-dragging
 * @param flags type of operation
 * @param p1 start tile of stretch-dragging
 * @param p2 waterclass to build. sea and river can only be built in scenario editor
 * @param text unused
 * @return the cost of this operation or an error
 */
CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
	WaterClass wc = Extract<WaterClass, 0, 2>(p2);
	if (p1 >= MapSize() || wc == WATER_CLASS_INVALID) return CMD_ERROR;

	/* Outside of the editor you can only build canals, not oceans */
	if (wc != WATER_CLASS_CANAL && _game_mode != GM_EDITOR) return CMD_ERROR;

	TileArea ta(tile, p1);

	/* Outside the editor you can only drag canals, and not areas */
	if (_game_mode != GM_EDITOR && ta.w != 1 && ta.h != 1) return CMD_ERROR;

	CommandCost cost(EXPENSES_CONSTRUCTION);
	TILE_AREA_LOOP(tile, ta) {
		CommandCost ret;

		Slope slope = GetTileSlope(tile);
		if (slope != SLOPE_FLAT && (wc != WATER_CLASS_RIVER || !IsInclinedSlope(slope))) {
			return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
		}

		/* can't make water of water! */
		if (IsTileType(tile, MP_WATER) && (!IsTileOwner(tile, OWNER_WATER) || wc == WATER_CLASS_SEA)) continue;

		bool water = IsWaterTile(tile);
		ret = DoCommand(tile, 0, 0, flags | DC_FORCE_CLEAR_TILE, CMD_LANDSCAPE_CLEAR);
		if (ret.Failed()) return ret;

		if (!water) cost.AddCost(ret);

		if (flags & DC_EXEC) {
			switch (wc) {
				case WATER_CLASS_RIVER:
					MakeRiver(tile, Random());
					if (_game_mode == GM_EDITOR) {
						TileIndex tile2 = tile;
						CircularTileSearch(&tile2, 5, RiverModifyDesertZone, NULL);
					}
					break;

				case WATER_CLASS_SEA:
					if (TileHeight(tile) == 0) {
						MakeSea(tile);
						break;
					}
					/* FALL THROUGH */

				default:
					MakeCanal(tile, _current_company, Random());
					if (Company::IsValidID(_current_company)) {
						Company::Get(_current_company)->infrastructure.water++;
						DirtyCompanyInfrastructureWindows(_current_company);
					}
					break;
			}
			MarkTileDirtyByTile(tile);
			MarkCanalsAndRiversAroundDirty(tile);
		}

		cost.AddCost(_price[PR_BUILD_CANAL]);
	}
Пример #10
0
func Initialize() {
  SetR(Random(360));
  AddAlienFlareEffect(this(),100);
  //AddFireEffect(this(),0,RGB(20,255,30),0,-20);
}
Пример #11
0
int main(){
	int i, j, k, r, index;
	int failCount = 0;
	int totalCount = 0;
	int numPlayers = 2;
	int seed = 5555;
	int kingCards[10] = {adventurer, council_room, feast, gardens, mine, remodel, smithy, village, baron, great_hall};
	struct gameState G;

	FILE* outfile;
	FILE* reportfile;

	outfile = fopen("unittest4.result", "w");
	reportfile = fopen("unittestresult.out", "a");

	fprintf(reportfile, "Testing isGameOver, with all combinations of number of provinces left (0-12), and number of other piles at zer0 (0-17).\n");

	for(i = 0; i < 13; i++)/*Number of Provinces*/{
		for(j = 0; j < 18; j++)/*Number of Piles at zero*/{
			memset(&G, 23, sizeof(struct gameState));
			r = initializeGame(numPlayers, kingCards, seed, &G);

			G.supplyCount[3] = i;

			for(k = 0; k < j; k++){
				index = floor(Random() * treasure_map);
				if(index == 3) k--;
				else if(G.supplyCount[index] == 0) k--;
				else G.supplyCount[index] = 0;
			}

			r = isGameOver(&G);
			totalCount++;

			if(i <= 0){
				if(r == 1) fprintf(outfile, "SUCCESS: Correctly found that Province pile is empty. (%d, %d)\n", i, j);
				else{
					fprintf(outfile, "FAILURE: Did not find that Province pile is empty. (%d, %d)\n", i, j);
					failCount++;
				}
			}
			else if(r == 1){
				fprintf(outfile, "FAILURE: Incorrectly found that Province pile is empty. (%d, %d)\n", i, j);
				failCount++;
			}
			else fprintf(outfile, "SUCCESS: Did not incorrectly find the Province pile is empty. (%d, %d)\n", i, j);

			if(j >= 3 && r > 1){
				if(r == 2) fprintf(outfile, "SUCCESS: Correctly found that 3 or more piles are empty. (%d, %d)\n", i, j);
				else{
					fprintf(outfile, "FAILURE: Did not find that 3 or more piles were empty. (%d, %d)\n", i, j);
					failCount++;
				}
			}
			else if(r == 2){
				fprintf(outfile, "FAILURE: Incorrectly found that 3 or more piles were empty. (%d, %d)\n", i, j);
				failCount++;
			}
			else fprintf(outfile, "SUCCESS: Did not incorrectly find that 3 or more piles were empty. (%d, %d)\n", i, j);

		}
	}

	fprintf(reportfile, "NUMBER OF COMBINATIONS TESTED: %d\n", totalCount);
	fprintf(reportfile, "NUMBER OF FAILED TESTS (2 possible per unique set of inputs): %d\n", failCount);

	fclose(outfile);
	fclose(reportfile);

	return 0;
}
Пример #12
0
void OcdDecoder::RecursiveDecode(blockID_t blockID) {
	uint32_t blockIndex, unsolvedBlockIndex;
	uint8_t *solvedBlock; /* Used to point to already known blocks */
	uint32_t degree, degree_it;
	std::list<blockID_t>::iterator blockID_it;
	uint32_t numberOfUnsolvedBlocks;

	/* Check if remaining degree is 1, so that we can derive
	   information from it right now. If not, return immediately. */
	if(mBlockRemainingDegreeList[blockID] != 1)
		return;

	/* Set solution holder to the contents of the checkBlock */
	memcpy(mBlockSolution, mCheckBlockCache[blockID], mBlockSize);

	/* Sweep all blocks related to this check block, and xor them together.
	   additionally, look for the block which has not been solved yet,
	   so that we could know where to commit the solution */
	SeedCodec(blockID);
	degree = GetDegree();

	numberOfUnsolvedBlocks = 0;
	for(degree_it = 0; degree_it < degree; degree_it++) {
		blockIndex = Random(mNumberOfIntermediateBlocks);

		if(mBlockStatus[blockIndex] == BLOCK_SOLVED) {
			/* Get block pointer */
			GetBlock(mIntermediateBuffer.buffer, blockIndex, &solvedBlock);
			BlockXor(mBlockSolution, solvedBlock);
		}
		else {
			numberOfUnsolvedBlocks++;
			unsolvedBlockIndex = blockIndex;
		}
	}

	/* At this point, blockSolution contains the solution for the
	   block at unsolvedBlockIndex. Just commit it */
	GetBlock(mIntermediateBuffer.buffer, unsolvedBlockIndex, &solvedBlock);
	memcpy(solvedBlock, mBlockSolution, mBlockSize);

	/* Now the update stage.
	   First step: Flag solvedBlockIndex as "BLOCK_SOLVED" and update
		numberOfRemainingBlocks */
	mBlockStatus[unsolvedBlockIndex] = BLOCK_SOLVED;
	mNumberOfRemainingBlocks--;

	/* Second step: decrease by one degree all checkBlocks related to
	   the solved one. */
	for(blockID_it = mRelatedBlockIDLists[unsolvedBlockIndex].begin();
		blockID_it != mRelatedBlockIDLists[unsolvedBlockIndex].end();
		blockID_it++) {

		if(mBlockRemainingDegreeList[*blockID_it] > 0)
			mBlockRemainingDegreeList[*blockID_it]--;
	}

	/* Third step: evaluate recursively those blocks which have degree equal to 1 */
	for(blockID_it = mRelatedBlockIDLists[unsolvedBlockIndex].begin();
		blockID_it != mRelatedBlockIDLists[unsolvedBlockIndex].end();
		blockID_it++) {

		if(mBlockRemainingDegreeList[*blockID_it] == 1)
			RecursiveDecode(*blockID_it);
	}

	/* Fourth step (optional): clear list of relational blocks */
	mRelatedBlockIDLists[unsolvedBlockIndex].clear();
}
Пример #13
0
int main()
{
	int i, j, p, position;
	struct gameState state;

	SelectStream(2);
	PutSeed(3);

	for (i = 0; i < 2000; i++)
	{
		for (j = 0; j < sizeof(struct gameState); j++)
		{
			((char*)&state)[j] = floor(Random() * 256);
		}
		p = floor(Random() * 4);

		position = floor(Random() * 20);
		state.deckCount[p] = floor(Random() * MAX_DECK);
		state.discardCount[p] = floor(Random() * MAX_DECK);
		state.playedCardCount = floor(Random() * MAX_DECK);
		state.handCount[p] = floor(Random() * MAX_HAND);
		state.whoseTurn = p;
		state.numActions = floor(Random() * 1);

		for (j = 0; j < treasure_map; j++)
		{
			state.supplyCount[j] = floor(Random() * 25);
		}

		for (j = 0; j < state.handCount[p]; j++)
		{
			state.hand[p][j] = floor(Random() * MAX_HAND);
		}

		for (j = 0; j < state.discardCount[p]; j++)
		{
			state.discard[p][j] = floor(Random() * MAX_DECK);
		}

		for (j = 0; j < state.deckCount[p]; j++)
		{
			state.deck[p][j] = floor(Random() * MAX_DECK);
		}

		for (j = 0; j < state.playedCardCount; j++)
		{
			state.playedCards[j] = floor(Random() * MAX_DECK);
		}

		testVillageCard(p, &state, position);
	}

	printf("No errors found in tests of Village Card \n");

	return 0;
}
Пример #14
0
//------------HotPotato_Init------------
// Setup hot-potato game mode elements
// Input: none
// Output: none
void HotPotato_Init(void){
	HotPotato_SetIt(Random()%4);
}
Пример #15
0
BOOL MonsterHerd::AddMonster(int iMonsterType, BOOL bRegen, BOOL bAttackFirst)
{
	if ( this->m_bHasInfo == 0 )
	{
		return false;
	}

	int iIndex;
	BYTE btMapNumber = this->m_iMapNumber;
	BYTE cX=0;
	BYTE cY=0;

	if (this->GetRandomLocation(cX, cY) == FALSE )
	{
		return false;
	}

	iIndex = gObjAddMonster(this->m_iMapNumber);

	if ( iIndex >= 0 )
	{
		gObj[iIndex].m_PosNum = -1;
		gObj[iIndex].X = cX;
		gObj[iIndex].Y = cY;
		gObj[iIndex].MapNumber = this->m_iMapNumber;
		gObj[iIndex].TX = gObj[iIndex].X;
		gObj[iIndex].TY = gObj[iIndex].Y;
		gObj[iIndex].m_OldX = gObj[iIndex].X;
		gObj[iIndex].m_OldY = gObj[iIndex].Y;
		gObj[iIndex].StartX = (BYTE)gObj[iIndex].X;
		gObj[iIndex].StartY = (BYTE)gObj[iIndex].Y;

		LPMONSTER_ATTRIBUTE iAttr = gMAttr.GetAttr(iMonsterType);

		if ( iAttr == NULL )
		{
			gObjDel(iIndex);
			return false;
		}

		gObj[iIndex].Level = iAttr->m_Level;
		gObjSetMonster(iIndex, iMonsterType);
		gObj[iIndex].MaxRegenTime = 1000;
		gObj[iIndex].Dir = Random(0,7);
		gObj[iIndex].m_bIsInMonsterHerd = 1;
		gObj[iIndex].m_bIsMonsterAttackFirst = bAttackFirst;
		gObj[iIndex].m_lpMonsterHerd = this;

		EnterCriticalSection(&this->m_critMonsterHerd);

		_MONSTER_HERD_DATA pMonsterData;
		pMonsterData.m_iIndex = iIndex;
		pMonsterData.m_iType = iMonsterType;
		pMonsterData.m_iX = cX;
		pMonsterData.m_iY = cY;	
		pMonsterData.m_bRegen = bRegen;

		this->m_mapMonsterHerd.insert( std::pair<int, _MONSTER_HERD_DATA>(iIndex, pMonsterData) );

		LeaveCriticalSection(&this->m_critMonsterHerd);
	}
	else
	{
		return FALSE;
	}

	return TRUE;

}
Пример #16
0
static void
NormalMycon (RESPONSE_REF R)
{
	RESPONSE_FUNC RespFunc;

	if (PLAYER_SAID (R, what_about_shattered))
	{
		NPCPhrase (ABOUT_SHATTERED);

		SET_GAME_STATE (KNOW_ABOUT_SHATTERED, 2);
	}
	else if (R)
	{
		DoRamble (R);
		NPCPhrase (RAMBLE_TAIL);

		DISABLE_PHRASE (RESPONSE_TO_REF (R));
	}

	if ((BYTE)Random () < 256 * 30 / 100)
		RespFunc = (RESPONSE_FUNC)CombatIsInevitable;
	else
		RespFunc = (RESPONSE_FUNC)NormalMycon;
	if (!(GET_GAME_STATE (GLOBAL_FLAGS_AND_DATA) & (1 << 7)))
	{
		if (PHRASE_ENABLED (come_in_peace))
			Response (come_in_peace, RespFunc);
		if (PHRASE_ENABLED (gonna_die))
			Response (gonna_die, RespFunc);
		if (!MadeChoice) switch (GET_GAME_STATE (MYCON_INSULTS))
		{
			case 0:
				Response (insult_1, RespFunc);
				break;
			case 1:
				Response (insult_2, RespFunc);
				break;
			case 2:
				Response (insult_3, RespFunc);
				break;
			case 3:
				Response (insult_4, RespFunc);
				break;
			case 4:
				Response (insult_5, RespFunc);
				break;
			case 5:
				Response (insult_6, RespFunc);
				break;
			case 6:
				Response (insult_7, RespFunc);
				break;
			case 7:
				Response (insult_8, RespFunc);
				break;
		}
		Response (bye_space, CombatIsInevitable);
	}
	else
	{
		if (!MadeChoice) switch (GET_GAME_STATE (MYCON_INFO))
		{
			case 0:
				Response (question_1, RespFunc);
				break;
			case 1:
				Response (question_2, RespFunc);
				break;
			case 2:
				Response (question_3, RespFunc);
				break;
			case 3:
				Response (question_4, RespFunc);
				break;
			case 4:
				Response (question_5, RespFunc);
				break;
			case 5:
				Response (question_6, RespFunc);
				break;
			case 6:
				Response (question_7, RespFunc);
				break;
			case 7:
				Response (question_8, RespFunc);
				break;
			case 8:
				Response (question_9, RespFunc);
				break;
			case 9:
				Response (question_10, RespFunc);
				break;
			case 10:
				Response (question_11, RespFunc);
				break;
			case 11:
				Response (question_12, RespFunc);
				break;
			case 12:
				Response (question_13, RespFunc);
				break;
			case 13:
				Response (question_14, RespFunc);
				break;
			case 14:
				Response (question_15, RespFunc);
				break;
			case 15:
				Response (question_16, RespFunc);
				break;
		}
		if (PHRASE_ENABLED (lets_be_friends))
			Response (lets_be_friends, RespFunc);
		if (PHRASE_ENABLED (came_to_homeworld))
			Response (came_to_homeworld, RespFunc);
		if (PHRASE_ENABLED (submit_to_us))
			Response (submit_to_us, RespFunc);
		if (!GET_GAME_STATE (MYCON_FELL_FOR_AMBUSH))
		{
			if (GET_GAME_STATE (KNOW_ABOUT_SHATTERED) == 1)
				Response (what_about_shattered, NormalMycon);
			if (GET_GAME_STATE (MYCON_AMBUSH))
			{
				Response (i_have_a_cunning_plan, TrickMycon);
			}
		}
		Response (bye_homeworld, CombatIsInevitable);
	}
}
Пример #17
0
//-----------------------------------------------------------------------------
// Does the given point lie on our shell? There are many cases; inside and
// outside are obvious, but then there's all the edge-on-edge and edge-on-face
// possibilities.
//
// To calculate, we intersect a ray through p with our shell, and classify
// using the closest intersection point. If the ray hits a surface on edge,
// then just reattempt in a different random direction.
//-----------------------------------------------------------------------------
bool SShell::ClassifyEdge(int *indir, int *outdir,
                          Vector ea, Vector eb,
                          Vector p, 
                          Vector edge_n_in, Vector edge_n_out, Vector surf_n)
{
    List<SInter> l;
    ZERO(&l);

    srand(0);

    // First, check for edge-on-edge
    int edge_inters = 0;
    Vector inter_surf_n[2], inter_edge_n[2];
    SSurface *srf;
    for(srf = surface.First(); srf; srf = surface.NextAfter(srf)) {
        if(srf->LineEntirelyOutsideBbox(ea, eb, true)) continue;

        SEdgeList *sel = &(srf->edges);
        SEdge *se;
        for(se = sel->l.First(); se; se = sel->l.NextAfter(se)) {
            if((ea.Equals(se->a) && eb.Equals(se->b)) ||
               (eb.Equals(se->a) && ea.Equals(se->b)) ||
                p.OnLineSegment(se->a, se->b))
            {
                if(edge_inters < 2) {
                    // Edge-on-edge case
                    Point2d pm;
                    srf->ClosestPointTo(p,  &pm, false);
                    // A vector normal to the surface, at the intersection point
                    inter_surf_n[edge_inters] = srf->NormalAt(pm);
                    // A vector normal to the intersecting edge (but within the
                    // intersecting surface) at the intersection point, pointing
                    // out.
                    inter_edge_n[edge_inters] =
                      (inter_surf_n[edge_inters]).Cross((se->b).Minus((se->a)));
                }

                edge_inters++;
            }
        }
    }

    if(edge_inters == 2) {
        // TODO, make this use the appropriate curved normals
        double dotp[2];
        for(int i = 0; i < 2; i++) {
            dotp[i] = edge_n_out.DirectionCosineWith(inter_surf_n[i]);
        }

        if(fabs(dotp[1]) < DOTP_TOL) {
            SWAP(double, dotp[0],         dotp[1]);
            SWAP(Vector, inter_surf_n[0], inter_surf_n[1]);
            SWAP(Vector, inter_edge_n[0], inter_edge_n[1]);
        }

        int coinc = (surf_n.Dot(inter_surf_n[0])) > 0 ? COINC_SAME : COINC_OPP;

        if(fabs(dotp[0]) < DOTP_TOL && fabs(dotp[1]) < DOTP_TOL) {
            // This is actually an edge on face case, just that the face
            // is split into two pieces joining at our edge.
            *indir  = coinc;
            *outdir = coinc;
        } else if(fabs(dotp[0]) < DOTP_TOL && dotp[1] > DOTP_TOL) {
            if(edge_n_out.Dot(inter_edge_n[0]) > 0) {
                *indir  = coinc;
                *outdir = OUTSIDE;
            } else {
                *indir  = INSIDE;
                *outdir = coinc;
            }
        } else if(fabs(dotp[0]) < DOTP_TOL && dotp[1] < -DOTP_TOL) {
            if(edge_n_out.Dot(inter_edge_n[0]) > 0) {
                *indir  = coinc;
                *outdir = INSIDE;
            } else {
                *indir  = OUTSIDE;
                *outdir = coinc;
            }
        } else if(dotp[0] > DOTP_TOL && dotp[1] > DOTP_TOL) {
            *indir  = INSIDE;
            *outdir = OUTSIDE;
        } else if(dotp[0] < -DOTP_TOL && dotp[1] < -DOTP_TOL) {
            *indir  = OUTSIDE;
            *outdir = INSIDE;
        } else {
            // Edge is tangent to the shell at shell's edge, so can't be
            // a boundary of the surface.
            return false;
        }
        return true;
    }

    if(edge_inters != 0) dbp("bad, edge_inters=%d", edge_inters);

    // Next, check for edge-on-surface. The ray-casting for edge-inside-shell
    // would catch this too, but test separately, for speed (since many edges
    // are on surface) and for numerical stability, so we don't pick up
    // the additional error from the line intersection.

    for(srf = surface.First(); srf; srf = surface.NextAfter(srf)) {
        if(srf->LineEntirelyOutsideBbox(ea, eb, true)) continue;

        Point2d puv;
        srf->ClosestPointTo(p, &(puv.x), &(puv.y), false);
        Vector pp = srf->PointAt(puv);

        if((pp.Minus(p)).Magnitude() > LENGTH_EPS) continue;
        Point2d dummy = { 0, 0 };
        int c = srf->bsp->ClassifyPoint(puv, dummy, srf);
        if(c == SBspUv::OUTSIDE) continue;

        // Edge-on-face (unless edge-on-edge above superceded)
        Point2d pin, pout;
        srf->ClosestPointTo(p.Plus(edge_n_in),  &pin,  false);
        srf->ClosestPointTo(p.Plus(edge_n_out), &pout, false);

        Vector surf_n_in  = srf->NormalAt(pin),
               surf_n_out = srf->NormalAt(pout);

        *indir  = ClassifyRegion(edge_n_in,  surf_n_in,  surf_n);
        *outdir = ClassifyRegion(edge_n_out, surf_n_out, surf_n);
        return true;
    }

    // Edge is not on face or on edge; so it's either inside or outside
    // the shell, and we'll determine which by raycasting.
    int cnt = 0;
    for(;;) {
        // Cast a ray in a random direction (two-sided so that we test if
        // the point lies on a surface, but use only one side for in/out
        // testing)
        Vector ray = Vector::From(Random(1), Random(1), Random(1));

        AllPointsIntersecting(
            p.Minus(ray), p.Plus(ray), &l, false, true, false);
        
        // no intersections means it's outside
        *indir  = OUTSIDE;
        *outdir = OUTSIDE;
        double dmin = VERY_POSITIVE;
        bool onEdge = false;
        edge_inters = 0;

        SInter *si;
        for(si = l.First(); si; si = l.NextAfter(si)) {
            double t = ((si->p).Minus(p)).DivPivoting(ray);
            if(t*ray.Magnitude() < -LENGTH_EPS) {
                // wrong side, doesn't count
                continue;
            }

            double d = ((si->p).Minus(p)).Magnitude();

            // We actually should never hit this case; it should have been
            // handled above.
            if(d < LENGTH_EPS && si->onEdge) {
                edge_inters++;
            }

            if(d < dmin) {
                dmin = d;
                // Edge does not lie on surface; either strictly inside
                // or strictly outside
                if((si->surfNormal).Dot(ray) > 0) {
                    *indir  = INSIDE;
                    *outdir = INSIDE;
                } else {
                    *indir  = OUTSIDE;
                    *outdir = OUTSIDE;
                }
                onEdge = si->onEdge;
            }
        }
        l.Clear();

        // If the point being tested lies exactly on an edge of the shell,
        // then our ray always lies on edge, and that's okay. Otherwise
        // try again in a different random direction.
        if(!onEdge) break;
        if(cnt++ > 5) {
            dbp("can't find a ray that doesn't hit on edge!");
            dbp("on edge = %d, edge_inters = %d", onEdge, edge_inters);
            SS.nakedEdges.AddEdge(ea, eb);
            break;
        }
    }

    return true;
}
Пример #18
0
Solver::Solver(int length) {
	rGen = Random(32, 126);
	sGen = Random(0, length);
}
Пример #19
0
//Based on the density level setting and the selection type, this test will
//randomly choose TRUE or FALSE to reflect the *odds*.
BOOLEAN PerformDensityTest()
{
	if( Random(100) < gusSelectionDensity )
		return TRUE;
	return FALSE;
}
Пример #20
0
Color Color::RandomColor(){
	return Color(Random(), Random(), Random(), 1.f);
}
Пример #21
0
static void TileLoop_Clear(TileIndex tile)
{
	/* If the tile is at any edge flood it to prevent maps without water. */
	if (_settings_game.construction.freeform_edges && DistanceFromEdge(tile) == 1) {
		uint z;
		Slope slope = GetTileSlope(tile, &z);
		if (z == 0 && slope == SLOPE_FLAT) {
			DoFloodTile(tile);
			MarkTileDirtyByTile(tile);
			return;
		}
	}
	TileLoopClearHelper(tile);

	switch (_settings_game.game_creation.landscape) {
		case LT_TROPIC: TileLoopClearDesert(tile); break;
		case LT_ARCTIC: TileLoopClearAlps(tile);   break;
	}

	switch (GetClearGround(tile)) {
		case CLEAR_GRASS:
			if (GetClearDensity(tile) == 3) return;

			if (_game_mode != GM_EDITOR) {
				if (GetClearCounter(tile) < 7) {
					AddClearCounter(tile, 1);
					return;
				} else {
					SetClearCounter(tile, 0);
					AddClearDensity(tile, 1);
				}
			} else {
				SetClearGroundDensity(tile, GB(Random(), 0, 8) > 21 ? CLEAR_GRASS : CLEAR_ROUGH, 3);
			}
			break;

		case CLEAR_FIELDS: {
			uint field_type;

			if (_game_mode == GM_EDITOR) return;

			if (GetClearCounter(tile) < 7) {
				AddClearCounter(tile, 1);
				return;
			} else {
				SetClearCounter(tile, 0);
			}

			if (GetIndustryIndexOfField(tile) == INVALID_INDUSTRY && GetFieldType(tile) >= 7) {
				/* This farmfield is no longer farmfield, so make it grass again */
				MakeClear(tile, CLEAR_GRASS, 2);
			} else {
				field_type = GetFieldType(tile);
				field_type = (field_type < 8) ? field_type + 1 : 0;
				SetFieldType(tile, field_type);
			}
			break;
		}

		default:
			return;
	}

	MarkTileDirtyByTile(tile);
}
Пример #22
0
Color Random(const Color& min, const Color& max)
{
	return Color(Random(min.r(), max.r()), Random(min.g(), max.g()),
		Random(min.b(), max.b()));
}
Пример #23
0
int main()
{
  int totalFail = 0;
  int totalPass = 0;

  int seed = -1;
  struct gameState G;
  int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
           sea_hag, tribute, smithy};

  int NUM_TEST_CARDS = 3;
  int testCards[NUM_TEST_CARDS];
  int i, x;
  int priorSupply, postSupply;
  int priorHand, postHand;
  int priorDeck, postDeck;
  int priorDiscard, postDiscard;

  SelectStream(1);
  PutSeed(-1);
  Random();

  for (i = 0; i < NUM_TEST_CARDS; i++) {
    testCards[i] = k[(int)floor(Random() * 10)];
  }

  initializeGame(2, k, seed, &G);

  //Begin testing--------------------------------------------------------------
  printf("------------------------------------------------------------\n");
  printf("-----------------BEGIN TESTING FOR gainCard()---------------\n");
  printf("------------------------------------------------------------\n");

  //Test out of bounds input for card to get ie. card that does not exist
  if (gainCard(treasure_map + 2, &G, 0, 0) == -1) {
    printf("gainCard(): PASS -> handles non existent card.\n\n");
    totalPass++;
  }
  else {
    printf("gainCard(): FAIL -> does not handle non existent card.\n\n");
    totalFail++;
  }

  //test empty supply pile ie. all cards are gone of that type
  G.supplyCount[curse] = 0;
  if (gainCard(curse, &G, 0, 0) == -1) {
    printf("gainCard(): PASS -> handles empty supply pile.\n\n");
    totalPass++;
  }
  else {
    printf("gainCard(): FAIL -> does not handle empty supply pile.\n\n");
    totalFail++;
  }

  //Test for out of bounds player
  if (gainCard(copper, &G, 0, MAX_PLAYERS + 1) == -1) {
    printf("gainCard(): PASS -> handles out of bounds player.\n\n");
    totalPass++;
  }
  else {
    printf("gainCard(): FAIL -> does not exit on out of bounds player.\n\n");
    totalFail++;
  }

  //Test to make sure anything other than 1 or 2 adds card to discard pile
  priorSupply = G.supplyCount[copper];
  priorDiscard = G.discardCount[0];
  gainCard(copper, &G, 3, 0);
  postSupply = G.supplyCount[copper];
  postDiscard = G.discardCount[0];
  if (postSupply == (priorSupply - 1)) {
    printf("gainCard(): PASS -> decrements supply count on flag not equal to 1 or 2.\n\n");
    totalPass++;
  }
  else {
    printf("gainCard(): FAIL -> does not decrement supply count on flag not equal to 1 or 2.\n\n");
    totalFail++;
  }
  
  if ( postDiscard == (priorDiscard + 1) && G.discard[0][postDiscard - 1] == copper ) {
    printf("gainCard(): PASS -> correctly discards card on flag not equal to 1 or 2.\n\n");
    totalPass++;
  }
  else {
    printf("gainCard(): FAIL -> did not discard card on flag not equal to 1 or 2.\n\n");
    totalFail++;
  }

  //Test scenario of adding card to the discard pile
  //test scenario of adding card to the deck
  //test scenario of adding card to the hand
  //The following uses NUM_TEST_CARDS number of random cards to test to make
  //sure that the cards are gained in either the discard, deck or hand
  for (x = 0; x < NUM_TEST_CARDS; x++) {
    
    //testing gaining card x and adding it to the deck
    priorSupply = G.supplyCount[testCards[x]];
    priorDeck = G.deckCount[0];
    gainCard(testCards[x], &G, 1, 0);   //add card to deck
    postSupply = G.supplyCount[testCards[x]];
    postDeck = G.deckCount[0];

    if ( postDeck == (priorDeck + 1) ) {
      if ( G.deck[0][postDeck - 1] == testCards[x] ) {
        printf("gainCard(): PASS -> Test card %d gained correctly to deck.\n\n", testCards[x]);
        totalPass++;
      }
      else {
        printf("gainCard(): FAIL -> Test card %d incremented deck count but was not correctly added to deck.\n\n", testCards[x]);
        totalFail++;
      }
    }
    else {
      if ( G.deck[0][postDeck - 1] == testCards[x] ) {
        printf("gainCard(): FAIL -> Test card %d was added to deck but did not increment deck count.\n\n", testCards[x]);
        totalFail++;
      }
      else {
        printf("gainCard(): FAIL -> Test card %d was not added to deck and did not increment deck count.\n\n", testCards[x]);
        totalFail++;
      }
    }

    if ( postSupply == (priorSupply - 1) ) {
      printf("gainCard(): PASS -> Test card %d decreased supply pile after added to deck.\n\n", testCards[x]);
      totalPass++;    
    }
    else {
      printf("gainCard(): FAIL -> Test card %d did not decrease supply pile after added to deck.\n\n", testCards[x]);
      totalFail++;      
    }

    //testing gaining card x and adding it to the hand
    priorSupply = G.supplyCount[testCards[x]];    
    priorHand = G.handCount[0];
    gainCard(testCards[x], &G, 2, 0);   //add card to hand
    postSupply = G.supplyCount[testCards[x]];
    postHand = G.handCount[0];

    if ( postHand == (priorHand + 1) ) {
      if ( G.hand[0][postHand - 1] == testCards[x] ) {
        printf("gainCard(): PASS -> Test card %d gained correctly to hand.\n\n", testCards[x]);
        totalPass++;
      }
      else {
        printf("gainCard(): FAIL -> Test card %d incremented hand count but was not correctly added to hand.\n\n", testCards[x]);
        totalFail++;
      }
    }
    else {
      if ( G.hand[0][postHand - 1] == testCards[x] ) {
        printf("gainCard(): FAIL -> Test card %d was added to hand but did not increment hand count.\n\n", testCards[x]);
        totalFail++;
      }
      else {
        printf("gainCard(): FAIL -> Test card %d was not added to hand and did not increment hand count.\n\n", testCards[x]);
        totalFail++;
      }
    }    

    if ( postSupply == (priorSupply - 1) ) {
      printf("gainCard(): PASS -> Test card %d decreased supply pile after added to hand.\n\n", testCards[x]);
      totalPass++;      
    }
    else {
      printf("gainCard(): FAIL -> Test card %d did not decrease supply pile after added to deck.\n\n", testCards[x]);
      totalFail++;      
    }

    //testing gaining card x and adding it to discard
    priorSupply = G.supplyCount[testCards[x]];
    priorDiscard = G.discardCount[0];
    gainCard(testCards[x], &G, 0, 0);   //add card to discard
    postSupply = G.supplyCount[testCards[x]];
    postDiscard = G.discardCount[0];

    if ( postDiscard == (priorDiscard + 1) ) {
      if ( G.discard[0][postDiscard - 1] == testCards[x] ) {
        printf("gainCard(): PASS -> Test card %d gained correctly to discard.\n\n", testCards[x]);
        totalPass++;
      }
      else {
        printf("gainCard(): FAIL -> Test card %d incremented discard count but was not correctly added to discard.\n\n", testCards[x]);
        totalFail++;
      }
    }
    else {
      if ( G.discard[0][postDiscard - 1] == testCards[x] ) {
        printf("gainCard(): FAIL -> Test card %d was added to discard but did not increment discard count.\n\n", testCards[x]);
        totalFail++;
      }
      else {
        printf("gainCard(): FAIL -> Test card %d was not added to discard and did not increment discard count.\n\n", testCards[x]);
        totalFail++;
      }
    }    

    if ( postSupply == (priorSupply - 1) ) {
      printf("gainCard(): PASS -> Test card %d decreased supply pile after added to discard.\n\n", testCards[x]);
      totalPass++;      
    }
    else {
      printf("gainCard(): FAIL -> Test card %d did not decrease supply pile after added to deck.\n\n", testCards[x]);
      totalFail++;      
    }    
    
  }

  printf("------------------------------------------------------------\n");
  printf("----------------RESULTS of gainCard() testing---------------\n");
  printf("Tests Passed: %d\tTests Failed: %d\n", totalPass, totalFail);
  printf("------------------------------------------------------------\n");

  return 0;
}
Пример #24
0
Random::Random()
{
	Random(time(NULL));
}
Пример #25
0
func SwimAround()
{
	if (!GBackLiquid() || !Random(100)) return RemoveObject();
	SetSpeed(0, 0);
}
Пример #26
0
void MonsterHerd::OrderAttack(LPOBJ lpObj, LPOBJ lpTargetObj, int iAttackPercent)
{
	if ( lpObj == NULL )
	{
		return;
	}

	if ( lpObj->Connected != PLAYER_PLAYING || lpObj->Type != OBJ_MONSTER )
	{
		return;
	}

	if ( lpTargetObj->Connected != PLAYER_PLAYING )
	{
		return;
	}

	if ( this->m_bHerdActive == 0 )
	{
		return;
	}

	if ( ((iAttackPercent<0)?FALSE:(iAttackPercent>100)?FALSE:TRUE) == FALSE )
	{
		return;
	}

	for ( std::map<int, _MONSTER_HERD_DATA>::iterator it = this->m_mapMonsterHerd.begin(); it != this->m_mapMonsterHerd.end() ; it++)
	{
		_MONSTER_HERD_DATA * lpMHD = &it->second;

		if ( OBJMAX_RANGE(lpMHD->m_iIndex)  == FALSE )
		{
			continue;
		}

		if ( gObj[lpMHD->m_iIndex].Live == FALSE || gObj[lpMHD->m_iIndex].m_State != 2 )
		{
			continue;
		}

		if ( gObj[lpMHD->m_iIndex].m_lpMonsterHerd != lpObj->m_lpMonsterHerd )
		{
			continue;
		}

		if ( lpMHD->m_iIndex == lpObj->m_Index )
		{
			continue;
		}

		if ( Random(0,99) < iAttackPercent )
		{
			gObj[lpMHD->m_iIndex].TargetNumber = lpTargetObj->m_Index;
			gObj[lpMHD->m_iIndex].m_ActState.Emotion = 1;
			gObj[lpMHD->m_iIndex].m_ActState.EmotionCount = 50;

			continue;
		}
	}
}
Пример #27
0
void cThumbnailWidget::AssignParameters(
	const cParameterContainer &_params, const cFractalContainer &_fractal)
{
	if (image)
	{
		if (!params) params = new cParameterContainer;
		if (!fractal) fractal = new cFractalContainer;
		*params = _params;
		*fractal = _fractal;
		params->Set("image_width", tWidth * oversample);
		params->Set("image_height", tHeight * oversample);
		params->Set("stereo_mode", int(cStereo::stereoRedCyan));
		params->Set("DOF_max_noise", params->Get<double>("DOF_max_noise") * 10.0);
		params->Set("DOF_min_samples", 5);

		double distance =
			cInterface::GetDistanceForPoint(params->Get<CVector3>("camera"), params, fractal);
		if (distance < 1e-5)
		{
			params->Set("opencl_mode", 0);
		}

		cSettings tempSettings(cSettings::formatCondensedText);
		tempSettings.CreateText(params, fractal);
		oldHash = hash;
		hash = tempSettings.GetHashCode();

		if (hash != oldHash)
		{
			stopRequest = true;
			while (image->IsUsed())
			{
				// just wait and pray
			}

			emit settingsChanged();

			isRendered = false;
			hasParameters = true;

			QString thumbnailFileName = GetThumbnailFileName();
			if (QFileInfo::exists(thumbnailFileName) && !disableThumbnailCache)
			{
				stopRequest = true;
				isRendered = true;
				while (image->IsUsed())
				{
					// just wait and pray
				}

				QPixmap pixmap;
				pixmap.load(thumbnailFileName);
				pixmap = pixmap.scaled(tWidth, tHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
				QImage qImage = pixmap.toImage();
				qImage = qImage.convertToFormat(QImage::Format_RGB888);

				sRGB8 *previewPointer = reinterpret_cast<sRGB8 *>(image->GetPreviewPrimaryPtr());
				sRGB8 *preview2Pointer = reinterpret_cast<sRGB8 *>(image->GetPreviewPtr());

				int bWidth = qImage.width();
				int bHeight = qImage.height();

				if (!qImage.isNull())
				{
					for (int y = 0; y < bHeight; y++)
					{
						sRGB8 *line = reinterpret_cast<sRGB8 *>(qImage.scanLine(y));
						for (int x = 0; x < bWidth; x++)
						{
							sRGB8 pixel(static_cast<unsigned short>(line[x].R),
								static_cast<unsigned short>(line[x].G), static_cast<unsigned short>(line[x].B));
							previewPointer[x + y * bWidth] = pixel;
							preview2Pointer[x + y * bWidth] = pixel;
						}
					}
				}

				delete params;
				params = nullptr;
				delete fractal;
				fractal = nullptr;
				emit thumbnailRendered();
			}
			else
			{
				if (!disableTimer)
				{
					// render thumbnail after random time. It forces rendering of widgets when they are not
					// visible. It makes rendering of widgets when they are idle.

					timer->start(Random(1000000) * 10 + 60000);
				}
			}
		}
	}
	else
	{
		qCritical() << "Image not yet allocated!";
	}
}
Пример #28
0
void MonsterHerd::MonsterBaseAct(LPOBJ lpObj)
{
	LPOBJ lpTargetObj = NULL;

	if ( lpObj->TargetNumber >= 0 )
	{
		lpTargetObj = &gObj[lpObj->TargetNumber];
	}
	else
	{
		lpObj->m_ActState.Emotion = 0;
	}

	switch ( lpObj->m_ActState.Emotion )
	{
		case 0:
			{
				if ( lpObj->m_ActState.Attack != 0 )
				{
					lpObj->m_ActState.Attack = 0;
					lpObj->TargetNumber = -1;
					lpObj->NextActionTime = 500;
				}

				int actcode1 = Random(0,1);

				if ( actcode1 == 0 )
				{
					lpObj->m_ActState.Rest = 1;
					lpObj->NextActionTime = 500;
				}
				else if ( lpObj->m_MoveRange > 0 )
				{
					if ( lpObj->m_SkillHarden == 0 )
					{
						this->MonsterMoveAction(lpObj);
					}
				}

				if ( lpObj->m_bIsMonsterAttackFirst != false )
				{
					lpObj->TargetNumber = gObjMonsterSearchEnemy(lpObj, OBJ_USER);

					if ( lpObj->TargetNumber >= 0 )
					{
						lpObj->m_ActState.EmotionCount = 30;
						lpObj->m_ActState.Emotion = 1;
					}
				}
			}
			break;

		case 1:

			if ( lpObj->m_ActState.EmotionCount > 0 )
			{
				lpObj->m_ActState.EmotionCount --;
			}
			else
			{
				lpObj->m_ActState.Emotion = 0;
			}

			if ( lpObj->TargetNumber >= 0 && lpObj->PathStartEnd == 0 )
			{
				int dis = gObjCalDistance(lpObj, lpTargetObj);
				int attackRange;

				if ( lpObj->m_AttackType >= 100 )
				{
					attackRange = lpObj->m_AttackRange + 2;
				}
				else
				{
					attackRange = lpObj->m_AttackRange;
				}

				if ( dis <= attackRange )
				{
					int tuser = lpObj->TargetNumber;
					int map = gObj[tuser].MapNumber;

					if ( MapC[map].CheckWall(lpObj->X, lpObj->Y, gObj[tuser].X, gObj[tuser].Y) == TRUE )
					{
						BYTE attr = MapC[map].GetAttr(gObj[tuser].X, gObj[tuser].Y);

						if ( (attr&1) != 1 )
						{
							lpObj->m_ActState.Attack = 1;
							lpObj->m_ActState.EmotionCount = (Random(0,29)+20);
						}
						else
						{
							lpObj->TargetNumber = -1;
							lpObj->m_ActState.EmotionCount = 30;
							lpObj->m_ActState.Emotion = 1;
						}

						lpObj->Dir = GetPathPacketDirPos(lpTargetObj->X-lpObj->X, lpTargetObj->Y-lpObj->Y);
						lpObj->NextActionTime = lpObj->m_AttackSpeed;
					}
				}
				else
				{
					if ( gObjMonsterGetTargetPos(lpObj) == TRUE )
					{
						if ( MapC[lpObj->MapNumber].CheckWall(lpObj->X, lpObj->Y, lpObj->MTX, lpObj->MTY) == TRUE )
						{
							lpObj->m_ActState.Move = 1;
							lpObj->NextActionTime = 400;
							lpObj->Dir = GetPathPacketDirPos(lpTargetObj->X - lpObj->X, lpTargetObj->Y-lpObj->Y);
						}
						else
						{
							this->MonsterMoveAction(lpObj);
							lpObj->m_ActState.Emotion = 3;
							lpObj->m_ActState.EmotionCount = 10;
						}
					}
					else
					{
						this->MonsterMoveAction(lpObj);
						lpObj->m_ActState.Emotion = 3;
						lpObj->m_ActState.EmotionCount = 10;
					}
				}
			}

			break;

		case 3:

			if ( lpObj->m_ActState.EmotionCount > 0 )
			{
				lpObj->m_ActState.EmotionCount--;
			}
			else
			{
				lpObj->m_ActState.Emotion = 0;
			}

			lpObj->m_ActState.Move = 0;
			lpObj->m_ActState.Attack = 0;
			lpObj->NextActionTime = 400;

			break;
	}
}
Пример #29
0
void InitializeMines( void )
{
	UINT8 ubMineIndex;
	MINE_STATUS_TYPE *pMineStatus;
	UINT8 ubMineProductionIncreases;
	UINT8 ubDepletedMineIndex;
	UINT8 ubMinDaysBeforeDepletion = 20;


	// set up initial mine status
	for( ubMineIndex = 0; ubMineIndex < MAX_NUMBER_OF_MINES; ubMineIndex++ )
	{
		pMineStatus = &(gMineStatus[ ubMineIndex ]);

		memset( pMineStatus, 0, sizeof( *pMineStatus ) );

		pMineStatus->ubMineType = gubMineTypes[ ubMineIndex ];
		pMineStatus->uiMaxRemovalRate = guiMinimumMineProduction[ ubMineIndex ];
		pMineStatus->fEmpty = (pMineStatus->uiMaxRemovalRate == 0) ? TRUE : FALSE;
		pMineStatus->fRunningOut = FALSE;
		pMineStatus->fWarnedOfRunningOut = FALSE;
//		pMineStatus->bMonsters = MINES_NO_MONSTERS;
		pMineStatus->fShutDown = FALSE;
		pMineStatus->fPrevInvadedByMonsters = FALSE;
		pMineStatus->fSpokeToHeadMiner = FALSE;
		pMineStatus->fMineHasProducedForPlayer = FALSE;
		pMineStatus->fQueenRetookProducingMine = FALSE;
		gMineStatus->fShutDownIsPermanent = FALSE;
	}

	// randomize the exact size each mine.  The total production is always the same and depends on the game difficulty,
	// but some mines will produce more in one game than another, while others produce less

	// adjust for game difficulty
	switch( gGameOptions.ubDifficultyLevel )
	{
		case DIF_LEVEL_EASY:
		case DIF_LEVEL_MEDIUM:
			ubMineProductionIncreases = 25;
			break;
		case DIF_LEVEL_HARD:
			ubMineProductionIncreases = 20;
			break;
		default:
			Assert( 0 );
			return;
	}

	while (ubMineProductionIncreases > 0)
	{
		// pick a producing mine at random and increase its production
		do
		{
			ubMineIndex = ( UINT8 ) Random(MAX_NUMBER_OF_MINES);
		} while (gMineStatus[ubMineIndex].fEmpty);

		// increase mine production by 20% of the base (minimum) rate
		gMineStatus[ubMineIndex].uiMaxRemovalRate += (guiMinimumMineProduction[ubMineIndex] / 5);

		ubMineProductionIncreases--;
	}


	// choose which mine will run out of production.  This will never be the Alma mine or an empty mine (San Mona)...
	do
	{
		ubDepletedMineIndex = ( UINT8 ) Random(MAX_NUMBER_OF_MINES);
		// Alma mine can't run out for quest-related reasons (see Ian)
	} while (gMineStatus[ubDepletedMineIndex].fEmpty || (ubDepletedMineIndex == MINE_ALMA));


	for( ubMineIndex = 0; ubMineIndex < MAX_NUMBER_OF_MINES; ubMineIndex++ )
	{
		pMineStatus = &(gMineStatus[ ubMineIndex ]);

		if (ubMineIndex == ubDepletedMineIndex)
		{
			if ( ubDepletedMineIndex == MINE_DRASSEN )
			{
				ubMinDaysBeforeDepletion = 20;
			}
			else
			{
				ubMinDaysBeforeDepletion = 10;
			}

			// the mine that runs out has only enough ore for this many days of full production
			pMineStatus->uiRemainingOreSupply = ubMinDaysBeforeDepletion * (MINE_PRODUCTION_NUMBER_OF_PERIODS * pMineStatus->uiMaxRemovalRate);

			// ore starts running out when reserves drop to less than 25% of the initial supply
			pMineStatus->uiOreRunningOutPoint = pMineStatus->uiRemainingOreSupply / 4;
		}
		else
		if (!pMineStatus->fEmpty)
		{
			// never runs out...
			pMineStatus->uiRemainingOreSupply = 999999999;		// essentially unlimited
			pMineStatus->uiOreRunningOutPoint = 0;
		}
		else
		{
			// already empty
			pMineStatus->uiRemainingOreSupply = 0;
			pMineStatus->uiOreRunningOutPoint = 0;
		}
	}
}
Пример #30
0
int Random(int from, int till)
{
	return Random(from) + (till - from);
}