Beispiel #1
0
void
RandomKnot::assignColors(void)
{
    // Initialize the color indices; -1 indicates an as-yet-unknown color.
    int color = mPrefs.technicolor() ? -1 : 0;
    for (int y = 0; y < mVSections; ++y) {
        for (int x = 0; x < mHSections; ++x) {
            mpSectionColors[BOT][y * mHSections + x] = color;
            mpSectionColors[TOP][y * mHSections + x] = color;
        }
    }
    ++color;

    // Assign colors to the sections by tracing all the 'strands' in the knot.
    for (int y = 0; y < mVSections; ++y) {
        for (int x = 0; x < mHSections; ++x) {
            if (mpSectionColors[TOP][y * mHSections + x] < 0) {
                // Assign a color to the top strand.
                if (traceColor(color, TOP, x, y, 0, 0)) {
                    ++color;
                }
            }

            if (mpSectionColors[BOT][y * mHSections + x] < 0) {
                // Assign a color to the bottom strand.
                switch (mpSectionTypes[y * mHSections + x]) {

                case D:
                case H:
                    if (traceColor(color, BOT, x, y, 0, 1)) {
                       ++color;
                    }
                    break;

                case V:
                    if (traceColor(color, BOT, x, y, 1, 0)) {
                        ++color;
                    }
                    break;

                case N:
                    break;
                }
            }
        }
    }

    // Generate the random colors.
    mpColors = new RandomColor[color];
    int hue = randomInteger(360);
    const int gamut = 90 + randomInteger(270);
    const int shift = gamut / color;
    for (int i = 0; i < color; ++i) {
        mpColors[i] = RandomColor(0.4, 0.9, 0.6, 1.0, 1.0, 1.0, hue);
        hue = (hue + shift) % 360;
    }
}
std::string itsAllGreek(std::ifstream &inFile) {
    std::string greek;
    char ch;
    while (inFile.get(ch)) {
        if (isupper(ch)) {
            int rand = randomInteger('A', 'Z');
            greek += rand;
        } else if (islower(ch)) {
            int rand = randomInteger('a', 'z');
            greek += rand;
        } else greek += ch;
    }
    return greek;
}
Beispiel #3
0
static bool hugeRangeSeemsReasonable() {
   unsigned maskHigh;
   int i, k, rangeBit, rangesLeft;

   maskHigh = ((unsigned) INT_MAX + 1) >> 1;
   rangesLeft = 0xF;
   for (i = 0; i < N_TRIALS && rangesLeft; i++) {
      k = randomInteger(INT_MIN, INT_MAX);
      if (k < 0) {
         rangeBit = (k & maskHigh) ? 1 : 2;
      } else {
         rangeBit = (k & maskHigh) ? 8 : 4;
      }
      rangesLeft &= ~rangeBit;
   }
   if (rangesLeft & 1) {
      reportError("No large negative values generated");
   }
   if (rangesLeft & 2) {
      reportError("No small negative values generated");
   }
   if (rangesLeft & 4) {
      reportError("No small positive values generated");
   }
   if (rangesLeft & 8) {
      reportError("No large positive values generated");
   }
   return rangesLeft == 0;
}
Beispiel #4
0
static bool randomIntegerSeemsReasonable(int low, int high) {
   int i, k, rangeSize, *counts, outcome;
   bool ok;
   double expected;

   rangeSize = high - low + 1;
   counts = newArray(rangeSize, int);
   for (i = 0; i < rangeSize; i++) {
      counts[i] = 0;
   }
   ok = true;
   for (i = 0; ok && i < N_TRIALS; i++) {
      k = randomInteger(low, high);
      if (k < low || k > high) {
         reportError("randomInteger returned out of range value %d", k);
         ok = false;
      } else {
         counts[k - low]++;
      }
   }
   expected = (double) N_TRIALS / rangeSize;
   for (i = 0; ok && i < rangeSize; i++) {
      outcome = low + i;
      if (counts[i] < 0.5 * expected) {
         reportError("Low count for outcome %d", outcome);
         ok = false;
      } else if (counts[i] > 1.5 * expected) {
         reportError("High count for outcome %d", outcome);
         ok = false;
      }
   }
   freeBlock(counts);
   return ok;
}
Beispiel #5
0
void randomPermutation (int n, int *p)
{
  for (int i = 0; i < n; ++i)
    p[i] = i;
  for (int i = 0; i < n - 1; ++i) {
    int j = randomInteger(i, n - 1), ti = p[i];
    p[i] = p[j];
    p[j] = ti;
  }
}    
Beispiel #6
0
void batalha(Jogador eu, Jogador foe)
{
	/* Toca a música especificada indefinidamente */
	tocaMusica("bgm/ffvi.wav");

	while (eu.status.hp > 0 && foe.status.hp > 0) {
		/* Exibe barras de vida na tela */
		lifebar(eu);
		lifebar(foe);

		/* Loop até chegar a vez de um personagem. O (+1) nesses dois
		   casos impede o personagem de nunca jogar caso SPD == 0. */
		while (eu.atb < MAX_ATB && foe.atb < MAX_ATB) {
			eu.atb += eu.status.spd + 1;
			foe.atb += foe.status.spd + 1;
		}

		if (eu.atb >= MAX_ATB) {
			eu.atb -= MAX_ATB;
			do {
				printf("\nSua vez! Digite 1 para atacar,\n"
				 	   "2 para carregar o golpe ou 3 para defender: ");
				scanf("%d", &eu.acao);

				if (eu.acao == 2 && eu.potencia == MAX_POW) {
					puts("\n>Limite atingido! Impossível carregar mais.");
					eu.acao = 0;
				}
			} while (eu.acao < 1 || eu.acao > 3);

			turno(&eu, &foe);
		}
		else { /* (foe.atb >= MAX_ATB) */
			congela(1);
			foe.atb -= MAX_ATB;

			do foe.acao = randomInteger(1, 3);
			while (foe.potencia == MAX_POW && foe.acao == 2);

			turno(&foe, &eu);
		}
	}

	/* Encerra a execução da música */
	paraMusica();

	/* Exibe resultado da batalha */
	lifebar(eu);
	lifebar(foe);
	printf("\n> %s foi aniquilado.\n", 
		(eu.status.hp <= 0) ? eu.nome : foe.nome);

	printf("\n***** Você %s! *****\n\n", 
		(eu.status.hp > 0) ? "ganhou" : "perdeu");
}
Beispiel #7
0
bool acerto(int agiX, int agiY)
{
	if (agiX >= 2*agiY) return true;

	int chance = (agiX <= agiY) ? sin((double) agiX/agiY * PI_2) * 80
							    : cos((double) agiX/agiY * PI_2) * (-20) + 80;
	#ifdef DEBUG
		printf(" (Chance: %d%%)", chance);
	#endif
	return (randomInteger(1, 100) <= chance);
}
Beispiel #8
0
void drawTree(double x, double y, double r, double theta, int depth) {
	if (depth < MAX_DEPTH) {
		double growth = randomReal(0.1, 0.4);
		setColor(TREE_COLORS[depth]);
		
		GPoint branchPt = drawPolarLine(x, y, r * growth, theta);
		
		int numChildren = randomInteger(2, 8);
		for (int i = 0; i < numChildren; i++) {
			double thetaPrime = theta + randomReal(-45, +45);
			drawTree(branchPt.getX(), branchPt.getY(), (1.0 - growth) * r, thetaPrime, depth + 1);
		}
	}
}
Beispiel #9
0
RandomKnot::RandomKnot(const KnotStyle &knotStyle,
                       int windowWidth, int windowHeight, int maxSections)
:   mWindowWidth(windowWidth),
    mWindowHeight(windowHeight),
    mHSections(3 + randomInteger(maxSections - 3)),
    mVSections(3 + randomInteger(maxSections - 3)),
    mOutlineStrokes(knotStyle.outline()),
    mFillStrokes(knotStyle.fill()),
    mHollow(randomFloat() < mPrefs.hollowKnotProbability()),
    mpSectionTypes(0),
    mpSectionCorners(0),
    mpColors(0),
    mDisplayList(0)
{
    // Initialize the knot data.  Derived classes have to establish
    // the proper boundary conditions.
    mpSectionTypes =
        randomDirectionArray(mHSections, mVSections,
                             mPrefs.sectionProbability1(),
                             mPrefs.sectionProbability2());
    mpSectionCorners =
        randomDirectionArray(mHSections + 1, mVSections + 1,
                             mPrefs.cornerProbability1(),
                             mPrefs.cornerProbability2());

    mpSectionColors[BOT] = new int[mHSections * mVSections];
    mpSectionColors[TOP] = new int[mHSections * mVSections];

    if (randomFloat() < mPrefs.symmetricKnotProbability()) {
        // Enforce symmetries.
        enforceHorizontalSymmetry(
            randomFloat() < mPrefs.horizontalMirrorProbability());
        enforceVerticalSymmetry(
            randomFloat() < mPrefs.verticalMirrorProbability());
    }
}
Beispiel #10
0
void ComsManage(void *vParameters)
{
  coms *myComs=(coms*)vParameters;
  char temp;
  while(1)
  {
//    //send();
//    // receive message per major cycle, frequency 5/100
    if (globalCounter%1000==0&&randomInteger(0, 1000)<3) // 750
    {
      *(myComs->thrusterCommand)=receive();
      switch(receive()%6){
        case 0: 
          temp='F';
          break;
        case 1:
          temp='B';
          break;
        case 2:
          temp='L';
          break;
        case 3:
          temp='R';
          break;
        case 4:
          temp='D';
          break;
        default:
          temp='H';
          break;
      }
      if(*(myComs->response)!=temp){
        resVar=!resVar;
        *(myComs->response)=temp;
      }
    }
    vTaskDelay(1000);
  }
}
Beispiel #11
0
    void reset() {
        _x = (SCREEN_WIDTH / 2) - (BALL_SIZE / 2);
        _y = (SCREEN_HEIGHT / 2) - (BALL_SIZE / 2);

        int direction = randomInteger(1, 7);

        switch (direction) {
        case 1:
            // Up/right
            _xSpeed = MAX_BALL_SPEED;
            _ySpeed = -MAX_BALL_SPEED;
            break;
        case 2:
            // Right
            _xSpeed = MAX_BALL_SPEED;
            _ySpeed = 0.0f;
            break;
        case 3:
            // Down/right
            _xSpeed = MAX_BALL_SPEED;
            _ySpeed = MAX_BALL_SPEED;
            break;
        case 4:
            // Down/left
            _xSpeed = -MAX_BALL_SPEED;
            _ySpeed = MAX_BALL_SPEED;
            break;
        case 5:
            // Left
            _xSpeed = -MAX_BALL_SPEED;
            _ySpeed = 0.0f;
            break;
        case 6:
            // Up/left
            _xSpeed = -MAX_BALL_SPEED;
            _ySpeed = -MAX_BALL_SPEED;
            break;
        }
    }
/*
* Function: RunSimulation
* Usage: RunSimulation();
* -----------------------
* This function runs the actual simulation. In each time unit,
* the program first checks to see whether a new customer arrives.
* Then, if the cashier is busy (indicated by a nonzero value for
* serviceTimeRemaining), the program decrements that variable to
* indicate that one more time unit has passed. Finally, if the
* cashier is free, the simulation serves another customer from
* the queue after recording the waiting time for that customer.
*/
void runSimulation() {
	Queue<int> queue;
	int serviceTimeRemaining = 0;
	int nServed = 0;
	long totalWait = 0;
	long totalLength = 0;
	for (int t = 0; t < SIMULATION_TIME; t++) {
		if (randomChance(ARRIVAL_PROBABILITY)) {
			queue.enqueue(t);
		}

		if (serviceTimeRemaining > 0) {
			serviceTimeRemaining--;
			if (serviceTimeRemaining == 0) nServed++;
		} else if (!queue.isEmpty()) {
			totalWait += t - queue.dequeue();
			serviceTimeRemaining = randomInteger(MIN_SERVICE_TIME, MAX_SERVICE_TIME);
		}

		totalLength += queue.size();
	}
	reportResults(nServed, totalWait, totalLength);
}
Beispiel #13
0
unsigned int receive(){
  return randomInteger(0, COMMAX);
}
Beispiel #14
0
void WorldMaze::createRandomMaze(WorldSize size) {
    clearSelection(/* redraw */ false);
    
    int rowsCols = getRowsCols(size) / 2 + 1;
    worldGrid.resize(rowsCols, rowsCols);
    worldGrid.fill(MAZE_FLOOR);
    graph = gridToGraph(worldGrid);
    
    // assign random weights to the edges
    // give each edge a 'random' weight;
    // put all edges into a priority queue, sorted by weight
    Set<Edge*> edgeSet = graph->getEdgeSet();
    int edgeCount = edgeSet.size();
    for (Edge* edge : edgeSet) {
        int weight = randomInteger(1, edgeCount * 1000);
        edge->cost = weight;
    }
    
    // run the student's Kruskal algorithm to get a minimum spanning tree (MST)
    Set<Edge*> mst = kruskal(*graph);
    
    // convert the MST/graph back into a maze grid
    // (insert a 'wall' between any neighbors that do not have a connecting edge)
    graph->clearEdges();
    for (Edge* edge : mst) {
        graph->addEdge(edge->start, edge->finish);
        graph->addEdge(edge->finish, edge->start);
    }

    // physical <-> logical size; a maze of size MxN has 2M-1 x 2N-1 grid cells.
    // cells in row/col 0, 2, 4, ... are open squares (floors), and cells in 
    // row/col 1, 3, 5, ... are blocked (walls).
    int digits = countDigits(rowsCols);
    int worldSize = rowsCols * 2 - 1;
    worldGrid.resize(worldSize, worldSize);
    worldGrid.fill(MAZE_WALL);
    
    pxPerWidth = (double) windowWidth / worldSize;
    pxPerHeight = (double) windowHeight / worldSize;
    
    for (int row = 0; row < worldSize; row++) {
        for (int col = 0; col < worldSize; col++) {
            if (row % 2 == 0 && col % 2 == 0) {
                worldGrid.set(row, col, MAZE_FLOOR);
            }
        }
    }
    
    for (int row = 0; row < rowsCols; row++) {
        int gridRow = row * 2;
        for (int col = 0; col < rowsCols; col++) {
            int gridCol = col * 2;
            std::string name = vertexName(row, col, digits);
            
            // decide whether to put open floor between neighbors
            // (if there is an edge between them)
            for (int dr = -1; dr <= 1; dr++) {
                int nr = row + dr;
                int gridNr = gridRow + dr;
                for (int dc = -1; dc <= 1; dc++) {
                    int nc = col + dc;
                    int gridNc = gridCol + dc;
                    if ((nr != row && nc != col)
                            || (nr == row && nc == col)
                            || !worldGrid.inBounds(gridNr, gridNc)) {
                        continue;
                    }
                    std::string neighborName = vertexName(nr, nc, digits);
                    if (graph->containsEdge(name, neighborName)) {
                        worldGrid.set(gridNr, gridNc, MAZE_FLOOR);
                    }
                }
            }
        }
    }
    
    delete graph;
    graph = gridToGraph(worldGrid);
}
Beispiel #15
0
char randomChar(){
    char alphabet[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    int randomNumber = randomInteger(0, 51);
    char randomCharacter = alphabet[randomNumber];
    return randomCharacter;
}
Beispiel #16
0
void turno(Jogador *x, Jogador *y)
{
	int dano, i;

	puts("\n----------------------------------------------------\n");

	/* Desfaz os efeitos da defesa no turno anterior */
	x->defendido = false;

	switch (x->acao) {
		/* Atacar */
		case 1: 
			printf("> %s ataca", x->nome);
			for (i = 0; i < 3; i++) {
				printf(".");
				fflush(stdout); /* evita que o buffer 'trave' */
				congela(1);
			}

			if (acerto(x->status.agi, y->status.agi)) {
				dano = x->status.atk - y->status.def;
				if (y->defendido) dano -= y->status.def;

				/* Evita dano 0 ou que 'cura' o oponente */
				if (dano <= 0) dano = 1; 

				dano *= x->potencia;
				dano += randomInteger((-dano)/5, dano/5);

				if (critico(x->status.luck)) {
					dano *= 2;
					printf(" CRÍTICO!");
					fflush(stdout);
					congela(1);
				}

				y->status.hp -= dano;
				if (y->status.hp < 0) y->status.hp = 0; /* HP nunca negativo */

				printf("\nTira %d de vida.\n", dano);
			}
			else printf("\n%s se esquivou!\n", y->nome);

			x->potencia = 1;
			break;

		/* Carregar */
		case 2:
			printf("> %s carrega energia.\nO dano agora é x%d!\n", 
				x->nome, ++(x->potencia));
			break;

		/* Defender */
		case 3:
			printf("> %s defende-se. DEF foi dobrada!\n", x->nome);
			if (x->status.hp < x->status.maxHp) {
				puts("Recupera 1 de vida!");
				(x->status.hp)++;
			}
			x->defendido = true;
	}

	puts("\n----------------------------------------------------");
	congela(1);
}
Beispiel #17
0
void
RandomKnot::prepareAnimation(Position extent, bool xRepeat, bool yRepeat)
{
    // Find a random position within the window where the knot will be visible.
    const GLfloat knotWidth = 2.0 * extent.x;
    const GLfloat knotHeight = 2.0 * extent.y;
    if (knotWidth < mWindowWidth && knotHeight < mWindowHeight) {
        mBasePosition =
            Position(randomFloat(mWindowWidth - knotWidth),
                     randomFloat(mWindowHeight - knotHeight))
            + extent;
    } else {
        mBasePosition = Position(randomFloat() * mWindowWidth,
                                 randomFloat() * mWindowHeight);
    }

    // Give the knot a random speed, direction, angle and spin.
    mSpeed = randomFloat(mPrefs.minSpeed(), mPrefs.maxSpeed()) + 0.1;

    GLfloat dir;
    if (randomFloat() < mPrefs.skewProbability()) {
        dir = randomFloat(0.0, M_PI * 2.0);

        if (xRepeat) {
            mAngle = fmod(dir + M_PI_2, M_PI * 2.0);
        } else if (yRepeat) {
            mAngle = dir;
        } else {
            mAngle = randomFloat(0.0, M_PI * 2.0);
        }

    } else {
        int quad;
        if (xRepeat) {
            quad = 2 * randomInteger(2) + 1;
        } else if (yRepeat) {
            quad = 2 * randomInteger(2);
        } else {
            quad = randomInteger(4);
        }
        dir = quad * M_PI_2;
        mAngle = 0.0;
    }
    mDirection = Position(cos(dir), sin(dir));

    if (randomFloat() < mPrefs.spinProbability()) {
        mSpin = randomFloat(mPrefs.minSpin(), mPrefs.maxSpin())
            * ((randomFloat() < 0.5) ? 1.0 : -1.0)
            / 180.0 * M_PI;
    } else {
        mSpin = 0.0;
    }

    // Calculate the starting and stopping times, i.e., the time at which
    // the knot's bounding circle is tangent to the window's bounding circle.
    //
    // - project window midpoint to point P0 on line of movement at time T0.
    // - use Pythagoras to compute distance from P0 to center of knot
    // - calculate T0 - distance and T0 + distance
    const Position midPosition(mWindowWidth * 0.5, mWindowHeight * 0.5);
    const GLfloat t0 = (midPosition - mBasePosition) * mDirection;
    const Position p0 = mBasePosition + t0 * mDirection;

    const GLfloat hyp = norm(midPosition) + norm(extent);
    const GLfloat cat = norm(midPosition - p0);
    const GLfloat distance = sqrt(hyp * hyp - cat * cat);

    mTime    = t0 - distance;
    mMaxTime = t0 + distance;

    // Adjust the spin rate so the angle is consistent at start and stop.
    GLfloat iterations = floor((mMaxTime - mTime) / mSpeed);
    mSpin = floor(mSpin / M_PI * iterations) * M_PI / iterations;
}
Beispiel #18
0
bool critico(int sorte)
{
	int chance = CRIT * (sorte + 10)/10.0;
	return (randomInteger(1, 100) <= chance);
}
Beispiel #19
0
Grid<double> createRandomMaze(int size) {
    Grid<double> maze(size, size, kMazeFloor);
    BasicGraph* graph = gridToGraph(maze, mazeCost);
    
    // assign random weights to the edges
    // give each edge a 'random' weight;
    // put all edges into a priority queue, sorted by weight
    Set<Edge*> edgeSet = graph->getEdgeSet();
    int edgeCount = edgeSet.size();
    for (Edge* edge : edgeSet) {
        int weight = randomInteger(1, edgeCount * 1000);
        edge->cost = weight;
    }
    
    // run the student's Kruskal algorithm to get a minimum spanning tree (MST)
    Set<Edge*> mst = kruskal(*graph);
    
    // convert the MST/graph back into a maze grid
    // (insert a 'wall' between any neighbors that do not have a connecting edge)
    graph->clearEdges();
    for (Edge* edge : mst) {
        graph->addEdge(edge->start, edge->finish);
        graph->addEdge(edge->finish, edge->start);
    }

    // physical <-> logical size; a maze of size MxN has 2M-1 x 2N-1 grid cells.
    // cells in row/col 0, 2, 4, ... are open squares (floors), and cells in 
    // row/col 1, 3, 5, ... are blocked (walls).
    int digits = countDigits(size);
    int worldSize = size * 2 - 1;
    Grid<double> world(worldSize, worldSize, kMazeWall);
    for (int row = 0; row < worldSize; row++) {
        for (int col = 0; col < worldSize; col++) {
            if (row % 2 == 0 && col % 2 == 0) {
                world[row][col] = kMazeFloor;
            }
        }
    }
    
    for (int row = 0; row < size; row++) {
        int gridRow = row * 2;
        for (int col = 0; col < size; col++) {
            int gridCol = col * 2;
            string name = vertexName(row, col, digits);
            
            // decide whether to put open floor between neighbors
            // (if there is an edge between them)
            for (int dr = -1; dr <= 1; dr++) {
                int nr = row + dr;
                int gridNr = gridRow + dr;
                for (int dc = -1; dc <= 1; dc++) {
                    int nc = col + dc;
                    int gridNc = gridCol + dc;
                    if ((nr != row && nc != col)
                            || (nr == row && nc == col)
                            || !world.inBounds(gridNr, gridNc)) {
                        continue;
                    }
                    string neighborName = vertexName(nr, nc, digits);
                    if (graph->containsEdge(name, neighborName)) {
                        world[gridNr][gridNc] = kMazeFloor;
                    }
                }
            }
        }
    }
    
    delete graph;
    return world;
}