Ejemplo n.º 1
0
void Tank::checkWhereAt()
{
	//check coordinates
		Ogre::Vector3 tempCoor = mTankBodyNode->getPosition();
		if(tankSide == 1)
		{
			//we check if we want to do aStar or not 
			if(tempCoor.x > -2125 && tempCoor.x < -625)
			{
				if(tempCoor.z > -2125 && tempCoor.z < 2125)
				{
					//means we are near the spawn point of side A
					currentState = A_STAR;
					aStar(tankSide);
				}
			}
			else if(tempCoor.x > 625 && tempCoor.x < 2125)
			{
				if(tempCoor.z > -2125 && tempCoor.z < 2125)
				{
					currentState = A_STAR;
					aStar(2);
				}
			}
			else
			{
				currentState = WANDER;
				resetWander();
				wanderAStar();
			}
		}
		else if (tankSide == 2)
		{
			if(tempCoor.x > 625 && tempCoor.x < 2125)
			{
				if(tempCoor.z > -2125 && tempCoor.z < 2125)
				{
					currentState = A_STAR;
					aStar(tankSide);
				}
			}
			else if(tempCoor.x > -2125 && tempCoor.x < -625)
			{
				if(tempCoor.z > -2125 && tempCoor.z < 2125)
				{
					//means we are near the spawn point of side A
					currentState = A_STAR;
					aStar(1);
				}
			}
			else
			{
				currentState = WANDER;
				resetWander();
				wanderAStar();
			}

		}
}
Ejemplo n.º 2
0
int main() {
    World theworld2(2);
//    cout << theworld2.getid() << "----" << theworld2.matter.getid() << endl;
     cout << theworld2.getid() << "----" << theworld2.getMatter() << endl;

    for(int i = 3; i < 6; i++)
        World theworld3(i);
    { // begin scope ctor is called
    Star aStar(1234.5, 0.1);
    } //end scope destructor is called
//    InputNum num;
//    cout << "The value is " << num.getValueNum() << endl;
//    num.addInput();
//    cout << "Now the value is " << num.getValueNum() << endl;
    InputNum num("Enter number ");
    num.addInput("Another one ");
    num.addInput("One more ");
    cout << sumString << num.getValueNum() << endl;
    [] {
    std::cout << "hello lambda" << std::endl;
    } (); // prints ‘‘hello lambda’’      //l()
    cout << msg1 << " - " << msg2 << " " << msg3 << endl;
    cout << *msg1 << endl;
    cout << msg2 << endl;
    cout << msg3 << endl;
}
Ejemplo n.º 3
0
	Direction::Enum OnThinkPacman3(const Pawn& in_ourPawn, const World& in_ourWorld, float in_deltaTime, float in_totalTime)
	{
		std::vector<PointObj*> pointObjects;
		in_ourWorld.GetPointObjects(pointObjects);

		Vector2 avgBestLocation = Vector2(0, 0);

		for(auto obj : pointObjects)
		{
			avgBestLocation = avgBestLocation + obj->GetPosition();
		}

		PointObj* closestObject = nullptr;
		float closestSqr = FLT_MAX;
		for (auto obj : pointObjects)
		{
			float distanceSqr = (obj->GetPosition() - avgBestLocation).MagnitudeSqr();
			if(distanceSqr < closestSqr)
			{
				closestSqr = distanceSqr;
				closestObject = obj;
			}
		}

		if (!closestObject)
			return Direction::Invalid;

		PathNode* start = in_ourWorld.GetNode(in_ourPawn.GetClosestNode());
		PathNode* destination = in_ourWorld.GetNode(closestObject->GetNode());

		return aStar(in_ourWorld, start, destination);
	}
Ejemplo n.º 4
0
int main()
{
    createMap();
    printMap();
    aStar();

    return 0;
}
Ejemplo n.º 5
0
void AStarLayer::onEnter(){
    Layer::onEnter();
    
    _addCheckNodeListener = EventListenerCustom::create("AddCheckNode", [&](EventCustom *eventCustom){
        
        AStarDataNode *userData = static_cast<AStarDataNode *>(eventCustom->getUserData());
        Sprite *checkNode = Sprite::create("res/astar_check.png");
        checkNode->setAnchorPoint(Vec2(0, 0));
        checkNode->setPosition(userData->column * 20, userData->row * 20);
        this->addChild(checkNode, 5);
        
    });
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(_addCheckNodeListener, this);
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    
    AStarDataNode beginNode = AStarDataNode(5, 5, true);
    AStarDataNode targetNode = AStarDataNode(90, 50, true);
    
    Sprite *beginNodeSprite = Sprite::create("res/astar_pathfinder.png");
    beginNodeSprite->setAnchorPoint(Vec2(0, 0));
    beginNodeSprite->setPosition(beginNode.column * 20, beginNode.row * 20);
    this->addChild(beginNodeSprite, 5);
    Sprite *targetNodeSprite = Sprite::create("res/astar_pathfinder.png");
    targetNodeSprite->setAnchorPoint(Vec2(0, 0));
    targetNodeSprite->setPosition(targetNode.column * 20, targetNode.row * 20);
    this->addChild(targetNodeSprite, 10);
    
    Label *starFindPathMenuItemLabel = Label::createWithSystemFont("开始", "Arial", 50);
    starFindPathMenuItemLabel->setColor(Color3B(0, 0, 0));
    MenuItemLabel *starFindPathMenuItem = MenuItemLabel::create(starFindPathMenuItemLabel, [&, beginNode, targetNode](Ref *sender){
        CCLOG("开始寻路");
        
        startTime = clock();
        
        std::vector<AStarDataNode> path = aStar(astarData, beginNode, targetNode);
        
        _calculateAStarTime();
        
        
        
        CCLOG("Path: %d", static_cast<int>(path.size()));
        for (std::vector<AStarDataNode>::iterator iter = path.begin(); iter != path.end(); ++iter){
            //        CCLOG("(%d, %d)", static_cast<int>(iter->column), static_cast<int>(iter->row));
            Sprite *path = Sprite::create("res/astar_pathfinder.png");
            path->setAnchorPoint(Vec2(0, 0));
            path->setPosition(iter->column * 20, iter->row * 20);
            this->addChild(path, 5);
        }
        
    });
    Menu *starFindPathMenu = Menu::create(starFindPathMenuItem, NULL);
    starFindPathMenu->setPosition(visibleSize.width - 100, 50);
    this->addChild(starFindPathMenu, 100);
    
}
Ejemplo n.º 6
0
void getNext(DataForAI& data)
{
	nextStep[data.myID].resize(0);
	short i=data.myID;
	Point goalTank;
	goalTank.row=data.tank[i].row;
	goalTank.col=data.tank[i].col;
	next[i]=aStar(nearestS[i],goalTank,data);
	//printf("round%d next step for tank%d:(%d,%d)\n",data.round,data.myID,next[i].row,next[i].col);
}
Ejemplo n.º 7
0
void Loop::findPath()
{
	//Run triangulation if topology changed
	if (!mIsDelaunayUpToDate)
	{
		clearVector(mVertices);

		for (std::vector<Block>::const_iterator it = mBlocks.begin(); it != mBlocks.end(); ++it)
		{
			mVertices.push_back(it->getPosition());
		}

		//Screen corners
		mVertices.push_back(Vector2(GUI_WIDTH - 1.0f, -1.0f));
		mVertices.push_back(Vector2(SCREEN_WIDTH, -1.0f));
		mVertices.push_back(Vector2(SCREEN_WIDTH, SCREEN_HEIGHT));
		mVertices.push_back(Vector2(GUI_WIDTH - 1.0f, SCREEN_HEIGHT));

		clearVector(mTriangles);

		triangulate(mVertices, mTriangles, mNeighborhoodGraph);
		mIsDelaunayUpToDate = true;
	}

	//If no leader found, only Delaunay triangles drawn
	if (mLeader != 0)
	{
		float xMin = GUI_WIDTH - 1.0f;
		float xMax = SCREEN_WIDTH;
		float yMin = -1.0f;
		float yMax = SCREEN_HEIGHT;
		const float screenBoundaries[] = { xMin, xMax, yMin, yMax };

		clearVector(mPathVertices);
		if (aStar(mPathVertices, mLeader->getPosition(), mPathFinish, mTriangles, mNeighborhoodGraph, mBlocks, screenBoundaries))
		{
			mGui.print("Path found to target.");
		}
		else
		{
			mGui.print("No accessible path to target.");
		}
	}
}
Ejemplo n.º 8
0
void Snake::update(const Grid<L,W>& g,const Point& a)
{
  if (pointToRemove)
    delete pointToRemove;
  pointToRemove=NULL;
  if(length==tail.size())
    {
      // pop body
      pointToRemove=new Point();
      *pointToRemove=tail.back();
      tail.pop_back();
    }

  tail.push_front(head);

  // compute the new head pos
  // head=dumbAI(g,a);
  // head=lessDumbAI(g,a);
  // head=randomAI(g,a);
  head=aStar(g,a);
}
Ejemplo n.º 9
0
std::vector<Eigen::Vector3f> PathPlanner::getPath(Eigen::Vector3f start, Eigen::Vector3f end, cv::Mat3b * image)
{
    std::vector<Eigen::Vector3f> path;
    std::vector<Eigen::Vector2i> pathImg;

    //Objects are outside the configuration space, so get the closest point
    Eigen::Vector2i lastPoint;
    if(!validPoint(worldToImg(end)))
    {
        if(!findClosestPoint(start, end, bot_in_pixels_))
        {
            return path;
        }
    }

    //Check if we can just go straight there unobstructed
    if(traceLine(worldToImg(start), worldToImg(end)))
    {
        path.push_back(start);
        path.push_back(end);
    }
    else if(aStar(worldToImg(start), worldToImg(end), pathImg))
    {
        pathImg = smoothPath(pathImg);

        for(size_t i = 0; i < pathImg.size(); i++)
        {
            path.push_back(imgToWorld(pathImg.at(i)));
        }
    }

    if(image)
    {
        drawPath(path, *image);
    }

    return path;
}
Ejemplo n.º 10
0
void AlgoRitmeWeek1::doAction(Koetje* koe, std::vector<Node*> collection, Haasje* haasje){
    aStar(koe, collection, haasje->getNode());
}
Ejemplo n.º 11
0
void Pathfinder::routeNets(int nrAttempts){
	list<int> targetNodes;
	map<int,t_nets>::iterator nets_it;
	list<int>::iterator netTree_it;
	vector<int>::iterator netTree_it2;
	vector<int>::iterator nodes_it;
	
	//Initializations
	clock_t start=clock(); 
	actualAttempt=0;
	trace_id=0;
	conflicts=0;
	visited=0;
	netlist.erase(blockageNet);
	for(nets_it=netlist.begin(); nets_it!=netlist.end(); ++nets_it){
		//cout << (nets_it->second).nodes[0] << endl;
		if(rand()%2==0) getCenter((nets_it->second).nodes);	
		//cout << (nets_it->second).nodes[0] << endl;
	}	
	//Pathfinder Routing
	cout << "-> Routing graph..." << endl;
	do{		
		// Loop over all nets
		for(nets_it=netlist.begin(); nets_it!=netlist.end(); ++nets_it){
			if(nets_it->second.conflict){
				//If conflict exists, check it out and do rip-upand re-route. Otherwise jump net.
				--conflicts;
				nets_it->second.conflict=false;
				for(netTree_it=nets_it->second.netTree.begin();netTree_it!=nets_it->second.netTree.end(); ++netTree_it){
					if(graph[*netTree_it].nrNets>1){
						nets_it->second.conflict=true;
						break;
					}
				}
			}
			if(nets_it->second.conflict | !actualAttempt){
				//Rip-up net 
				for(netTree_it=(nets_it->second).netTree.begin(); netTree_it!=(nets_it->second).netTree.end(); ++netTree_it){
					if(!isSource(*netTree_it)){
						--graph[*netTree_it].nrNets;
						if(getNet(*netTree_it)==nets_it->first)  graph[*netTree_it].net=0; 
					}
				}
				//Clear netTree	of the net
				(nets_it->second).netTree.clear();
				(nets_it->second).routeResult.clear();
				
				//Create list of target nodes 
				targetNodes.clear();
				for(nodes_it=(nets_it->second).nodes.begin();nodes_it!=(nets_it->second).nodes.end(); ++nodes_it){
					targetNodes.push_back(*nodes_it);
					//cout << *nodes_it << endl;
				}		
				//Insert the first node to the tree
				(nets_it->second).netTree.push_back(*targetNodes.begin());
				targetNodes.erase(targetNodes.begin());
				//Loop until all sinks have been found
				while(!targetNodes.empty() && aStar(nets_it, targetNodes)){}  //Route the tree to the closest node in the graph
				
				if(!targetNodes.empty()) break;
				if(nets_it->second.conflict) ++conflicts;
			}
		}
		//update H cost
		++trace_id;
		for(nets_it=netlist.begin(); nets_it!=netlist.end(); ++nets_it){
			if(nets_it->second.conflict){
				for(netTree_it=nets_it->second.netTree.begin();netTree_it!=nets_it->second.netTree.end(); ++netTree_it){
					if(graph[*netTree_it].nrNets>1 && graph[*netTree_it].idNr!=trace_id){
						++graph[*netTree_it].history;
						graph[*netTree_it].idNr=trace_id;
					}
				}
			}
		}
		
		if(!(++actualAttempt%15)) cerr << "." << conflicts << ".";				
		//		cout << conflicts << endl;
	}while(targetNodes.empty() && conflicts && actualAttempt<nrAttempts);
	//	cout << visited << endl;
		cout << endl << "-> Runtime = " << float((clock()-start)/(CLOCKS_PER_SEC/1000))/1000 << "s" << endl;
	if(!targetNodes.empty()) cout << "-> Impossible to route net: " << nets_it->first << endl;		
	if(conflicts || !targetNodes.empty()){
		cout <<"-> Unable to route the circuit after ";
		cout << actualAttempt << " attempts."<< endl;
	}else{
		cout <<"-> Routing finished in ";
		cout << actualAttempt << " attempts."<< endl;
		showResult();
	}
	if(!targetNodes.empty() || conflicts)
        throw AstranError("Could not finish routing");
}
Ejemplo n.º 12
0
void pathfinder( const BNavmesh *navmesh, const BVector *start, const BVector *end, BPath *outPath )
{
	assert( outPath->numVertices == 0 );
	
	const BTriangle *const startTriangle = findTriangleContainingPoint( navmesh, start );
	const BTriangle *const endTriangle = findTriangleContainingPoint( navmesh, end );
	const BTriangle *adjustedStartTriangle, *adjustedEndTriangle;
	BVector adjustedStart, adjustedEnd;

	if ( startTriangle == NULL )
	{
		projectPointOntoNavmesh( navmesh, start, &adjustedStartTriangle, &adjustedStart );
	}
	else
	{
		adjustedStart = *start;
		adjustedStartTriangle = startTriangle;
	}
	assert( adjustedStartTriangle );

	const int isDestinationReachable = endTriangle != NULL && endTriangle->connectedComponent == adjustedStartTriangle->connectedComponent;
	if ( !isDestinationReachable )
	{
		projectPointOntoConnectedComponent( navmesh, end, adjustedStartTriangle->connectedComponent, &adjustedEndTriangle, &adjustedEnd );
	}
	else
	{
		adjustedEnd = *end;
		adjustedEndTriangle = endTriangle;
	}
	assert( adjustedEndTriangle );

	assert( isPointInsideNavmeshTriangle( navmesh, &adjustedStart, adjustedStartTriangle ) );
	assert( isPointInsideNavmeshTriangle( navmesh, &adjustedEnd, adjustedEndTriangle ) );

	BAStarOutput aStarOutput;
	aStar( navmesh, adjustedStartTriangle, adjustedEndTriangle, &adjustedEnd, &aStarOutput );
	
	funnelPath( navmesh, &adjustedStart, &adjustedEnd, &aStarOutput, outPath );
	
	freeAStarOutput( &aStarOutput );
	
	assert( outPath->numVertices > 0 );
	assert( outPath->vertices != NULL );

	if ( !vectorEquals( start, &adjustedStart ) )
	{
		BVector *newVertices = malloc( ( 1 + outPath->numVertices ) * sizeof( BVector ) );
		newVertices[0] = *start;
		memcpy( &newVertices[1], outPath->vertices, ( outPath->numVertices ) * sizeof( BVector ) );
		free( outPath->vertices );
		outPath->vertices = newVertices;
		outPath->numVertices++;
	}

	if ( isDestinationReachable && !vectorEquals( end, &adjustedEnd ) )
	{
		BVector *newVertices = malloc( ( 1 + outPath->numVertices ) * sizeof( BVector ) );
		newVertices[outPath->numVertices] = *end;
		memcpy( newVertices, outPath->vertices, ( outPath->numVertices ) * sizeof( BVector ) );
		free( outPath->vertices );
		outPath->vertices = newVertices;
		outPath->numVertices++;
	}
	
}
Ejemplo n.º 13
0
void movimiento_t::logica_movimiento() {


    char cad[255];
    vector<node> nodosDefault;
    vector<node> nodosWalk;
    vector<node> &nodos = nodosDefault;

    int tipo_mov;
    int PM = mechs->mechJugador->dmj->PM_andar;

    int estrategia = estrategia_movimiento(); //ATACAR o DEFENDER

    int tons = mechs->mechJugador->defMechInfo->toneladas;
    int col_mech = mechs->mechJugador->pos_Hexagono.columna;
    int fil_mech = mechs->mechJugador->pos_Hexagono.fila;
    const bool estabaEnSuelo = mapa->info_mechs->mechJugador->enElSuelo;
    int lado_mech = mechs->mechJugador->encaramiento_mech;
    this->destino.fila = fil_mech;
    this->destino.columna = col_mech;
    this->lado = lado_mech;
    int col_dest, fil_dest, lado_dest;

    pasos = 0;
    //Si esta  en el suelo intentar levantarse

    //ATACAR O DEFENDER

    sprintf(cad, "%s : Posicion mech jugador: fila: %i,columna: %i,lado: %i \n\n", ctime(&tiempo), fil_mech, col_mech, lado_mech);
    flog += cad;

    int tipo_mov_get_destino = getDestino(fil_mech, col_mech, fil_dest, col_dest, lado_dest, estrategia);
    if (fil_dest == -1 && col_dest == -1 && lado_dest == -1) {
        sprintf(cad, "El jugador no tiene PM asi que permanecera inmovil.\n");
        flog += cad;
        tipo_movimiento = INMOVIL;
        //cout << "El jugador no tiene PM asi que permanecera inmovil." << endl;
        //cin.get();
        return;
    } else if (fil_dest == fil_mech && col_dest == col_mech && lado_dest == lado_mech && !estabaEnSuelo) {
        sprintf(cad, "El jugador decide permanecer inmovil.\n");
        flog += cad;
        //cout << "El jugador decide permanecer inmovil.(Destino elegido pos. actual)" << endl;
        //cin.get();
        tipo_movimiento = INMOVIL;
        return;

    }



    sprintf(cad, "%s : Destino final de movimiento: fila: %i,columna: %i,lado: %i \n\n", ctime(&tiempo), fil_dest, col_dest, lado_dest);
    flog += cad;



    if (tipo_mov_get_destino == SALTAR) {
        tipo_movimiento = SALTAR;
        this->destino.fila = fil_dest;
        this->destino.columna = col_dest;
        this->lado = lado_dest;
        //cout << "El jugador decide saltar a la pos " << destino.stringPos() << endl;
        //cin.get();
        return;

    }

    if (tipo_mov_get_destino != SALTAR) {

        node *destino = new node(fil_dest, col_dest, lado_dest, mapa, tons);

        node *inicio = new node(fil_mech, col_mech, lado_mech, destino, mapa, tons);
        aStar(inicio, destino, nodosDefault, mapa, tons);
        delete inicio;
        delete destino;

        destino = new node(fil_dest, col_dest, lado_dest, mapa, tons);
        inicio = new node(fil_mech, col_mech, lado_mech, destino, mapa, tons);

        aStar(inicio, destino, nodosWalk, mapa, tons, WALK);
        delete inicio;
        delete destino;

        if (nodosWalk.back().coste + 1 < nodosDefault.back().coste) {
            tipo_mov = ANDAR;
            nodos = nodosWalk;
            if (nodos[1].coste >= PM) {
                sprintf(cad, "%s : Como no podemos realizar la ruta nos encaramos al enemigo.\n\n", ctime(&tiempo), fil_dest, col_dest, lado_dest);
                flog += cad;
                fil_dest = fil_mech;
                col_dest = col_mech;
                mapa->encarar_objetivo(fil_enemigo, col_enemigo, fil_mech, col_mech, lado_dest);

                destino = new node(fil_dest, col_dest, lado_dest, mapa, tons);
                inicio = new node(fil_mech, col_mech, lado_mech, destino, mapa, tons);

                aStar(inicio, destino, nodos, mapa, tons, WALK);
                delete inicio;
                delete destino;
            }

        } else {
            tipo_mov = tipo_movim(nodosDefault);
            nodos = nodosDefault;
        }
        ///////////////
        if (!estabaEnSuelo && mapa->info_mechs->mechJugador->dmj->PM_saltar > 1) {
            int PS = mapa->info_mechs->mechJugador->dmj->PM_saltar;
            int filS, colS;
            saltoIntermedio(fil_mech, col_mech, fil_dest, col_dest, filS, colS, mapa, PS);

            sprintf(cad, "%s : El mech saltara a la posicion f:%i c:%i\n\n", ctime(&tiempo), filS, colS);
            flog += cad;


            tipo_movimiento = SALTAR;
            mapa->encarar_objetivo(fil_enemigo, col_enemigo, filS, colS, this->lado);
            this->destino.fila = filS;
            this->destino.columna = colS;

            //cout << "El jugador decide saltar a la pos " << this->destino.stringPos() << endl;
            //cin.get();
            return;

        } else {
            sprintf(cad, "%s : El mech realizara la ruta a pie\n\n", ctime(&tiempo));
            flog += cad;
            if (nodos[1].coste >= PM) {

                //SALTAR
                sprintf(cad, "%s : Como no podemos realizar la ruta nos encaramos al enemigo.\n\n", ctime(&tiempo), fil_dest, col_dest, lado_dest);


                fil_dest = fil_mech;
                col_dest = col_mech;
                mapa->encarar_objetivo(fil_enemigo, col_enemigo, fil_mech, col_mech, lado_dest);

                //                node *destino = new node(fil_dest, col_dest, lado_dest, mapa, tons);
                //                node *inicio = new node(fil_mech, col_mech, lado_mech, destino, mapa, tons);
                //                aStar(inicio, destino, nodos, mapa, tons);
                //                delete inicio;
                //                delete destino;

            }

        }

        tipo_movimiento = tipo_mov;
        switch (tipo_mov) {
            case ANDAR:
                PM = mechs->mechJugador->dmj->PM_andar;
                break;
            case CORRER:
                PM = mechs->mechJugador->dmj->PM_correr;
                break;
        }//Aniadir saltar



        if (mapa->info_mechs->mechJugador->enElSuelo) {


            if (PM >= 2 && mapa->info_mechs->mechJugador->equilibrio_ok()) {
                cout << "Intentamos levantarnos" << endl;

                tiempo = time(&tiempo);
                sprintf(cad, "%s : El mech %i esta en el suelo e intentara levantarse\n\n", ctime(&tiempo), mapa->info_mechs->mechJugador->numJ);
                flog += cad;

                tipo[pasos] = MOV_LEVANTARSE;
                veces[pasos] = nodos[0].orientacion;
                pasos++;
                this->destino.fila = nodos[0].fil;
                this->destino.columna = nodos[0].col;
                this->lado = nodos[0].orientacion;


                /* Actualizar los PM que llevamos usados */
                /* Para simplificar, suponemos que tenemos ambos brazos y no estan danhados */
                PM -= 2;
            } else {
                sprintf(cad, "%s : El mech %i no puede levantarse\n\n", ctime(&tiempo), mapa->info_mechs->mechJugador->numJ);
                flog += cad;
                tipo_movimiento = INMOVIL;
                //cout << "El mech no puede levantarse " << endl;
                //cin.get();
                return;

            }
        }
    }

    printf("El camino al destino es el siguiente:\n");
    show(nodos);
    getSecuenciaPasos(nodos, PM);

    sprintf(cad, "%s : Destino alcanzado: fila: %i,columna: %i,lado: %i \n\n", ctime(&tiempo), this->destino.fila, this->destino.columna, this->lado);
    flog += cad;

    //cout << "Fin de logica de mov" << endl;
    //cin.get();

}
Ejemplo n.º 14
0
void Tank::update(const float& deltaTime, std::vector<PowerUpSpawn*> mPowerUpSpawns){
	
	//this check must be first
	if (!isAlive())
	{
		deathTimer -= deltaTime;

		if (deathTimer <= 0.f)
		{
			deathTimer = 0.f;
			resetAll();
			
			std::random_device rd;
			std::mt19937 random(rd());

			if (tankSide == 1)
			{
				std::uniform_real_distribution<double> randomGen1(1, 5);
				int tempNumber = randomGen1(random);
				std::uniform_real_distribution<double> randomGen2(0, 36);
				int tempNumber2 = (36 * (int)randomGen2(random)) + (int)tempNumber;

				Ogre::Vector3 position = pathFindingGraph->getPosition(tempNumber2);

				mTankBodyNode->setPosition(position);
			} else if(tankSide == 2){
				std::uniform_real_distribution<double> randomGen1(31, 35);
				int tempNumber = randomGen1(random);
				std::uniform_real_distribution<double> randomGen2(0, 36);
				int tempNumber2 = (36 * (int)randomGen2(random)) + (int)tempNumber;
				
				Ogre::Vector3 position = pathFindingGraph->getPosition(tempNumber2);

				mTankBodyNode->setPosition(position);
			}
			mTankBodyNode->setVisible(true);
			setSelected(false);
		}
	}

	//Check for tank powerups
	sphereSceneTime += deltaTime;
	if(sphereSceneTime > 0.2)
	{
		sphereSceneTime = 0;

		Ogre::Vector3 tankCenter = mTankBodyNode->getPosition();
		int location;
		bool found = false;

		for(int i = 0; i < mPowerUpSpawns.size(); i++)
		{
			Ogre::Vector3 powerUpLocation = mPowerUpSpawns[i]->spawnNode->getPosition();
			if(tankCenter.squaredDistance(powerUpLocation) < 5625) //squaredDistance is better
			{
				found = true;
				location = i;
			}
		}
		if (found)
		{
			if(mPowerUpSpawns[location]->getIsPowerUp())
			{
				char tempType = mPowerUpSpawns[location]->pickupPowerUp(mSceneMgr);

				printf("Got Powerup %c\n", tempType);

				switch(tempType)
				{
					case ('H'): //health
					{
						hp += 0.1f;
						if (hp > 1.0f)
						{
							hp = 1.0f;
						}
						printf("Got Health\n");

						//update healthbar
						float healthBarAdjuster = (1.0 - hp) / 2;
						mHealthBarBB->setTexcoordRect(0.0 + healthBarAdjuster, 0.0, 0.5 + healthBarAdjuster, 1.0);
					}
					break;
					case ('R'): //fire rate
					{
						fireRate = 1.f;
						powerUpDurationR = 6.f;
					}
					break;
					case ('S'): //speed
					{
						mRotSpd = 75.0f;
						ms = 100.f;
						mMoveSpd = 100.f;
						powerUpDurationS = 6.f;
					}
					break;
					case ('P'): //damage
					{
						dmg = 30.f;
						powerUpDurationP = 6.f;
					}
					break;
					default:
						printf("Unknown Powerup\n");
					break;
				}
			}
			currentState = WANDER;
			resetWander();
			wanderAStar();
		}
	}

	decrementPowerups(deltaTime);

	//weapontimer
	weaponTimer += deltaTime;

	//seek powerups
	/*
	Ogre::Real distancePowerUp = 0;
	int powerUpNo = 0;
	bool firstTimeDistanceCheck = true;
	for(int i = 0; i < mPowerUpSpawns.size(); i++)
	{
		if(mPowerUpSpawns[i]->getIsPowerUp())
		{
			Ogre::Real tempDistancePowerUp = mTankBodyNode->getPosition().distance(mPowerUpSpawns[i]->getPowerLocation());

			if(firstTimeDistanceCheck)
			{
				firstTimeDistanceCheck = false;
				distancePowerUp = tempDistancePowerUp;
			}
			if(tempDistancePowerUp < distancePowerUp)
			{
				distancePowerUp = tempDistancePowerUp;
				powerUpNo = i;
			}
		}
	}*/
	/*
	if(distancePowerUp < 500 && distancePowerUp > 0 && currentState != POSSESSED)
	{
		if(mPowerUpSpawns[powerUpNo]->getIsPowerUp())
		{
			if(currentState != SEEK)
			{
				currentState = SEEK;
				seekTarget = mPowerUpSpawns[powerUpNo]->getPowerLocation();
				seekAStar();
			}
			
		}
		else 
			currentState = WANDER;
		
	}*/
	
	//check if the user is like somewhere and stopped ocassionally 
	if (currentState != POSSESSED)
	{
		checkPosition += deltaTime;
		if(checkPosition > 3)
		{
			if(mTankBodyNode->getPosition().x == previousLocation.x)
			{
				if(mTankBodyNode->getPosition().z == previousLocation.z)
				{
					checkWhereAt();
				}
			}
			checkPosition = 0;
			previousLocation = mTankBodyNode->getPosition();
		}
	
		checkOrientation += deltaTime;
		if(checkOrientation > 15)
		{
			if(currentState != A_STAR)
			{
				if(!orientationEquals(initBodyOrientation, mTankBodyNode->getOrientation()))
				{
					mTankBodyNode->setOrientation(initBodyOrientation);
				}
				if(!orientationEquals(initBarrelOrientation, mTankBarrelNode->getOrientation()))
				{
					mTankBarrelNode->setOrientation(initBarrelOrientation);
				}
				if(!orientationEquals(initTurretOrientation, mTankTurretNode->getOrientation()))
				{
					mTankTurretNode->setOrientation(initTurretOrientation);
				}
			}
			checkOrientation = 0;
		}
	}

	//no movement for body yet

	//A_STAR, SEEK, WANDER, ESCAPE, STOP
	switch(currentState)
	{
		case A_STAR:
			//initiate astar
			if(tankStarted == false)
			{
				tankStarted = true;
				aStar(tankSide); //creates the path to get out of there
			}
			else
			{
				aStarMovement(deltaTime);
			}
		break;
		case FIRE:
		{
			Ogre::Vector3 targetPosition = getPredictPos(target);
			targetPosition.y = 16.f;

			Ogre::Degree angle = getShootingAngle(targetPosition);

			mTankTurretNode->lookAt(targetPosition, Ogre::Node::TransformSpace::TS_WORLD, Ogre::Vector3::NEGATIVE_UNIT_X);
			//barrelDegree = angle;
			if (weaponTimer > 4)
			{
				tnkMgr->createProjectile(mTankBodyNode->getPosition(), mTankTurretNode->_getDerivedOrientation(), angle, shootingVelocity, dmg);
				weaponTimer = 0;
			}
			if (target->hp <= 0 || mTankBodyNode->getPosition().distance(target->getPosition()) > 600 )
				currentState = WANDER;
		}
		case WANDER:
			//wander(deltaTime);
			wanderMovement(deltaTime);
			break;
	
		case SEEK:
			//seek(mPowerUpSpawns[powerUpNo]->getPowerLocation(), deltaTime);

			//seek(Ogre::Vector3::ZERO, deltaTime);
			//seekMovement(deltaTime);
		break;
		case ESCAPE:
			
		break;
		case STOP:
		
		break;

		case POSSESSED: {
			Ogre::Vector3 rayDest;

			if (mMove < 0)
				rayDest = mTankBodyNode->getOrientation() * Ogre::Vector3(-1,0,0);
			else if (mMove > 0)
				rayDest = mTankBodyNode->getOrientation() * Ogre::Vector3(1,0,0);


			//THIS IS WHERE THE TANK IS MOVED WHEN PROCESSING

			//if (rayDest != NULL)
			{
				Ogre::Ray shootToCheckWall = Ogre::Ray(mTankBodyNode->getPosition(), rayDest);

				Ogre::RaySceneQuery* mRaySceneQuery = mSceneMgr->createRayQuery(shootToCheckWall, Ogre::SceneManager::ENTITY_TYPE_MASK);
				mRaySceneQuery->setSortByDistance(true);

				// Ray-cast and get first hit
				Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
				Ogre::RaySceneQueryResult::iterator itr = result.begin();

				bool hit = false;
				for (itr = result.begin(); itr != result.end(); itr++) 
				{
					
					std::string x = itr->movable->getName();
					printf("Check %s \n", x.c_str());

					if (x[0] == 'C' && itr->distance < 10)
					{
						printf("Too close to %s: %f \n", x.c_str(), (float)itr->distance);
						hit = true;
					}
				}

				if(hit == false)
				{
				
					mTankBodyNode->translate(mMove * deltaTime * mMoveSpd, 0, 0, Ogre::Node::TransformSpace::TS_LOCAL);
				}
			}		

			mTankBodyNode->yaw(Ogre::Degree(bodyRotate * deltaTime * mRotSpd));

			// Rotate the tank turret
			mTankTurretNode->yaw(Ogre::Degree(turretRotation * deltaTime * mRotSpd * 1.5));

			turretDegree += turretRotation;

			//to move barrel change barrelRotation
			float barrelChange = barrelRotation * deltaTime * mRotSpd;
			barrelDegree += barrelChange;

			if(barrelDegree > 30)
				barrelDegree = 30;
			else if(barrelDegree < 0)
				barrelDegree = 0;
			else
				mTankBarrelNode->roll(Ogre::Degree(-barrelChange));				
		}

		break;
	}

	Ogre::Vector3 setpos = mTankBodyNode->getPosition();
	setpos.y = 13.f;
	mTankBodyNode->setPosition(setpos);

}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();
    SDL_Surface* ecran = NULL, *ecranSurface = NULL;
    //SDL_Surface *ecran2;
    //ecran = SDL_CreateRGBSurface(0,700,700,32,0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
    SDL_Rect origine;
    origine.x = 0;
    origine.y = 0;

    /*TTF_Font *police = NULL;
    SDL_Color couleurNoire = {0, 0, 0};
    police = TTF_OpenFont("annexes/Arial.ttf", 18);
    texte = TTF_RenderText_Blended(police, "Projet d'info !!!!!!!!!!!!!", couleurNoire);
    position.x = 10;
    position.y = 10;
    SDL_BlitSurface(texte, NULL, ecran, &position);*/

    ecranSurface = SDL_CreateRGBSurface(SDL_HWSURFACE, 0, 0, 32, 0, 0, 0, 0); // On cre notre surface de dpart : un rectangle de taille nulle !
    int i;

    char * nomImages[NB_IMAGES] = { "M", "M1", "M2", "M3","M3b", "M4", "M5", "M6", "M7", "M7b" ,"M8", "M9", "M10", "M11", "M12", "M13", "M14", "T1", "T2", "T3", "RA", "RB", "RC", "RD", "RE", "Val"};
    /*char tmp[TAILLE_NOM] ="";
    SDL_Surface * tabImages[NB_IMAGES];
    for ( i = 0 ; i < NB_IMAGES ; i++ )
    {
    	strcat(tmp,CHEMIN);
    	strcat(tmp,nomImages[i]);
    	strcat(tmp,".png");
    	printf("%s\n",tmp);
    	tabImages[i] = IMG_Load(tmp);
    	strcpy(tmp,"");
    }

    for ( i = 0 ; i < NB_IMAGES ; i++ )
    {
    	//position.x=30*i%610;
    	//position.y=30*i/610;
    	position.x=30*i;
    	position.y=30*i;
    	SDL_BlitSurfaceSecure(tabImages[i], NULL, ecran, &position);
    }*/
    //tabImage[PIETON]

    int nbStation, numDep, numArr;
    char nomDep[TAILLE_NOM], nomArr[TAILLE_NOM];
    char nom[] =  "graphes/metro2012.csv";
    Station * plan = NULL;
    puts("lecture ...");
    plan = lecture(nom, &nbStation);

    ListeRes resultat = NULL;
    ListeChangement final = NULL;

    puts("Choix de la station de départ :");
    fgets(nomDep,TAILLE_NOM,stdin);
    nomDep[strlen(nomDep)-1]='\0';
    numDep = nomToNum(nomDep, plan, nbStation);

    viderBuffer();

    puts("Choix de la station d'arrivée :");
    fgets(nomArr,TAILLE_NOM,stdin);
    nomArr[strlen(nomArr)-1]='\0';
    numArr = nomToNum(nomArr, plan, nbStation);

    puts("aStar ...");
    resultat = aStar(numDep, numArr, plan);
    afficherRes(resultat);

    puts("Changement :");
    final = traitementAffichage(resultat);
Ejemplo n.º 16
0
void AlgoRitmeWeek1::goToPlace(Beestje* beestje, std::vector<Node*> collection, Node* destination){
    aStar(beestje, collection, destination);
}
Ejemplo n.º 17
0
int main( int argc, char* argv[] )
{
	//***MPI: INITIAL STEPS***
	MPI::Init ();  //Initialize MPI.
	int procid = MPI::COMM_WORLD.Get_rank ( );  //Get the individual process ID.
	int nprocs = MPI::COMM_WORLD.Get_size ( );

	//***MPI: ALL PROCESSORS PARSE THE COMMAND LINE***
	//get mandatory command line arguments
	char* VarFilePath = argv[1];
	char* DatFilePath = argv[2];
	
	//initialize optional command line arguments
	unsigned int MinCoreSize;
	unsigned int MaxCoreSize;
	int SamplingFreq;
	int NumReplicates;
	char* OutFilePath;
	char* KerFilePath;
	char* IdealFilePath;

	//declare variables
	unsigned int i, j;
	int b;
	string DoM = "no"; //switch to perform M+ optimization
	string Rarify = "no"; //switch to use rarefaction to correct allele count for sample size differences
	string Kernel = "no"; //switch to include a mandatory set in the core
	string Ideal = "no"; //switch to compute the ideal core, using A* algorithm
	vector<std::string> KernelAccessionList;
	vector<std::string> BadFiles;
	string bf;

	//parse the command line for options
	for (int i=0;i<argc;i++)
	{
		if ( string(argv[i]) == "-m" ) 
    	{
        	DoM = "yes";
        	MinCoreSize = atoi(argv[i+1]);
			MaxCoreSize = atoi(argv[i+2]);
			SamplingFreq = atoi(argv[i+3]);
			NumReplicates = atoi(argv[i+4]);
			OutFilePath = argv[i+5];
		}

		if ( string(argv[i]) == "-r" ) 
    	{
        	Rarify = "yes";
		}

		if ( string(argv[i]) == "-k" ) 
    	{
        	Kernel = "yes";
        	KerFilePath = argv[i+1];
        	KernelAccessionList = MySetKernel(KerFilePath);
			//verify that specified input file actually exists
			if (fileExists(KerFilePath) == 0) 
			{
				bf = "KerFilePath = ";
				bf += KerFilePath;
				BadFiles.push_back(bf);
			}
		}
		
		if ( string(argv[i]) == "-a" ) 
    	{
        	Ideal = "yes";
        	IdealFilePath = argv[i+1];
		}
	}
	
	//test whether all files specified on the command line exist
	if (fileExists(VarFilePath) == 0) 
	{
		bf = "VarFilePath = ";
		bf += VarFilePath;
		BadFiles.push_back(bf);
	}
	if (fileExists(DatFilePath) == 0) 
	{
		bf = "DatFilePath = ";
		bf += DatFilePath;
		BadFiles.push_back(bf);
	}
	
	if (BadFiles.size() > 0)
	{
		//***MPI: MASTER 0 SHARES THE BAD NEWS***
		if ( procid == 0)
		{
			cout << "\nThe following variables appear to contain misspecified paths:\n";
			for (i=0;i<BadFiles.size();++i)
			{
				cout << "  " << BadFiles[i] << "\n";
			}
			cout << "\nPlease check the command line.  Quitting...\n\n";
		}
		
		//***MPI: ALL PROCESSORS QUIT***
		exit (EXIT_FAILURE);
	}
	
	//***MPI: MASTER 0 PRINTS RUN SPECS***
	//print out input variables
	if ( procid == 0 )
	{
		cout << "Input variables:\n  VarFilePath = " << VarFilePath << "\n";
		cout << "  DatFilePath = " << DatFilePath << "\n";
		if (DoM == "yes")
		{
			cout << "  -m invoked:\n";
			cout << "    MinCoreSize = " << MinCoreSize << "\n";
			cout << "    MaxCoreSize = " << MaxCoreSize << "\n";
			cout << "    SamplingFreq = " << SamplingFreq << "\n";
			cout << "    NumReplicates = " << NumReplicates << "\n";
			cout << "    OutFilePath = " << OutFilePath << "\n";
		}
		if (Rarify == "yes")
		{
			cout << "  -r invoked:\n";
			cout << "    Using rarefaction for M+ search\n";
		}
		if (Kernel == "yes") 
		{
			cout << "  -k invoked:\n";
			cout << "    KerFilePath = " << KerFilePath << "\n";
		}
		if (Ideal == "yes")
		{
			cout << "  -a invoked:\n";
			cout << "    IdealFilePath = " << IdealFilePath << "\n";
		}
	}
	
	//catch some errors in the command line, all procs do this so that if one fails, they can all be made
	//to quit easily.  This instead of doing the test on procid==0 and sending a kill to all other procs.
	if (DoM == "yes")
	{
		if (MinCoreSize > MaxCoreSize) 
		{
			if ( procid == 0 ) cout << "ERROR:  The minimum core size ("<<MinCoreSize<<") is greater than the maximum core size.  Please correct the command line arguments.  Quitting...\n\n";
    		exit (EXIT_FAILURE); //master0 reports above, everybody quits here
    	}
		if (MinCoreSize == 1)
		{
			if ( procid == 0 ) cout << "ERROR:  A minimum core size of 1 is not allowed.  Please correct the command line.  Quitting...\n\n"; 
			exit (EXIT_FAILURE); //master0 reports above, everybody quits here
		}
		if (KernelAccessionList.size() > MinCoreSize)
		{
			if ( procid == 0 ) cout << "ERROR:  The number of mandatory accessions ("<<KernelAccessionList.size()
				 <<") is greater than the minimum core size ("<<MinCoreSize
				 <<").  Please modify the kernel file or the command line argument.  Quitting...\n\n";
				exit (EXIT_FAILURE);
		}
	}
	if (Kernel == "yes" && Ideal == "yes" && DoM == "no")
	{
		if ( procid == 0 ) cout << "ERROR:  A* search cannot be performed with a kernel file.  Please correct the command line.  Quitting...\n\n";
		exit (EXIT_FAILURE);
	}

	//DETERMINE MACHINE CONFIGURATIION
	int ncpu = sysconf( _SC_NPROCESSORS_ONLN );

	//PROCESS INPUT DATA
	
	//start the clock
	time_t starti,endi;
	time (&starti);

	//***MPI: MASTER 0 READS THE VAR FILE, BROADCASTS TO ALL PROCS
	//read the file into a buffer using fread, pass it to other procs using MPI_Bcast
	unsigned long long f = 0; //var (and later, dat) file size
	
	if (procid == 0)
	{
		f = (unsigned long long)filesize(VarFilePath); 
		f = f + 1; //increase by 1 to accomodate \0 string terminator
	}
			
	MPI_Bcast(&f, 1, MPI_UNSIGNED_LONG_LONG, 0, MPI_COMM_WORLD); //broadcast file size to all procs
	MPI_Barrier(MPI_COMM_WORLD);
	char * VarFileBuffer = (char*)malloc(f); //initialize and size the data structure to hold contents of var file

	if (procid == 0)
	{
		char * d = MyBigRead(VarFilePath);
		strcpy(VarFileBuffer, d); //convert the char* to a char array, presized from prior MPI_Bcast
		strcpy(d,""); //clear char*
	}
	
	MPI_Bcast(&VarFileBuffer[0], f, MPI_CHAR, 0, MPI_COMM_WORLD); //broadcast the var file contents to all procs
	MPI_Barrier(MPI_COMM_WORLD);


	//.var file
	vector<int> AllColumnIDList;
	vector<std::string> AllLociNameList;
	vector<int> ActiveColumnIDList;
	vector<std::string> ActiveLociNameList;
	vector<int> TargetColumnIDList;
	vector<std::string> TargetLociNameList;
	vector<vector<int> > ColKeyToAllAlleleByPopList;
	vector<int> ReferenceOrTargetKey;
	vector<int> PloidyList;
	vector<std::string> UniqLociNamesList;

	MyProcessVarFile(VarFileBuffer, AllColumnIDList, AllLociNameList, ActiveColumnIDList, ActiveLociNameList, TargetColumnIDList, TargetLociNameList, ColKeyToAllAlleleByPopList, ReferenceOrTargetKey, PloidyList, UniqLociNamesList ); 
	//all but first variable above are updated as references in MyProcessVarFile

	//***MPI: MASTER 0 PRINTS OUT LOCUS SPECS***
	if ( procid == 0 ) 
	{
		//Print out ActiveColumnIDList and ActiveLociNameList
		if (ActiveColumnIDList.size() == 0)
		{
			cout << "\nThere are no active loci.\n";
		}
		else
		{
			cout << "\nActive Locus	Column\n";
			for (i=0; i < ActiveColumnIDList.size(); i++)
			{
				cout << ActiveLociNameList[i] << "\t" << (ActiveColumnIDList[i] + 1) << "\n";
			}
		}

		//Print out TargetColumnIDList and TargetLociNameList
		if (TargetColumnIDList.size() == 0)
		{
			cout << "\nThere are no target loci.\n";
		}
		else
		{
			cout << "\nTarget Locus	Column\n";
			for (i=0; i < TargetColumnIDList.size(); i++)
			{
				cout << TargetLociNameList[i] << "\t" << (TargetColumnIDList[i] + 1) << "\n";
			}
		}

		//process .dat file
		cout << "\nProcessing .dat file...\n";
	}


	//***MPI: MASTER 0 READS THE DAT FILE, BROADCASTS TO ALL PROCS
	//read the whole file into a buffer using fread, pass it to other procs using MPI_Bcast
	f=0; //dat file size
	
	if (procid == 0)
	{
		f = (unsigned long long)filesize(DatFilePath); 
		f = f + 1; //increase by 1 to accomodate \0 string terminator
	}
			
	MPI_Bcast(&f, 1, MPI_UNSIGNED_LONG_LONG, 0, MPI_COMM_WORLD); //broadcast file size to all procs
	MPI_Barrier(MPI_COMM_WORLD);
	char * DatFileBuffer = (char*)malloc(f); //initialize and size the data structure to hold contents of dat file

	if (procid == 0)
	{
		char * d = MyBigRead(DatFilePath);
		strcpy(DatFileBuffer, d); //convert the char* to a char array, presized from prior MPI_Bcast
		strcpy(d,""); //clear char*
	}
	
	MPI_Bcast(&DatFileBuffer[0], f, MPI_CHAR, 0, MPI_COMM_WORLD); //broadcast the dat file contents to all procs
	MPI_Barrier(MPI_COMM_WORLD);
 

	//***MPI: ALL PROCESSORS PROCESS .DAT FILE***
	vector<std::string> FullAccessionNameList;
	vector<std::string> IndivPerPop;
	vector<int> AllAlleles;
	
	vector<vector<vector<int> > > AllAlleleByPopList; //structure of this 3D vector is:
	//vector<vector<vector<int> > > AllAlleleByPopList( AllAlleleByPopListSet.size(), vector<vector<int> >(UniqLociNamesList.size()) ); //structure of this 3D vector is:
	// { { {pop1,loc1 alleles},{pop1,loc2 alleles},...}, { {pop2,loc1 alleles},{pop2,loc2 alleles},...} } }
	
	//Process the dat file
	MyProcessDatFileIII(DatFileBuffer, procid, AllColumnIDList, ColKeyToAllAlleleByPopList, AllAlleleByPopList, FullAccessionNameList, IndivPerPop, AllAlleles, Rarify);
	//AllAlleleByPopList, FullAccessionNameList, IndivPerPop, AllAlleles updated by reference
	
	time_t startd,endd;
	double dif = difftime (endd,startd);
	if (procid == 0) 
	{
		cout << "  Separating reference and target loci...\n";
		time (&startd);
	}

	//sort AllAlleleByPopList into reference and target loci lists
	vector<vector<vector<int> > > ActiveAlleleByPopList; 
	vector<vector<vector<int> > > TargetAlleleByPopList; 
	MyReduceToRef(AllAlleleByPopList, ReferenceOrTargetKey, ActiveAlleleByPopList, TargetAlleleByPopList); //latter 2 variables updated as reference

	/*
		//Print out alleles from AllAlleleByPopList
		if (procid == 0) 
		{
			vector<int> si;
			for (i=0;i<AllAlleleByPopList.size() ;i++)
			{
				cout << "Population " << FullAccessionNameList[i] << "\n";
				for (j=0;j<AllAlleleByPopList[i].size();j++)
				{
					cout << "  Locus " << j << "\n    ";
					cout << "  AllAlleleByPopList[" << i << "][" << j << "].size()=" << AllAlleleByPopList[i][j].size() << "\n";
					si = AllAlleleByPopList[i][j];
					for (std::vector<int>::iterator it=si.begin(); it!=si.end(); ++it)
						cout << *it << ",";
					cout << "\n";
				}
			}
		}
			
		//Print out FullAccessionNameList
		cout << "\n\nPopulation names\n";
		for (unsigned int i=0; i<FullAccessionNameList.size();i++) cout << FullAccessionNameList[i] << "\n";
		
		//Print out lists of unique reference alleles from ActiveAlleleByPopList
		cout << "ActiveAlleleByPopList:\n";
		for (unsigned int i=0; i<ActiveAlleleByPopList.size() ;i++)
		{
			cout << "Population " << i << "\n";
			for (unsigned int j=0;j<ActiveAlleleByPopList[i].size();j++)
			{
				cout << "Locus " << j << "\n";
				for (unsigned int k=0;k<ActiveAlleleByPopList[i][j].size();k++)
				{
					cout << ActiveAlleleByPopList[i][j][k] << ",";
				}
				cout << "\n";
			}
		
		}
		
		//Print out lists of unique target alleles from TargetAlleleByPopList
		cout << "TargetAlleleByPopList:\n";
		for (unsigned int i=0; i<TargetAlleleByPopList.size() ;i++)
		{
			cout << "Population " << i << "\n";
			for (unsigned int j=0;j<TargetAlleleByPopList[i].size();j++)
			{
				cout << "Locus " << j << "\n";
				for (unsigned int k=0;k<TargetAlleleByPopList[i][j].size();k++)
				{
					cout << TargetAlleleByPopList[i][j][k] << ",";
				}
				cout << "\n";
			}
		}
	*/	

	vector<vector<vector<int> > >().swap(AllAlleleByPopList); //clear variable, no longer needed

	if (procid == 0) 
	{
		time (&endd);
		double dif = difftime (endd,startd);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	
	}

	//CALCULATE SOME USEFUL VARIABLES
	//get total number of accessions
	unsigned int NumberOfAccessions = ActiveAlleleByPopList.size();
	
	//catch a possible error in the command line
	if (DoM == "yes")
	{
		if (MaxCoreSize > NumberOfAccessions)
		{
			if ( procid == 0 ) cout << "ERROR:  Maximum core size of "<<MaxCoreSize<< " is greater than the number of accessions.  Please set to a lower value. Quitting...\n\n";
			exit (EXIT_FAILURE); //master0 reports above, everybody quits here
		}
	}

	//get number of loci
	int NumLoci = ActiveAlleleByPopList[1].size();
	
	//calculate population sizes
	vector<int> PopSizes;
	for (i=0;i<FullAccessionNameList.size();++i)
	{
		bf = FullAccessionNameList[i];
		b = std::count (IndivPerPop.begin(), IndivPerPop.end(), bf);
		PopSizes.push_back(b); //synchronized with FullAccessionNameList
	}
	
	if (procid == 0) 
	{
		cout << "  Calculating run specific parameters...\n";
		time (&startd);
	}

	//1. remove target alleles from AllAlleles
	vector<int> AllRefAlleles = MyRemoveTargetAlleles(AllAlleles, AllColumnIDList, TargetColumnIDList);
	vector<int>().swap(AllAlleles); //clear variable, no longer needed
	
	//2. put AllRefAlleles into a 2d vector, samples are rows
	vector<vector<int> > RefAllelesIntoRows(IndivPerPop.size(), vector<int> ( ActiveLociNameList.size() ));
	MyMakeRefAllelesIntoRows(AllRefAlleles, ActiveLociNameList, RefAllelesIntoRows);
	vector<int>().swap(AllRefAlleles); //clear variable, no longer needed

	//3. extract alleles into vector of pairs (ignores missing data -9999)
	vector<std::pair<std::string, vector<int> > > RefAllelesByLocus; // first = locus name, second = vector of all alleles present, updated as reference below
	MyMakeRefAllelesByLocus(RefAllelesIntoRows, ActiveLociNameList, RefAllelesByLocus);
	vector<vector<int> >().swap(RefAllelesIntoRows); //clear variable, no longer needed
	
	//4. calculate allele frequencies, finally (ignores missing data -9999)
	vector<Alfreq> AlleleFrequencies;//(RefAllelesByLocus.size());  //declare vector of struct Alfreq
	MyCalculateAlleleFrequencies(RefAllelesByLocus, AlleleFrequencies);
	vector<std::pair<std::string, vector<int> > >().swap(RefAllelesByLocus); //clear variable, no longer needed
	
	if (procid == 0) 
	{
		time (&endd);
		double dif = difftime (endd,startd);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	

		cout << "  Finalizing data structures...\n";
		time (&startd);
	}

	/*	
		//print out structs containing allele frequencies
		Alfreq laf;
		vector<int> anames;
		vector<double> frqs;
		for (i=0;i<AlleleFrequencies.size();++i)
		{
			cout << AlleleFrequencies[i].locusname << "\n";
		
			laf = AlleleFrequencies[i];
			anames = AlleleFrequencies[i].allelenames;
			frqs = AlleleFrequencies[i].frequencies;
			for (j=0;j<anames.size();++j)
			{
				cout << " " << anames[j];
				cout << " " << frqs[j] << "\n";
			}
		}
	*/
	
	//from list of all accession names, generate an index that is used later to locate alleles belonging to specific accessions
	vector<int> AccessionNameList;
	for (i=0;i<NumberOfAccessions;i++) AccessionNameList.push_back (i);
	//make a similar list for only those accessions contained in the kernel
	vector<int> KernelAccessionIndex;
	int breaker;//contains a switch value to exit the inner loop
	if (Kernel == "yes") 
	{
		for (i=0;i<KernelAccessionList.size();i++)
		{
			breaker = 0;
			for (j=0;j<FullAccessionNameList.size();j++)
			{
				//find the name in the KernelAccessionList in the FullAccessionNameList
				if (FullAccessionNameList[j] == KernelAccessionList[i])
				{
					//add the index value in the coordinated AccessionNameList to the KernelAccessionIndex
					KernelAccessionIndex.push_back(AccessionNameList[j]);
					breaker = 1;
				}
				if (breaker == 1) break;
			}
		}
	}
	//reverse sort KernelAccessionIndex, necessary later
	std::sort(KernelAccessionIndex.begin(), KernelAccessionIndex.end(), std::greater<int>());

	//seed the random number generator for each procid
	unsigned long long seed = (unsigned long long)chrono::high_resolution_clock::now().time_since_epoch().count();
	std::mt19937_64 rng(seed*(procid+1));    // random-number engine used (Mersenne-Twister in this case), seeded with time*procid

	//get maximum number of alleles possible at each locus for active and target
	vector<unsigned int> sss;  //sss is a vector holding the smallest non-zero sample size for each Active locus, only relevant to Rarify=yes
	vector<unsigned int> sst;  //sst is a vector holding the smallest non-zero sample size for each Target locus, only relevant to Rarify=yes
	vector<int> ActiveMaxAllelesList, TargetMaxAllelesList;
	sss = Mysss(ActiveAlleleByPopList);
	sst = Mysss(TargetAlleleByPopList);
	ActiveMaxAllelesList = MyGetMaxs(ActiveAlleleByPopList, rng);
	TargetMaxAllelesList = MyGetMaxs(TargetAlleleByPopList, rng);

	/*
		//Print out alleles from TargetAlleleByPopList
		if (procid == 1) 
		{
			vector<int> si;
			for (i=0;i<TargetAlleleByPopList.size() ;i++)
			{
				cout << "PrePopulation " << FullAccessionNameList[i] << "\n";
				for (j=0;j<TargetAlleleByPopList[i].size();j++)
				{
					cout << "PreLocus " << j << ", ";
					cout << "TargetAlleleByPopList[" << i << "][" << j << "].size()=" << TargetAlleleByPopList[i][j].size() << ", ";
					si = TargetAlleleByPopList[i][j];
					for (std::vector<int>::iterator it=si.begin(); it!=si.end(); ++it)
						cout << *it << ",";
					cout << "\n";
				}
			}
		}
	*/

	//***MPI: MASTER 0 RARIFIES THE DATA, BROADCASTS TO ALL PROCS
	//If Rarify="yes", reduce the Active(Target)AlleleByPopList to the smallest non-zero sample size for each locus
	//This is the rarification step. It is performed by master node then passed to other procids 
	//using MPI_Bcast so that the same rarefied data set is used by all procs.
	if (Rarify == "yes")
	{
		if (procid == 0) cout << "    Rarefaction...\n";
		
		//subsample the Active(Target)MaxAllelesList
		ActiveAlleleByPopList = MyRarifyData(ActiveAlleleByPopList, procid, sss, rng);
		TargetAlleleByPopList = MyRarifyData(TargetAlleleByPopList, procid, sst, rng);

		//test whether all smallest sample sizes are zero for ActiveAlleleByPopList after rarefaction
		MPI_Barrier(MPI_COMM_WORLD);
		bool zerovec = std::any_of(sss.begin(), sss.end(), [](unsigned int i) { return i==0; });
		if (zerovec)
		{
			if ( procid == 0 ) cout << "\nERROR:  Some sample sizes = 0 after rarefaction.  Remove loci with missing data for all members of an accession.  Quitting...\n\n"; 
			exit (EXIT_FAILURE); //master0 reports above, everybody quits here
		}
		
		//recalculate Active(Target)MaxAllelesList
		ActiveMaxAllelesList = MyGetMaxs(ActiveAlleleByPopList, rng);
		TargetMaxAllelesList = MyGetMaxs(TargetAlleleByPopList, rng);
	}
	
	/*
		//Print out alleles from ActiveAlleleByPopList
		if (procid == 1) 
		{
			vector<int> si;
			for (i=0;i<ActiveAlleleByPopList.size() ;i++)
			{
				cout << "PostPopulation " << FullAccessionNameList[i] << "\n";
				for (j=0;j<ActiveAlleleByPopList[i].size();j++)
				{
					cout << "PostLocus " << j << ", ";
					cout << "ActiveAlleleByPopList[" << i << "][" << j << "].size()=" << ActiveAlleleByPopList[i][j].size() << ", ";
					si = ActiveAlleleByPopList[i][j];
					for (std::vector<int>::iterator it=si.begin(); it!=si.end(); ++it)
						cout << *it << ",";
					cout << "\n";
				}
			}
			//print out smallest sample size
			for (unsigned int i=0;i<sss.size();++i) cout << sss[i] << ",";
			cout << "\n";
		}
	
		//print the *MaxAllelesList
		for (unsigned int i=0;i<ActiveMaxAllelesList.size();++i)
		{
			cout << "ActiveMaxAllelesList[" << i << "]=" << ActiveMaxAllelesList[i] << "\n";
		}
		for (unsigned int i=0;i<TargetMaxAllelesList.size();++i)
		{
			cout << "TargetMaxAllelesList[" << i << "]=" << TargetMaxAllelesList[i] << "\n";
		}
	*/	
	
	//clean up a little
	vector<unsigned int>().swap(sss);
	vector<unsigned int>().swap(sst);	

	if (procid == 0) 
	{
		time (&endd);
		double dif = difftime (endd,startd);
		if (dif==1) cout << "    " << dif << " second.\n";	
		else cout << "    " << dif << " seconds.\n";	
	}

	//stop the clock
	if (procid == 0) 
	{
		time (&endi);
		dif = difftime (endi,starti);
	}

	//***MPI: MASTER 0 PRINTS DAT FILE SPECS
	if ( procid == 0 ) 
	{
		if (dif == 1)
			cout << "Input files processed.  Elapsed time = "<< dif << " second.\n\n";
		else
			cout << "Input files processed.  Elapsed time = "<< dif << " seconds.\n\n";
		
			cout << "Number of accessions = " << NumberOfAccessions << ", Number of reference loci = " << NumLoci 
			<< "\n  Number of target loci = "<< TargetAlleleByPopList[1].size();
		if (Kernel == "yes") cout << ", Number of kernel accessions = " << KernelAccessionList.size() << "\n\n";
		else cout << "\n\n";
	}
	
	//PERFORM A* USING MASTER 0 ONLY (A* uses OpenMP)
	if ( procid == 0 )
	{
		if (Ideal == "yes")
		{
			int parallelism_enabled = 1; //0=no, not 0 = yes
			if (parallelism_enabled == 0) cout << "\nBeginning serial A* search...\n\n";
			else cout << "\nBeginning parallel A* search (" << ncpu << " threads)...\n\n";
				
			//start the clock
			time_t start1,end1;
			time (&start1);

			//run A*
			aStar
			(
				IdealFilePath, 
				ActiveAlleleByPopList, 
				ActiveMaxAllelesList, 
				UniqLociNamesList, 
				ReferenceOrTargetKey, 
				FullAccessionNameList, 
				PloidyList, 
				PopSizes, 
				AlleleFrequencies, 
				parallelism_enabled,
				start1
			);
		
			//stop the clock
			time (&end1);
			double dif = difftime (end1,start1);
			cout << "\nA* search complete.  Elapsed time = "<< dif << " seconds.\n\n";
		}	
	}
	
	//PERFORM M+
	if (DoM == "yes")
	{
		if ( procid == 0 ) cout << "\nBeginning parallel M+ search (" << nprocs << " processors)...\n\n";
		
		//start the clock
		time_t startm,endm;
		time (&startm);
		
		//run M+
		mp
		(
		MinCoreSize,
		MaxCoreSize,
		SamplingFreq,
		NumReplicates,
		OutFilePath,
		rng,
		Kernel,
		KernelAccessionIndex,
		AccessionNameList,
		ActiveAlleleByPopList,
		TargetAlleleByPopList,
		ActiveMaxAllelesList,
		TargetMaxAllelesList,
		FullAccessionNameList
		);
		
		//stop the clock
		time (&endm);
		double dif = difftime (endm,startm);
		if ( procid == 0 ) cout << "\nM+ search complete.  Elapsed time = "<< dif << " seconds.\n\n";
	
	}
		
	//Terminate MPI.
	MPI::Finalize ( );

	return 0;
}
Ejemplo n.º 18
0
Vector<TBLoc>
shortestPath(TBLoc start,
             TBLoc end,
             const Grid<double>& world,
             double costFn(const TBLoc& from, const TBLoc& to, const Grid<double>& world),
             double heuristicFn(const TBLoc& from, const TBLoc& to, const Grid<double>& world),
             AlgorithmType algorithm) {
    // modified by Marty to use an actual Graph object
    ensureWorldCache(world, costFn);
    cout << endl;

    Grid<double>* const pWorld = const_cast<Grid<double>*>(&world);
    BasicGraph* graph = WORLD_CACHE[pWorld];
    // graph->resetData();   // make the student worry about this

    s_world = pWorld;
    s_heuristicFunction = heuristicFn;

    // convert start/end from Loc to Vertex
    Vertex* startVertex = graph->getVertex(vertexName(start.row, start.col, world));
    Vertex* endVertex   = graph->getVertex(vertexName(end.row, end.col, world));
    if (startVertex == NULL) {
        error(string("Graph can not find start vertex with name \"") + vertexName(start.row, start.col, world) + "\"");
        for (Vertex* v : graph->getVertexSet()) {
            cout << v->name << " ";
        }
        cout << endl;
    }
    if (endVertex == NULL) {
        error(string("Graph can not find end vertex with name \"") + vertexName(start.row, start.col, world) + "\"");
        for (Vertex* v : graph->getVertexSet()) {
            cout << v->name << " ";
        }
        cout << endl;
    }

    cout << "Looking for a path from " << startVertex->name
         << " to " << endVertex->name << "." << endl;

    Vector<Vertex*> result;
    switch (algorithm) {
    case BFS:
        cout << "Executing breadth-first search algorithm ..." << endl;
        result = breadthFirstSearch(*graph, startVertex, endVertex);
        break;
    case DIJKSTRA:
        cout << "Executing Dijkstra's algorithm ..." << endl;
        result = dijkstrasAlgorithm(*graph, startVertex, endVertex);
        break;
    case A_STAR:
        cout << "Executing A* algorithm ..." << endl;
        result = aStar(*graph, startVertex, endVertex);
        break;
#ifdef BIDIRECTIONAL_SEARCH_ALGORITHM_ENABLED
    case BIDIRECTIONAL:
        cout << "Executing Bidirectional Search algorithm ..." << endl;
        extern Vector<Vertex*> bidirectionalSearch(BasicGraph& graph, Vertex* start, Vertex* end);
        result = bidirectionalSearch(*graph, startVertex, endVertex);
        break;
#endif // BIDIRECTIONAL_SEARCH_ALGORITHM_ENABLED
    case DFS:
    default:
        cout << "Executing depth-first search algorithm ..." << endl;
        result = depthFirstSearch(*graph, startVertex, endVertex);
        break;
    }

    cout << "Algorithm complete." << endl;

    // convert Vector<Vertex*> to Vector<Loc>
    Vector<TBLoc> locResult;
    for (Vertex* v : result) {
        locResult.add(TBLoc(getRow(v), getCol(v)));
    }
    return locResult;
}
Ejemplo n.º 19
0
int gameloop(dataStore *data,SDL_Surface *screen) {
	createRandomField(data);
	clock_t innerStartTime, innerStopTime, startTime, stopTime, diffTime,mouseTime,mT,mousetimewait=500;
	int done=0,i=0,aVal,motionPath=0,runPath=0,drawPath=0,mouseDown=0,ownpath=0;
	position *lastmouse=NULL,*mouse_pos=NULL,*tmp=NULL,*lastpath=NULL;
	SDL_Event event;

	// MUSIC FADEOUT AND IN
	//Mix_HaltMusic();	 
		Mix_PlayMusic( data->ingamemusic, -1);
	
	
	GraphicUpdate(screen,data);
	while (!done) {
		
		/* Check for events */
		startTime = SDL_GetTicks();
		while ( SDL_PollEvent(&event) ) {
			innerStartTime = SDL_GetTicks();
			switch (event.type) {
				case SDL_QUIT:
					done = 1;
					quitSDL(data);
					break;
				case SDL_MOUSEMOTION:
					//Prüft ob sich die Maus aus dem 50x50 Feld bewegt hat
					mouse_pos=calloc(1,sizeof(struct position));
					SDL_GetMouseState(&mouse_pos->x,&mouse_pos->y);
					if(mouse_pos->x > 24 && 226 > mouse_pos->x && mouse_pos->y > 24 && 51 >  mouse_pos->y) {
						aStar(data,&(data->home));
						GraphicUpdate(screen,data);
						positionListDelete(data);
						break;
					} else if(mouse_pos->x > 574 && 776 > mouse_pos->x && mouse_pos->y > 24 && 51 > mouse_pos->y) {
						aStar(data,&(data->stash));
						GraphicUpdate(screen,data);
						positionListDelete(data);
						break;
					} else {
						mouse_pos=pixelToGrid(mouse_pos);
						if(lastmouse!=NULL && mouseDown) {
							if(lastmouse->x!=mouse_pos->x || lastmouse->y!=mouse_pos->y || ownpath==0) {
								tmp=calloc(1,sizeof(struct position));
								tmp->x=mouse_pos->x+data->horizontalScroll;
								tmp->y=mouse_pos->y+data->verticalScroll;
								if(data->player.anfang!=NULL&& data->hedgewood[tmp->y][tmp->x].aStarValue*data->hedgewood[tmp->y][tmp->x].visible>-1 && aStarManhatten(*lastpath,*tmp)==AVGASTAR) {
									lastpath=tmp;
									positionQListAdd(data,tmp);
									ownpath++;
									GraphicUpdate(screen,data);
								} else {
									if(tmp->x==data->player.p_pos.x && tmp->y==data->player.p_pos.y) {
										lastpath=tmp;
										positionQListAdd(data,tmp);
										ownpath++;
										GraphicUpdate(screen,data);
									} else if(lastmouse->x!=mouse_pos->x || lastmouse->y!=mouse_pos->y)printf("Die Startposition muss die Spielerposition sein\n");
								}
								//free(tmp);
							}
						} else if(lastmouse!=NULL && ownpath==0) {
							if(lastmouse->x!=mouse_pos->x || lastmouse->y!=mouse_pos->y)mouseTime=SDL_GetTicks(),drawPath=1;
							else {
								if(drawPath) {
									mT=SDL_GetTicks();
									if((mouseTime + mousetimewait)< mT) {
										motionPath=1;
									}
								}
							}
						} else if(ownpath==0) {
							mouseTime = SDL_GetTicks();
							drawPath=1;
							if((lastmouse=calloc(1,sizeof(position))) == NULL) {
								printf("Kein Speicherplatz vorhanden fuer position\n");
								return -1;
							}
						}
						memcpy(lastmouse,mouse_pos,sizeof(position));
					}
					free(mouse_pos);
					break;
				case SDL_MOUSEBUTTONDOWN:
					mouseDown=1;
					if(DEBUG)printf("MOUSE DOWN\n");
					break;
				case SDL_MOUSEBUTTONUP:
					if(ownpath>0) {
						runPath=1;
						mouseDown=0;
						break;
					}
					mouseDown=0;
					mouse_pos=calloc(1,sizeof(struct position));
					SDL_GetMouseState(&mouse_pos->x,&mouse_pos->y);
					printf("Cusor-Position x: %d y: %d\n",mouse_pos->x,mouse_pos->y);
					if(mouse_pos->x > 24 && 226 > mouse_pos->x && mouse_pos->y > 24 && 51 >  mouse_pos->y) {
						aStar(data,&(data->home));
						runPath=1;
						break;
					} else if(mouse_pos->x > 574 && 776 > mouse_pos->x && mouse_pos->y > 24 && 51 > mouse_pos->y) {
						aStar(data,&(data->stash));
						runPath=1;
						break;
					} else {
						mouse_pos=pixelToGrid(mouse_pos);
						if(DEBUG)printf("Cusor-Feld x: %d y: %d\n",mouse_pos->x,mouse_pos->y);
						if(lastmouse==NULL) {
							if((lastmouse=calloc(1,sizeof(position))) == NULL) {
								printf("Kein Speicherplatz vorhanden fuer position\n");
								return -1;
							}
						}
						memcpy(lastmouse,mouse_pos,sizeof(position));
						free(mouse_pos);
						mouse_pos=NULL;
						motionPath=1;
						runPath=1;
						break;
					}
					
				case SDL_KEYDOWN:
					switch( event.key.keysym.sym ) {
						case 	SDLK_m:
							
							if( Mix_PlayingMusic() == 0 )  
								Mix_PlayMusic( data->ingamemusic, -1);
							
							if( Mix_PausedMusic() == 1 )
								Mix_ResumeMusic(); 
							else Mix_PauseMusic(); 
							
							break;
						case SDLK_s:
							if (data->soundEnabled) {
								Mix_HaltChannel(-1);
							}
							data->soundEnabled=!data->soundEnabled;
							
							break;

						case SDLK_0:
							printf ("Music off\n");
							Mix_HaltMusic();
							Mix_HaltChannel(-1);
							data->soundEnabled=0;
							
							break;
							
							
						case SDLK_ESCAPE:
							done = ingameMenuStart(screen, data);
							if (!done)
								GraphicUpdate(screen, data);
							break;
						case SDLK_q:
							done = 1;
							break;
						default:
							break;
					}
					break;
				default:
					break;
			}
			innerStopTime = SDL_GetTicks();
			diffTime=(innerStopTime-innerStartTime);
			if (MS_FRAMETIME>diffTime)SDL_Delay(MS_FRAMETIME-diffTime);
		}
		mT=SDL_GetTicks();
		if((mouseTime + mousetimewait)< mT && lastmouse!=NULL && ownpath==0 &&runPath==0) {
			motionPath=1;
		}
		if((motionPath || runPath) && !done) {
			if(motionPath) {
				lastmouse->y+=data->verticalScroll;
				lastmouse->x+=data->horizontalScroll;
				aStar(data,lastmouse);
				if(DEBUG)printf("Player-Feld x: %d y: %d\n",data->player.p_pos.x,data->player.p_pos.y);
				GraphicUpdate(screen, data);
				free(lastmouse);
				lastmouse=NULL;
				motionPath=0;
				drawPath=0;
			}
			if(runPath) {
				i=1;
				tmp=data->player.anfang;
				/*sound*/
				if(data->soundEnabled&&data->player.cutSpeed>=2)
					Mix_PlayChannel(CHAINSAWCHANNEL1, data->chainpause, -1);
				while(tmp!=NULL&&i) {
					//Schleife um die Laufbewegung Abzubrechen
					while ( SDL_PollEvent(&event) ) {
						switch (event.type) {
							case SDL_MOUSEBUTTONUP:
								i=0;
								break;
							case SDL_KEYDOWN:
								switch( event.key.keysym.sym ) {
										
										
									case 	SDLK_m:
										printf ("Music on /Pause\n");				
										if( Mix_PlayingMusic() == 0 )  
											Mix_PlayMusic( data->ingamemusic, -1);			
										if( Mix_PausedMusic() == 1 )
											Mix_ResumeMusic(); 
										else Mix_PauseMusic();						
										break;
									case SDLK_s:
										if (data->soundEnabled) {
											Mix_HaltChannel(-1);
										}
										data->soundEnabled=!data->soundEnabled;

										break;
									case SDLK_0:
										printf ("Music off\n");
										Mix_HaltMusic();
										Mix_HaltChannel(-1);
										data->soundEnabled=0;
										break;
									case SDLK_ESCAPE:
										i=0;
										break;
									default:
										break;
								}
							default:
								break;
						}
					}
					tmp=positionListRead(data);
					if(tmp!=NULL) {
						if(DEBUG)printf("Position Stack x: %d y: %d\n",tmp->x,tmp->y);						
						if(headPositionUpdate(data,tmp,screen)) {
							aVal=data->hedgewood[data->player.p_pos.y][data->player.p_pos.x].aStarValue;
							if(aVal>0) {
								data->player.currentEnergy-=aVal;
								if(data->player.currentEnergy<0) {
									printf("YOU ARE DEAD\nNEW GAME\n");
									done=1;
									i=0;
								} else {
									data->hedgewood[data->player.p_pos.y][data->player.p_pos.x].type=6;
									data->hedgewood[data->player.p_pos.y][data->player.p_pos.x].aStarValue=2;
									data->player.bp.currentVolume+=data->hedgewood[data->player.p_pos.y][data->player.p_pos.x].currency;
									if(data->player.bp.currentVolume > data->player.bp.maxVolume) data->player.bp.currentVolume=data->player.bp.maxVolume;
									data->hedgewood[data->player.p_pos.y][data->player.p_pos.x].currency=0;
								}
							}
							if(!done)GraphicUpdate(screen,data);
						} else positionListDelete(data);
					}
				}
				/*sound off*/
				Mix_HaltChannel(CHAINSAWCHANNEL1);

				runPath=0;
				ownpath=0;
			}
			positionListDelete(data);
		}
		stopTime = SDL_GetTicks();
		diffTime = (stopTime-startTime);
		if (MS_FRAMETIME>diffTime)SDL_Delay(MS_FRAMETIME-diffTime);
	}

	addHighscore(screen,data,calcHighscore(data));	
	return 0;
	
	
}
Ejemplo n.º 20
0
void AlgoRitmeWeek1::doAction(Beestje* owner, std::vector<Node*> collection, Beestje* target){
	aStar(owner, collection, target->getNode());
}
Ejemplo n.º 21
0
// update updates the position and orientation of each object according to the 
// actions initiated by the user
//
void Design::update() {


    int delta;
	int dt=0;
	int ds=0;
    delta = now - lastUpdate;
    lastUpdate = now;
	Vector hpos;
    if (now - lastFireTime_ > 100) {
		if(pressed(GREEDY_KEY)){
			searchroutine_=GREEDY;
			lastFireTime_=now;
		}
		else if(pressed(UNIFORM_KEY)){
			searchroutine_=UNIFORM;
			lastFireTime_=now;
		}
		else if(pressed(ASTAR_KEY)){
			searchroutine_=ASTAR;
			lastFireTime_=now;
		}
		else if(pressed(IDASTAR_KEY)){
			searchroutine_=IDASTAR;
			lastFireTime_=now;
		}
		else if(pressed(NEXTBOX)){
			selectloc_=(selectloc_+1)%map_.numvert();
			hpos=highlighter_->position();
			highlighter_->translate(-hpos.x,-hpos.y,-hpos.z);
			highlighter_->translate(map_.vx(selectloc_),map_.vy(selectloc_),map_.vz(selectloc_));
			lastFireTime_=now;
		}
		else if(pressed(PREVBOX)){
			selectloc_=(selectloc_==0)?map_.numvert()-1:selectloc_-1;
			hpos=highlighter_->position();
			highlighter_->translate(-hpos.x,-hpos.y,-hpos.z);
			highlighter_->translate(map_.vx(selectloc_),map_.vy(selectloc_),map_.vz(selectloc_));
			lastFireTime_=now;
		}
		else if(pressed(STARTANIM)){
			if(!ismoving_){
				if(selectloc_!=whichbox_){
					bool searchsuccess=false;        //stores return value of path finding function
					switch (searchroutine_){
						case GREEDY: searchsuccess=greedy(selectloc_); break;
						case UNIFORM: searchsuccess=uniformCost(selectloc_); break;
						case ASTAR: searchsuccess=aStar(selectloc_); break;
						case IDASTAR: searchsuccess=iDAStar(selectloc_); break;
					}/*switch*/
					if(searchsuccess){
						ismoving_=true;
						currloc_=0;
					}
				}
			}//!ismoving_
		}
	}
	if(ismoving_){
		  //move bucket along
		  bool done=false;
		  float leftover=(float)delta/UNITS_PER_SEC;  //amount of time leftover moving bucket along the edge
		  //in this time frame.
		  int dest=path_[currloc_+1];
	  	  while(!done && moveBucket(path_[currloc_],path_[currloc_+1],leftover)){

			//function returns true if destination was reached
			//in this time frame.  so if it was reached,
			//continue to next node or if end of path stop the movment
			currloc_++;
			if(currloc_==numnodes_-1){
				whichbox_=path_[numnodes_-1];
				done=true;
				currloc_=0;
				ismoving_=false;
			}
		  }
	   }


	
 
    lastUpdate = now;
 
}