Ejemplo n.º 1
0
Map::Map(int largeur, int hauteur, string fichier, Level* lvl)
: Reader(), _foreground(), _backgroundLv1(), _backgroundLv2()
{
    string chemin = "Tileset/"+fichier;
    _filePathTileset = "Tileset/"+fichier;
    _tileset.loadFromFile(chemin.c_str());
    _largeurMap = largeur;
    _hauteurMap = hauteur;
    _mapSize = sf::Vector2i(_largeurMap*32,_hauteurMap*32);
    _filePath = fichier;
    _mapArray = new int [_largeurMap*_hauteurMap];
    for (int i(0);i<_largeurMap*_hauteurMap;i++)
    {
        _mapArray[i] = 121;
        _tabMap.push_back(1024);
        _tabForeground.push_back(1024);
        _tabBackgroundLv1.push_back(1024);
        _tabBackgroundLv2.push_back(1024);
    }
    lvl->setForeground(createMap());
    lvl->setbackgroundLv1(createBackground("Lv1"));
    lvl->setbackgroundLv2(createBackground("Lv2"));
    //load();
}
Ejemplo n.º 2
0
int main(int argc, char* argv[]) {
    // Init
    initPath(argv[0]);
    SDL_Surface* screen = NULL;
    SDL_Event event;
    int *seed;
    srand((int)seed);
    int previousTime = 0, currentTime = 0;
    Events *flags = createEventFlags();

    SDL_Init(SDL_INIT_VIDEO);
    SDL_SetEventFilter(eventFilter);

    screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE | SDL_ASYNCBLIT | SDL_DOUBLEBUF | SDL_NOFRAME);
    SDL_WM_SetCaption("Tower Defense", NULL);
    Action *actionList = initAction();

    Map* map = createMap(getPath("resources/Forest.png"));
    _map = map;

    SDL_Rect surface = {0, 0, 720, 600};
    Viewport* viewport = createViewport(screen, surface, map);
    _viewport = viewport;

    // FIXME uh? what's this thing?
    surface.x = 800 - 80;
    surface.y = 0;
    surface.h = 80;
    surface.w = 600;

    // Creation of the enemies
    TypeEn *whiteCat = createTypeEn(100, 5, false, true, true, false, 1,getPath("resources/white_transparent_cat.png"));
    TypeEn *blackCat = createTypeEn(100, 5, false, true, true, false, 1,getPath("resources/black_transparent_cat.png"));
    Enemy *cat1 = createEnemy(1,1,whiteCat);
    Enemy *cat2 = createEnemy(1,10,whiteCat);
    Enemy  *cat3 = createEnemy(5,5,blackCat);
    Enemy *cat4 = createEnemy(21,4,blackCat);

    TypeEn *zombie = createTypeEn(100,5,false,true,true,false,1,getPath("resources/zombie.png"));
    Enemy *zombie1 = createEnemy(4,4,zombie);
    Enemy *zombie2 = createEnemy(9,4,zombie);
    Enemy *zombie3 = createEnemy(9,9,zombie);
    Enemy *zombie4 = createEnemy(7,14,zombie);

    //Add enemy in the List
    List *catList = newList(cat4);
    pushList((void*)catList,cat2);
    pushList((void*)catList,cat3);
//   pushList((void*)catList,cat1);

    List *zombieList = newList(zombie1);
    /*   pushList((void*)zombieList,zombie2);*/
    /*   pushList((void*)zombieList,zombie3);*/
    /*   pushList((void*)zombieList,zombie4);*/

//   removeEnemyFromList(cat4,catList);

    //TOWER
    TypeBul *bullet = createTypeBul(getPath("resources/bullet.png"), 1);
    TypeTo *tower = createTypeTo(0,5,0,0,false,false,false,false,bullet,NULL,getPath("resources/tower.png"));
    upgradeTypeTo(tower,0.5,getPath("resources/towerUP.png"));
    flags->selectedTower = tower->nextType;
    Tower *tower1 = createTower(7,7,tower);

    List *towerList = newList(tower1);
    flags->towerList = towerList;

    // Create and Renders the right panel game menu
    SDL_Rect surfaceMenu = {720, 0, 800, 600};
    Menu* menu = menu_create(screen, surfaceMenu);
    menu_loadBackground(menu, "resources/enemyFont.gif");
    // For testing only, we add a few random buttons
    menu_addButton(menu, button_createBuildButton(tower));
    menu_addButton(menu, button_createBuildButton(tower));
    menu_addButton(menu, button_createBuildButton(tower));
    menu_render(menu);


    _cell = *getCase(20,11);
    // Main loop
    while(actionList[QUIT].boolean == NULL) {
        // Managing the events
        manageEvents(viewport, flags,actionList);
        for(int i=1; i<ACTION_LENGTH; i++) {
            if(actionList[i].boolean) {
                int repeat = (*actionList[i].action)(viewport,flags,actionList[i].boolean);
                if(!repeat) {
                    actionList[i].boolean = NULL;
                }
            }
        }

        // Redraws the map (viewport contents) before blitting stuff on it
        updateViewport(viewport);


///////////////////////////// DEBUG WALL /////////////////////////////
        SDL_Rect position;
        for(int i=0; i < _map->nbCaseW; i++) {
            for(int j=0; j < _map->nbCaseH; j++) {
                Case cell = *getCase(i,j);
                position.x = cell.x;
                position.y = cell.y;
                if(map->matrice[i][j].hasTower == 2) {
                    SDL_Surface *wall = IMG_Load(getPath("resources/brick.png"));
                    blitToViewport(viewport, wall, NULL, &position);
                }
            }
        }
        position.x = _cell.x;
        position.y = _cell.y;
        blitToViewport(viewport, IMG_Load(getPath("resources/candy_cane.png")), NULL, &position);
/////////////////////////////////////////////////////////////////////

        // Move enemies
        if(flags->enemy_Path_Calculation) {
            pathReCalculation(catList);
            pathReCalculation(zombieList);
            flags->enemy_Path_Calculation = false;
        }
        moveEnemyList(zombieList);
        moveEnemyList(catList);

        // Blit enemies
        drawEnemyList(zombieList);
        drawEnemyList(catList);
        //Blit TOWER
        /*      if(event.key.keysym.sym == SDLK_u){*/
        /*         upgrade(tower1);*/
        /*      }*/
        Bullet *bullet1 = createBullet(tower1);
        animateBullet(bullet1);
        drawTowerList(towerList);

        /* This should be handled by event.c
          switch(event.key.keysym.sym){
             case SDLK_a:
                flags->selectedTower = tower;
              break;
             case SDLK_b:
                flags->selectedTower = tower->nextType;
              break;
             default:
              break;

          }*/
        /*      */


        // Ask SDL to swap framebuffers to update the displayed screen
        SDL_Flip(screen);

        // Managing frames
        currentTime = SDL_GetTicks();
        if (currentTime - previousTime <= 20) {
            SDL_Delay(20 - (currentTime - previousTime));
        }

        // DEBUG
        printf("Frame %i : %ims\n", framecounter++, currentTime - previousTime);

        previousTime = SDL_GetTicks();
    }
    free(actionList);
    SDL_Quit();

    return EXIT_SUCCESS;
}
Ejemplo n.º 3
0
int main(int argc, const char * argv[]) {
	const char* filename;
	struct hashMap *hashTable;
	int tableSize = 63;
	clock_t timer;
	FILE *fileptr;
	/*
	this part is using command line arguments, you can use them if you wish
	but it is not required. DO NOT remove this code though, we will use it for
	testing your program.

	if you wish not to use command line arguments manually type in your
	filename and path in the else case.
	*/
	if (argc == 2)
		filename = argv[1];
	else
		filename = "input1.txt"; /*specify your input text file here*/

	printf("opening file: %s\n", filename);

	timer = clock();

	hashTable = createMap(tableSize);

	/*... concordance code goes here ...*/
	fileptr = fopen(filename, "r"); //open the given file

	if (fileptr != NULL) //if the file was opened sucessfully...
	{
		/* while the end of the file has not yet been reached, get the next word in the file, 
		 * adding it to the hash table or updating the number of times it has appeared in the document.
		 * the alogrithm is case sensitive
		 */
		while (!feof(fileptr)) 
		{
			char* word = getWord(fileptr);

			if (word != NULL)
			{
				int* wordCount = atMap(hashTable, word);

				if (wordCount == NULL)
				{
					insertMap(hashTable, word, 1);
				}
				else
				{
					insertMap(hashTable, word, (*wordCount) + 1);
				}
			}
		}
	}
	else
	{
		fprintf(stderr, "Could not open file."); //print an error message if the file could not be opened
	}

	fclose(fileptr); //close the file

	//print each word in the document along with the number of times it has appeared. 
	for (int i = 0; i < hashTable->tableSize; i++)
	{
		hashLink* curLink = hashTable->table[i];

		while (curLink != NULL)
		{
			printf("%s: %d\n", curLink->key, curLink->value);

			curLink = curLink->next;
		}
	}
	/*... concordance code ends here ...*/

	printMap(hashTable);
	timer = clock() - timer;
	printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
	printf("Table count = %d\n", size(hashTable));
	printf("Table capacity = %d\n", capacity(hashTable));
	printf("Table load = %f\n", tableLoad(hashTable));

	printf("Deleting keys\n");

	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
	printMap(hashTable);

	deleteMap(hashTable);
	printf("\nDeleted the table\n");
	return 0;
}
Ejemplo n.º 4
0
int main()
{

    // On aura TOUJOURS comme première fichier map "Map1.tmx" puis un nombre de map a définir

    string etatMap = "start";
    int nbMap = 20;

    // Tableau des différentes Maps
    vector<string> Maps;

    for(int i = 1; i < (nbMap + 1); i++)
    {
        string nomMap = "map/Map";
        nomMap.append(int_to_string(i));
        nomMap.append(".tmx");

        Maps.push_back(nomMap);

        //cout << "la map " << nomMap << " a ete pushe" << endl;
    }

    string Map_EnCours = Maps[0];


    unsigned int Map_Actuelle = 0;

    tile** Matrice;
    //tile** MatriceTest;



    //int LARGEUR_MAP = NbColonnes * LARGEUR_TILE;
    //int HAUTEUR_MAP = NbLignes * HAUTEUR_TILE;

    bool debugMode = true;



    // Fenêtre
    RenderWindow app(VideoMode((int)WINDOW_SIZE.x, (int)WINDOW_SIZE.y, 32), "Another : Beta v0.2");

	// Frames Per Second (FPS)
    //app.setFramerateLimit(60); // limite la fenêtre à 60 images par seconde

    // NE PAS mettre les deux en meme temps

    app.setVerticalSyncEnabled(true);

	Texture myTile, myEchelle, myBullet, myEnnemi, myEnnemi2, myPlayer, myPlayer2, lifeBonus,
	myEndBlock, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward;

	if (!myBullet.loadFromFile(SPRITES_FILE_PATH_BULLET)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myBullet.SetSmooth(false);
    }

	if (!myEnnemi.loadFromFile(SPRITES_FILE_PATH_ENNEMI)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myEnnemi.SetSmooth(false);
    }

	if (!myEnnemi2.loadFromFile(SPRITES_FILE_PATH_ENNEMI_2)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myEnnemi2.SetSmooth(false);
    }

	if (!myPlayer.loadFromFile(SPRITES_FILE_PATH_PLAYER)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //myPlayer.SetSmooth(false);
    }

	if (!lifeBonus.loadFromFile(SPRITES_FILE_PATH_LIFEBONUS)) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //lifeBonus.SetSmooth(false);
    }

	if (!myTile.loadFromFile("images/blocTerre.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myTile.SetSmooth(false);
    }

	if (!myEchelle.loadFromFile("images/blocEchelle.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myEchelle.SetSmooth(false);
    }

	if (!myEndBlock.loadFromFile("images/blocFin.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myEndBlock.SetSmooth(false);
    }

    if (!tileSet1.loadFromFile("map/tileset1.png")) // Si le chargement a échoué
    {
        cerr<<"Erreur durant le chargement de l'image"<<endl;
    }
    else
    {
        //tileSet1.SetSmooth(false);
    }

    if (!myInterrupteur.loadFromFile("images/interrupteur.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myInterrupteur.SetSmooth(false);
    }

    if (!myDoor.loadFromFile("images/porteCoulissante.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myDoor.SetSmooth(false);
    }

	if (!myCheckpoint.loadFromFile("images/checkpoint.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //myCheckpoint.SetSmooth(false);
    }

    if (!reward.loadFromFile("images/reward.png")) // Si le chargement a échoué
	{
		cerr<<"Erreur durant le chargement de l'image"<<endl;
	}
    else
    {
        //reward.SetSmooth(false);
    }

    vector<Bullet> vectorBullet;
	vector<Character> vectorCharacter;
	vector<Object*> vectorObject;




	// ====== Variable importante !! =======

//	int x = 150;
//	int y = 150;
	int controleSaut = false; /* Booléen qui va permettre de ne pas relancer un second saut avant d'avoir relaché la touche */
	float transparence = 0;
	float transparenceInverse = 255;
	Clock clockTempsMap;
	Clock clockFrame;
	bool startGame = false;
	bool changementDeMap = false;

	/*string etatMap = "start";

	// Tableau des différentes Maps
    vector<string> Maps;



    for(int i = 1; i < (nbMap + 1); i++)
    {
        string nomMap = "map/Map";
        nomMap.append(int_to_string(i));
        nomMap.append(".tmx");

        Maps.push_back(nomMap);

        //cout << "la map " << nomMap << " a ete pushe" << endl;
    }*/

	// =====================================
	// =====================================




	// Création et positionnement du joueur au lancement du jeu



	// =========================


	// Création d'une vue qui suivra les déplacements du joueur

	View vue = app.getDefaultView();
	View hud;

	// =========================================================

	// Création des barres de vie et d'énergie du joueur et du rectangle de fondu

    sf::RectangleShape hud1;
    hud1.setSize(sf::Vector2f(150, 140));
    hud1.setFillColor(sf::Color(190, 200, 200));
    hud1.setOutlineColor(sf::Color::Black);
    hud1.setOutlineThickness(1);

    sf::RectangleShape barLife;
    barLife.setSize(sf::Vector2f(50, 10));
    barLife.setFillColor(sf::Color::Red);
    barLife.setOutlineColor(sf::Color::Black);
    barLife.setOutlineThickness(1);

    sf::RectangleShape barPower;
    barPower.setSize(sf::Vector2f(50, 10));
    barPower.setFillColor(sf::Color(0, 150, 255));
    barPower.setOutlineColor(sf::Color::Black);
    barPower.setOutlineThickness(1);

    sf::RectangleShape fondu;
    fondu.setSize(sf::Vector2f(WINDOW_SIZE.x, WINDOW_SIZE.y));

	// ===============================================================
	// Menu

    menu(app, false, changementDeMap, hud, WINDOW_SIZE, startGame, Maps, Map_EnCours, Map_Actuelle);

    createMap(Map_EnCours, &Matrice, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward, vectorObject);

    int NbColonnes = nbColonnesMap(Map_EnCours);
    int NbLignes = nbLignesMap(Map_EnCours);

    int LARGEUR_TILE = largeurTileMap(Map_EnCours);
    int HAUTEUR_TILE = largeurTileMap(Map_EnCours);

    Player player(myPlayer, 0, 0, PLAYER_SPEED, "bleu", "normal");
	PlayerPosition(player, &Matrice, NbColonnes, NbLignes, LARGEUR_TILE, "depart");

	clockTempsMap.restart();

    cout << "Map en cours avant main" << Map_EnCours << endl;
    cout << "Map Actuelle avant main" << Map_Actuelle << endl;

    // Boucle principale
    while (app.isOpen())
    {
		// Remplissage de l'écran (couleur noire par défaut)
        app.clear();

        //vue.setSize(WINDOW_SIZE.x, WINDOW_SIZE.y);
        app.setView(vue);
        hud = app.getDefaultView();


        // On récupère le temps de rafraichissement entre chaque frame pour ajuster la vitesse du jeu
        float frameTime = clockFrame.restart().asSeconds();

        bool actionElement = false;

        // On modifier la valeur du temps de la map

        /*if(clockTempsMap.getElapsedTime().asSeconds() > 0.1f)
        {
            tempsMap += 0.1f;
            clockTempsMap.restart();
        }*/


		/* Gestion de l'affichage d'un certain nombre de tile autour du player, et non toute la map */

		int indexPlayerI = convertToIndex(player.getLeftSide(), LARGEUR_TILE);
		int indexPlayerJ = convertToIndex(player.getBottomSide(), LARGEUR_TILE);

		/* Les nombre en dessous permettent de déterminer la distance ou lon affiche la map autour du héro */

		float visionI = 20, visionJ = 10;

		int idPImoins = indexPlayerI - visionI;
		int idPIplus = indexPlayerI + visionI;
		int idPJmoins = indexPlayerJ - visionJ;
		int idPJplus = indexPlayerJ + visionJ;

		if(idPImoins < 0)
			idPImoins = 0;

		if(idPIplus > NbColonnes)
			idPIplus = NbColonnes;

		if(idPJmoins < 0)
			idPJmoins = 0;

		if(idPJplus > NbLignes)
			idPJplus = NbLignes;

        for(int j=idPJmoins; j<idPJplus; j++)
                for(int i=idPImoins; i<idPIplus; i++)
                    if(Matrice[i][j].spr != 0)
                        app.draw(*Matrice[i][j].spr);


		//=================================================



		/* REGENERATION du POWER */

		player.setPower(player.getPower() + 0.2f);

		if(player.getPower() > 100.0f)
			player.setPower(100.0f);

		if(player.getPower() < 0)
			player.setPower(0);

		if(player.getPower() > 50.0f)
			player.setSurchauffe(false);

		/* ===================== */



		/* == LIFE == */

		if(player.getLife() <= 100)
			player.upLife(0.05f);

		if(player.getLife() > 200.0f)
			player.setLife(200.0f);

		if(player.getLife() < 0)
			player.setLife(0);

		/* ===================== */



		// Dès que la vitesse descend en dessous de 0 alors le joueur n'est plus en saut

		if(player.getSpeedY() < 0)
			player.setEnSaut(false);

		/* ===================== */


		/* GRAVITE : On diminue la vitesse verticale si pas sur Terre */

		if(!player.surTerre()){

			player.setSpeedY(player.getSpeedY() - 30.0f);

			/* Effet de resistance de l'air */
			if((CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 1)
                || (CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 2)
            )
            {
                if(player.getSpeedY() < -400.0f)
                    player.setSpeedY(-400.0f);
            }
            else
            {
               if(player.getSpeedY() < -800.0f)
                    player.setSpeedY(-800.0f);
            }


		}

		/* ===================== */



		/* On enleve la GRAVITE lorsque l'on est au sol */

		if(player.surTerre()){
			player.setSpeedY(0);
		}

		/* ===================== */


		/* CLOCK du freeze Time */

		if(player.getFreeze()){

			if(player.getClockFreeze() > 1.5f){
				player.setFreeze(false);
				player.setSpeedY(0);
			}
		}

		// ======================

		Event event;

        while (app.pollEvent(event))
        {

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Space){

				//player.setEnSaut(false);
				controleSaut = false;
			}

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Down){

				player.setDescendre(false);
			}

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Right){

				player.setDeplacement(false);
				player.setMouvementDroite(false);
			}

			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::Left){

				player.setDeplacement(false);
				player.setMouvementGauche(false);
			}
			if(event.type == sf::Event::KeyReleased && event.key.code == Keyboard::LShift){

				player.notShooting();
			}


            switch(event.type)
			{
				case Event::Closed : // Croix de fermeture
					app.close();
					break;

				case Event::KeyPressed : // Appui sur une touche
				{
					switch(event.key.code)
					{
						case Keyboard::Escape : // Touche echap

                            if(player.surTerre())
                            {
                                startGame = false;
                                menu(app, true, changementDeMap, hud, WINDOW_SIZE, startGame, Maps, Map_EnCours, Map_Actuelle);

                                if(changementDeMap)
                                {
                                    clockTempsMap.restart();
                                    player.setScore(0);

                                    deleteMatrice(&Matrice, NbColonnes, NbLignes, vectorObject);

                                    createMap(Map_EnCours, &Matrice, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward, vectorObject);

                                    NbColonnes = nbColonnesMap(Map_EnCours);
                                    NbLignes = nbLignesMap(Map_EnCours);

                                    PlayerPosition(player, &Matrice, NbColonnes, NbLignes, LARGEUR_TILE, "depart");


                                    changementDeMap = false;
                                }
                            }
                            else
                            {
                                cout << "Vous devez etre sur terre pour aller dans le menu. (En cas de probleme, sautez !)" << endl;
                            }
							break;

                        default:
                            break;
					}
				}



				default:
                    break;
			}


        }



        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
            if(!player.getMouvementDroite()){

                player.setMouvementGauche(true);

                if(!player.getFreeze()){
                //	if(!Matrice[mxGauche][myGauche].solid){
                        if(!player.getFreeze())
                            //if(player.getSpeed() > -15.0f)
                                player.deplacementGaucheX();

                //	}

                    player.setDeplacement(true);
                }

                player.setDirectionGauche();
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
            if(!player.getMouvementGauche()){

                player.setMouvementDroite(true);

                if(!player.getFreeze()){
                    //if(!Matrice[mxDroite][myDroite].solid){
                        if(!player.getFreeze())
                            //if(player.getSpeed() < 15.0f)
                                player.deplacementDroiteX();

                    //}

                    player.setDeplacement(true);
                }

                player.setDirectionDroite();
		    }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
        {
            if(!controleSaut && !player.getFreeze() && player.surTerre()){
					player.setSpeedY(650.0f);
					player.setEnSaut(true);
					controleSaut = true;
            }

            if(!controleSaut && !player.getFreeze() && !player.surTerre())
            {
                if(CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 1)
                {
                    player.setSpeedY(850.0f);
                    player.setSpeed(700.0f);
					player.setEnSaut(true);
					controleSaut = true;
                    //cout << "saut gauche" << endl;
                }
                else if(CollisionDecorLateralSide(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice, vectorObject) == 2)
                {
                    player.setSpeedY(850.0f);
                    player.setSpeed(-700.0f);
					player.setEnSaut(true);
					controleSaut = true;
                    //cout << "saut droite" << endl;
                }
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
        {
            if(!player.getSurchauffe()){
				player.teleport();
				player.setFreeze(false);
			}
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
        {
            actionElement = true;
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::P))
        {
            etatMap = "end";
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z))
        {
            if(!player.getFreeze())
				player.freezeTime();
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
        {
            if(player.getClockBullet() > 0.2f){
				if(player.getDirection() == "droite"){
					vectorBullet.push_back(Bullet(myBullet, (player.getRightSide() - 10), (player.getTopSide() + 12.0f), (BULLET_SPEED * frameTime), player.getDirection(), player.getEquipe(), "ball"));
				}else if(player.getDirection() == "gauche"){
					vectorBullet.push_back(Bullet(myBullet, (player.getLeftSide() - 20), (player.getTopSide() + 12.0f), (BULLET_SPEED * frameTime), player.getDirection(), player.getEquipe(), "ball"));
				}

				player.resetClockBullet();
			}

            player.shootAnimation();
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        {
            player.setDescendre(true);
        }



		//	===================================================
		//  =============== AFFICHAGE DES TESTS ===============
		//	===================================================

		/*if(CollisionDecorPlafond(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice))
			cout << " COLLISION PLAFOND  " << endl;
		else
			cout << " PAS COLLISION PLAFOND  " << endl;

		if(CollisionDecorSol(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, player, Matrice))
			cout << " COLLISION SOL  " << endl;
		else
			cout << " PAS COLLISION SOL  " << endl;	*/


		/*if(player.surTerre())
			cout << " SUR TERRE  " << endl;
		else
			cout << " PAS SUR TERRE  " << endl;
*/
		//cout << player.getSpeed() << endl;
		/*
			cout << vectorCharacter.size() << endl;
			cout << vectorBullet.size() << endl;
			cout << vectorObject.size() << endl;*/


      // cout << "speed y :" << player.getSpeedY() << endl;



		//	===================================================


	//	===================================================


		/* Friction / Ralentissement de la vitesse latérale */

		if(!player.getDeplacement()){

			if(player.getSpeed() > 1500.0f){
				player.setSpeed(player.getSpeed() - 500.0f);
			}else if(player.getSpeed() < -1500.0f){
				player.setSpeed(player.getSpeed() + 500.0f);
			}

			if(player.getSpeed() > 0){
				if(player.getSpeed() < 150.00f){
					player.setSpeed(0);
				}
				else{
					player.setSpeed(player.getSpeed() - 50.00f);
				}

			}else if(player.getSpeed() < 0){
				if(player.getSpeed() > -150.0f){
					player.setSpeed(0);
				}
				else{
					player.setSpeed(player.getSpeed() + 50.00f);
				}
			}

		}

		/* Lorsque le joueur n'est pas Freeze on effectue les essai de mouvement sur X et Y pour on application la nouvelle position */

		if(!player.getFreeze()){

			EssaiDeplacementX(Matrice, frameTime, player, player.getSpeed(), LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorObject);

			if(EssaiDeplacementY(Matrice, frameTime, player, player.getSpeedY(), LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorObject)){

				// Si true, alors le joueur est en contact avec un bloc de fin de niveau
                cout << "ERREUR" << endl;
                cout << Map_Actuelle << " " << Map_EnCours << endl;
				etatMap = "end";
			}



			player.setPosition();

		}







		//	===========================================================================
		//  =========== Double boucle testant chaque balles si elle est en  ===========
		//	===========	collision avec un ennemi, un player, un mur ou rien ===========
		//	===========================================================================


		for(int unsigned i = 0; i < vectorBullet.size(); i++){

			if(CollisionBulletDecor(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorBullet[i], Matrice)){
					vectorBullet[i].kill();
				}

			if(vectorBullet[i].getDirection() == "droite"){
				vectorBullet[i].deplacementDroiteX();
			}else if(vectorBullet[i].getDirection() == "gauche"){
				vectorBullet[i].deplacementGaucheX();
			}

			vectorBullet[i].drawBullet(app);

			// Collision des balles et des ennemis
			for(int unsigned j = 0; j < vectorCharacter.size(); j++){

				float degatDeal;

				// On test si l'équipe de la balle est la meme que celle du character, si non, on peut tester la collision
				if(vectorBullet[i].getEquipe() != vectorCharacter[j].getEquipe()){
					if(!vectorBullet[i].isKilled()){
						if(CollisionBulletCharacter(vectorBullet[i], vectorCharacter[j])){

							degatDeal = vectorBullet[i].getDegat();
							vectorCharacter[j].downLife(degatDeal);

							vectorBullet[i].kill();
						}
					}
				}

			}

			// Collision des balles et des objet

            for(int unsigned j = 0; j < vectorObject.size(); j++){

                if(vectorObject[j]->getSolid()){

                    if(CollisionObjectBullet(vectorObject[j], vectorBullet[i])){
                        vectorBullet[i].kill();

                        if(vectorObject[j]->getBreakable()){
                           vectorObject[j]->kill();
                        }
                    }
                }
            }

			// Collision des balles et du joueur

			if(vectorBullet[i].getEquipe() != player.getEquipe()){
				if(!vectorBullet[i].isKilled()){
					if(CollisionBulletCharacter(vectorBullet[i], player)){

						float degatDeal = vectorBullet[i].getDegat();
						player.downLife(degatDeal);

						vectorBullet[i].kill();
					}
				}
			}

		}

		//	===========================================================================



		//	===================================================
		//  ============== Boucle sur les objets ==============
		//	===================================================

		for(int unsigned i = 0; i < vectorObject.size(); i++){

			for(int unsigned j = 0; j < vectorCharacter.size(); j++){

				if(CollisionObjectCharacter(vectorObject[i], vectorCharacter[j])){

					float life = vectorObject[i]->getLife();
					vectorCharacter[j].upLife(life);

					vectorObject[i]->kill();
				}

			}

			if(CollisionObjectCharacter(vectorObject[i], player)){

                if(vectorObject[i]->getType() == "lifeBonus"){
                    float life = vectorObject[i]->getLife();
                    player.upLife(life);

                    vectorObject[i]->kill();
                }
                else if(vectorObject[i]->getType() == "interrupteur"){

                    if(actionElement){
                        if(vectorObject[i]->getEstActive() == false){
                            vectorObject[i]->setActive();
                            vectorObject[i]->resetClockInt();
                        }
                    }

                }
                else if(vectorObject[i]->getType() == "tilePique"){

                    if(vectorObject[i]->getDeadly()){
                        player.kill();
                    }

                }
                else if(vectorObject[i]->getType() == "checkpoint"){

                    if(!vectorObject[i]->getActive()){
                        vectorObject[i]->setActive(true);

                        player.setInitialPosition(vectorObject[i]->getX(), vectorObject[i]->getY());

                        for(int unsigned j = 0; j < vectorObject.size(); j++){

                            if(vectorObject[j]->getType() == "checkpoint"){
                                if(j != i)
                                {
                                    if(vectorObject[j]->getActive()){
                                        vectorObject[j]->setActive(false);
                                    }
                                }
                            }
                        }

                    }
                }
                else if(vectorObject[i]->getType() == "blockPique"){

                    if(vectorObject[i]->getDeadly()){
                        player.kill();
                    }

                }
                else if(vectorObject[i]->getType() == "reward"){
                    int val = vectorObject[i]->getValeur();
                    player.setScore(player.getScore() + val);

                    vectorObject[i]->kill();
                }
			}

            //cout << "test 1030 et taille de  : " << vectorObject.size() << endl;


			if((vectorObject[i]->getType() == "interrupteur") && (vectorObject[i]->getEstActive())){

                if(vectorObject[i]->getClockInt() > vectorObject[i]->getDelai()){

                    vectorObject[i]->setNotActive();
                }

			}
			else if(vectorObject[i]->getType() == "door"){

                if(vectorObject[i]->buttonIsActive()){

                    vectorObject[i]->setOpen(true);
                }
                else{

                    if(!CollisionObjectCharacter(vectorObject[i], player))
                        vectorObject[i]->setOpen(false);
                }

			}
			else if(vectorObject[i]->getType() == "launcher"){

                if(!vectorObject[i]->getIsReady()){
                    if(vectorObject[i]->getClock() > vectorObject[i]->getDecallage()){

                        vectorObject[i]->resetClock();
                        vectorObject[i]->setReady(true);

                    }
                }
                else{
                    if(vectorObject[i]->getClock() > vectorObject[i]->getInterval()){

                        vectorObject[i]->resetClock();

                        float x, y;

                        if(vectorObject[i]->getDirection() == "gauche")
                        {
                            x = (vectorObject[i]->getLeftSide()) - 5.0f;
                            y = (vectorObject[i]->getTopSide()) + 15.0f;

                            vectorBullet.push_back(Bullet(myBullet, x, y, (BULLET_SPEED * frameTime), vectorObject[i]->getDirection(), vectorObject[i]->getEquipe(), vectorObject[i]->getAmmoType()));
                        }
                        else if(vectorObject[i]->getDirection() == "droite")
                        {
                            x = (vectorObject[i]->getRightSide()) - 15.0f;
                            y = (vectorObject[i]->getTopSide()) + 15.0f;

                            vectorBullet.push_back(Bullet(myBullet, x, y, (BULLET_SPEED * frameTime), vectorObject[i]->getDirection(), vectorObject[i]->getEquipe(), vectorObject[i]->getAmmoType()));
                        }



                    }

                }

			}
			else if(vectorObject[i]->getType() == "blockPique"){

               // if(EssaiDeplacementY(Matrice, app, player, player.getSpeedY(), LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, vectorObject)){

                if(CollisionObjectDecor(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, i, vectorObject, Matrice))
                {

                    if(vectorObject[i]->getDirection() == "gauche"){

                        vectorObject[i]->setDirection("droite");
                    }
                    else if(vectorObject[i]->getDirection() == "droite"){

                        vectorObject[i]->setDirection("gauche");
                    }
                    else if(vectorObject[i]->getDirection() == "haut"){

                        vectorObject[i]->setDirection("bas");
                    }
                    else if(vectorObject[i]->getDirection() == "bas"){

                        vectorObject[i]->setDirection("haut");
                    }
                }

                if(vectorObject[i]->getDirection() == "gauche"){

                    vectorObject[i]->deplacementGaucheX();
                }
                else if(vectorObject[i]->getDirection() == "droite"){

                    vectorObject[i]->deplacementDroiteX();
                }
                else if(vectorObject[i]->getDirection() == "haut"){

                    vectorObject[i]->deplacementHautY();
                }
                else if(vectorObject[i]->getDirection() == "bas"){

                    vectorObject[i]->deplacementBasY();
                }

			}
			else if(vectorObject[i]->getType() == "reward"){

                if(CollisionObjectDecor(LARGEUR_TILE, HAUTEUR_TILE, NbColonnes, NbLignes, i, vectorObject, Matrice))
                {
                    vectorObject[i]->deplacement(true, frameTime);

                }
                else
                {
                    vectorObject[i]->deplacement(false, frameTime);

                }



			}

			vectorObject[i]->drawObject(app);
		}


        /** A AJUSTER */

		vue.setCenter((int)(player.getX() + (player.GetSprite().getLocalBounds().width)/2), (int)(player.getY() + (player.GetSprite().getLocalBounds().height)/2));


        player.drawPlayer(app);

		// == Boucle permettant de supprimer du Vector les balles qui sont "killed" après une collision

		for(int unsigned i = 0; i < vectorBullet.size();){
			if(vectorBullet[i].isKilled())
				vectorBullet.erase(vectorBullet.begin()+i);
			else
				i++;
		}

		// == Boucle permettant de supprimer du Vector les Ennemis qui sont "killed" lorsqu'il n'ont plus de points de vie

/*		// == Ou plutot de faire respawn le Character

		for(int unsigned i = 0; i < vectorCharacter.size();){
			if(vectorCharacter[i].isKilled()){

				vectorCharacter[i].setX(vectorCharacter[i].getInitialX());
				vectorCharacter[i].setY(vectorCharacter[i].getInitialY());
				vectorCharacter[i].setLife(vectorCharacter[i].getInitialLife());
				vectorCharacter[i].setSpeed(vectorCharacter[i].getInitialSpeed());
				vectorCharacter[i].setEnSaut(vectorCharacter[i].enSautInitial());
				vectorCharacter[i].setSurTerre(vectorCharacter[i].surTerreInitial());

				vectorCharacter[i].setPosition();

			//	vectorCharacter.erase(vectorCharacter.begin()+i);
			}else
				i++;
		}*/

		// == Boucle permettant de supprimer du Vector les objets qui sont "killed" lorsqu'ils ont été utilisés

		for(int unsigned i = 0; i < vectorObject.size();){
			if(vectorObject[i]->isKilled())
				vectorObject.erase(vectorObject.begin()+i);
			else
				i++;
		}



		// == Test permettant de voir si le player est Killed, et de le faire respawn en conséquence

		// systeme de CHECKPOINT ici

		if(player.isKilled()){

				player.setX(player.getInitialX());
				player.setY(player.getInitialY());
				player.setLife(player.getInitialLife());
				player.setSpeed(player.getInitialSpeed());
				player.setEnSaut(player.enSautInitial());
				player.setSurTerre(player.surTerreInitial());
				player.revive();

				player.setPosition();

			//	vectorCharacter.erase(vectorCharacter.begin()+i);
		}



        app.setView(hud); // IMPORTANT <<

        // On affiche le block hud1

        hud1.setPosition((hud.getCenter().x - (hud.getSize().x / 2)), (hud.getCenter().y - (hud.getSize().y / 2)));
        app.draw(hud1);

        // Permet d'afficher les FPS en mode debug

		if(debugMode){
			sf::Text fpsMessage;
			int FPS;
			ostringstream oss;

			FPS = 1 / frameTime;
			oss << "FPS : " << FPS;

            fpsMessage.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 110.0f));
            fpsMessage.setColor(Color(255,0,0,255));
            fpsMessage.setString(oss.str());
            fpsMessage.setCharacterSize(14);

			app.draw(fpsMessage);
		}

        // On Affiche le Score

        sf::Text score;
        ostringstream oss2;

        oss2 << "Score : " << player.getScore();

        score.setColor(Color(0,0,0,255));
        score.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 90.0f));
        score.setCharacterSize(14);
        score.setString(oss2.str());

        app.draw(score);

        // On Affiche le temps

        sf::Text tpsMaps;
        ostringstream oss3;

        oss3 << "Temps : " << clockTempsMap.getElapsedTime().asSeconds();

        tpsMaps.setColor(Color(0,0,0,255));
        tpsMaps.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 70.0f));
        tpsMaps.setCharacterSize(14);
        tpsMaps.setString(oss3.str());


        app.draw(tpsMaps);


		// Affichage d'un message "surcharge" si l'energie est basse

		sf::Text txtSurcharge;

		txtSurcharge.setString("Overheating !");
		txtSurcharge.setColor(Color(255,0,0,255));
		txtSurcharge.setCharacterSize(14);
		txtSurcharge.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 50.0f));

		if(player.getSurchauffe())
			app.draw(txtSurcharge);

		// Variations des barres de vies et de power

		barLife.setSize(sf::Vector2f(player.getLife(), 10.0f));
		barPower.setSize(sf::Vector2f(player.getPower(), 10.0f));

		barLife.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 10.0f));
		barPower.setPosition((hud.getCenter().x - (hud.getSize().x / 2) + 20.0f), (hud.getCenter().y - (hud.getSize().y / 2) + 30.0f));

		if(player.getSurchauffe()){

			barPower.setFillColor(sf::Color(0, 25, 100));
		}
		else{

			barPower.setFillColor(sf::Color(0, 150, 255));
		}

        app.draw(barLife);
		app.draw(barPower);

        //cout << "x now :" << player.getX() << endl;
        //cout << "speed Y :" << player.getSpeedY() << endl;


		if(etatMap == "end"){


			/* Systeme de fondu pour fin de niveau // Le rectangle suit le joueur pour éviter tout problème visuel */

			fondu.setPosition((hud.getCenter().x - (hud.getSize().x / 2)), (hud.getCenter().y - (hud.getSize().y / 2)));
			fondu.setFillColor(sf::Color(0,0,0,transparence));

			app.draw(fondu);

			// La transparence s'effectue a 0.5 par frame ( a modifier si besoin !)

			if(transparence < 255){
				transparence += 1.0f;
			}


			if(transparence >= 255){

                save((Map_Actuelle + 2), player.getScore(), clockTempsMap.getElapsedTime().asSeconds());
                // MapActuelle + 2 car pour le niveau 1 mapActuelle = 0 et que l'on veux save le dernier niveau que l'on
                //a atteint donc fin du 1 = 0 + 2 = 2

                clockTempsMap.restart();
                player.setScore(0);

                deleteMatrice(&Matrice, NbColonnes, NbLignes, vectorObject);

                GoToNextMap(Map_EnCours, Map_Actuelle, Maps);

                createMap(Map_EnCours, &Matrice, tileSet1, myInterrupteur, myDoor, myCheckpoint, reward, vectorObject);

                NbColonnes = nbColonnesMap(Map_EnCours);
                NbLignes = nbLignesMap(Map_EnCours);


				// On repositionne le joueur en fonction des valeurs initiales

				// =========
// IMPORTANT	// Les valeurs "initiales" varieront en fonction des checkpoint et des changement de niveau
				// =========



				// ========================

                PlayerPosition(player, &Matrice, NbColonnes, NbLignes, LARGEUR_TILE, "depart");




				// =================================

				etatMap = "transition"; // TEMPORAIRE
				transparence = 0;

			}

		}

		if(etatMap == "transition"){

			// On réalise un fondu (inverse) pour réafficher le jeu

			fondu.setPosition((hud.getCenter().x - (hud.getSize().x / 2)), (hud.getCenter().y - (hud.getSize().y / 2)));
			fondu.setFillColor(sf::Color(0,0,0,transparenceInverse));

			app.draw(fondu);

			if(transparenceInverse > 0){
				transparenceInverse -= 2.0f;
			}


			if(transparenceInverse <= 0)
			{
			    etatMap = "start";
			    transparenceInverse = 255;
			}

		}

        // Affichage de la fenêtre à l'écran
        app.display();
    }

	deleteMatrice(&Matrice, NbColonnes, NbLignes, vectorObject);

    return EXIT_SUCCESS;


}
Ejemplo n.º 5
0
Archivo: main.c Proyecto: wsims/CS261
int main (int argc, const char * argv[]) {
	const char* filename;
	struct hashMap *hashTable;
	int tableSize = 10;
	clock_t timer;
	FILE *fileptr;
    /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.

     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc == 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/

    printf("opening file: %s\n", filename);

	timer = clock();

	hashTable = createMap(tableSize);

    /*... concordance code goes here ...*/
    fileptr = fopen(filename, "r");
    if (fileptr != NULL) {
        int *val, *x;
        char *word;
        while ((word = getWord(fileptr))) {
            if (containsKey(hashTable, word)) {
                val = (int *) atMap(hashTable, word);
                (*val) ++;
                free(word);
            } else {
                x = malloc(sizeof(int));
                *x = 1;
                insertMap(hashTable, word, x);
            }
        }
        fclose(fileptr);
    } else printf("Error opening file.\n");
	/*... concordance code ends here ...*/

	printMap(hashTable, keyPrint, valPrint);
	timer = clock() - timer;
	printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
	printf("Table capacity = %d\n", capacity(hashTable));
	printf("Table load = %f\n", tableLoad(hashTable));

	printf("Deleting keys\n");

	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
    printMap(hashTable, keyPrint, valPrint);
    printKeyValues(hashTable, keyPrint, valPrint);
         /* Test out the iterator */
#ifdef ITERATOR_IN
         struct mapItr *myItr;
         myItr = createMapIterator(hashTable);

         KeyType  key;

         /* Free up our keys and values using our iterator!!  Also printing them as we go along */
         while(hasNextMap(myItr))
           {
             key = nextMap(myItr);
             int *value = atMap(hashTable,key);
             printf("Freeing ...Key = %s, value = %d \n", key, *value);
             free(value);  /* To match the malloc above*/
             free(key);

           }
#endif


        deleteMap(hashTable);
	printf("\nDeleted the table\n");
	return 0;
}
Ejemplo n.º 6
0
int main (int argc, const char * argv[]) {
	const char* filename;
	struct hashMap *hashTable;	
	char *word;
	int tableSize = 10;
	clock_t timer;
	FILE *fileptr;
	int *numWordOccurances;	
    /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.
     
     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc == 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/
    
    	printf("opening file: %s\n", filename);

	timer = clock();
	
	hashTable = createMap(tableSize);	   
	
	// generate concordance
	fileptr = fopen(filename,"r");	
	while (!feof(fileptr)) {	

		word = getWord(fileptr);

		if(!word){
			break;
		}
		numWordOccurances = (int *)atMap(hashTable, word); /* cast return of atMap to int*/
		
		if(numWordOccurances!=0){			
			(*numWordOccurances)++;
		} else {
			/* need to malloc numWordOccurances before insertMap*/
			numWordOccurances = (int *) malloc(sizeof(int));
			*numWordOccurances = 1;
			insertMap(hashTable, word, numWordOccurances);		
		}
	}	

	// print concordance
	printMap(hashTable);
	
	// print hashmap statistices
	fclose(fileptr);
	timer = clock() - timer;
	printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
	printf("Table capacity = %d\n", capacity(hashTable));
	printf("Table load = %f\n", tableLoad(hashTable));
	
	printf("Deleting keys: \"and\", \"me\", and \"the\"\n");
	
	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
	printMap(hashTable);
		
	deleteMap(hashTable);
	printf("\nDeleted the table\n");   
	return 0;
}
Ejemplo n.º 7
0
int main (int argc, const char * argv[]) {
	const char* filename;
	struct hashMap *hashTable;
	int tableSize = 10;
	clock_t timer;

    /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.

     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc == 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/

    printf("opening file: %s\n", filename);

	timer = clock();

	hashTable = createMap(tableSize);

    /*... concordance code goes here ...*/
    FILE *file;
    file = fopen(filename, "r");
    /* if there is no file named that */
    if(!file){
        printf("Unable to open file. \n");
    }
    /* loops until the end of the file */
    while(!feof(file)){
        char *word = getWord(file);
        if(word){
            if(containsKey(hashTable, word)){
                int *value = atMap(hashTable, word);
                ++(*value);
            }
            else{
            insertMap(hashTable, word, 1);
            }
        }
    }


	/*... concordance code ends here ...*/

	printMap(hashTable);
	timer = clock() - timer;
	printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
	printf("Table capacity = %d\n", capacity(hashTable));
	printf("Table load = %f\n", tableLoad(hashTable));

	printf("Deleting keys\n");

	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
	printMap(hashTable);

	deleteMap(hashTable);
	printf("\nDeleted the table\n");
	return 0;
}
Ejemplo n.º 8
0
/**
 * Load a PHP script then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by reference.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param real_inputs the maps containing the inputs
 * @param real_outputs the maps containing the outputs
 */
int zoo_php_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){	
  maps* m=*main_conf;
  maps* inputs=*real_inputs;
  maps* outputs=*real_outputs;
    
  map* libp = getMapFromMaps(m, "main", "libPath");  
  int res=SERVICE_FAILED;

  map* tmp=getMap(s->content,"serviceProvider");
  if (tmp == NULL || tmp->value == NULL) {
	  return errorException(m, "Missing serviceProvider (library file)", "NoApplicableCode", NULL);
  }
  
  map* cwd=getMapFromMaps(m,"lenv","cwd");
#ifdef IGNORE_METAPATH
  map* mp = createMap("metapath", "");
#else  
  map* mp = getMap(request, "metapath");
#endif
  char *scriptName;
  
  if (libp != NULL && libp->value != NULL) {
	scriptName = (char*) malloc((strlen(libp->value) + strlen(tmp->value) + 2)*sizeof(char));
    sprintf (scriptName, "%s/%s", libp->value, tmp->value);	
  }
  else {	
    if(mp!=NULL && strlen(mp->value)>0){
      scriptName=(char*)malloc((strlen(cwd->value)+strlen(mp->value)+strlen(tmp->value)+3)*sizeof(char));
      sprintf(scriptName,"%s/%s/%s",cwd->value,mp->value,tmp->value);
    }else{
      scriptName=(char*)malloc((strlen(cwd->value)+strlen(tmp->value)+2)*sizeof(char));
      sprintf(scriptName,"%s/%s",cwd->value,tmp->value);
    }
  } 
  zend_file_handle iscript;
  iscript.type=ZEND_HANDLE_FD;
  iscript.opened_path=NULL;
  iscript.filename=tmp->value;
  iscript.free_filename=0;
  FILE* temp=fopen(scriptName,"rb");
  if(temp==NULL){
    char tmp1[1024];
    sprintf(tmp1,_("Unable to load the PHP file %s"),tmp->value);
    free(scriptName);
    return errorException(m,tmp1,"NoApplicableCode",NULL);
  }
  iscript.handle.fd=fileno(temp);

  php_embed_init(0,NULL PTSRMLS_CC);
   
  zend_try {
    zend_startup_module(&zoo_module_entry);
    php_execute_script(&iscript TSRMLS_CC);
    zval *iargs[3];
    zval iret, ifunc,ifile;
      
    ZVAL_STRING(&ifunc, s->name, 0);
    iargs[0] = php_Array_from_maps(*main_conf);
    iargs[1] = php_Array_from_maps(*real_inputs);
    iargs[2] = php_Array_from_maps(*real_outputs);
      
    if((res=call_user_function(EG(function_table), NULL, &ifunc, &iret, 3, iargs TSRMLS_CC))==SUCCESS){
      
      HashTable* t=HASH_OF(iargs[2]);
      HashTable* t1=HASH_OF(iargs[0]);
      freeMaps(real_outputs);
      free(*real_outputs);
      freeMaps(main_conf);
      free(*main_conf);
      *real_outputs=php_maps_from_Array(t);
      *main_conf=php_maps_from_Array(t1);

      res=Z_LVAL(iret);
    }else{
      free(scriptName);
      fclose(temp);
      return errorException(m,"Unable to process.","NoApplicableCode",NULL);;
    }
  } zend_catch { 
    free(scriptName);
    fclose(temp);
    return errorException(m,"Unable to process.","NoApplicableCode",NULL);;
  } zend_end_try();
  free(scriptName);
  fclose(temp);
  php_embed_shutdown(TSRMLS_C);

  return res;
}
Ejemplo n.º 9
0
bool AflMapData::openMap(LPCSTR pcstrFileName)
{
	std::fstream file(pcstrFileName,std::ios::in | std::ios::binary);
	if(!file.is_open())
		return false;

	//ヘッダチェック
	CHAR cBuff[1024];
	file.read(cBuff,strlen(m_strMapHeader[MAP_BINHEADER])+1);
	if(strcmp(cBuff,m_strMapHeader[MAP_BINHEADER]) != 0)
		return false;

	m_strFileName = pcstrFileName;
	
	INT iWidth = 0;
	INT iHeight = 0;
	m_iOutTipIndex = 0;


	DWORD dwSize;
	LPVOID pVoid;
	while(readHeader(file,cBuff,&pVoid,&dwSize))
	{
		int nIndex = getHeaderIndex(cBuff);
		switch(nIndex)
		{
		case MAP_VERSION:
			break;
		case MAP_MAPNAME:
			m_strMapName = (LPCSTR)pVoid;
			break;
		case MAP_BITMAP:
			m_strBmpName[0] = (LPCSTR)pVoid;
			break;
		case MAP_SPRITE:
			m_strBmpName[1] = (LPCSTR)pVoid;
			break;
		case MAP_WIDTH:
			iWidth = *(LPINT)pVoid;
			break;
		case MAP_HEIGHT:
			iHeight = *(LPINT)pVoid;
			break;
		case MAP_OPATTERN:
			m_iOutTipIndex = *(LPINT)pVoid;
			break;
		case MAP_PARTSWIDTH:
			m_iTipWidth = *(LPINT)pVoid;
			break;
		case MAP_PARTSHEIGHT:
			m_iTipHeight = *(LPINT)pVoid;
			break;
		case MAP_MAPDATA0:
			createMap(iWidth,iHeight);
		case MAP_MAPDATA1:
		case MAP_MAPDATA2:
		case MAP_MAPDATA3:
		case MAP_MAPDATA4:
			CopyMemory((PCHAR)m_ptrData[nIndex-MAP_MAPDATA0].get(),pVoid,dwSize);
			break;
		case MAP_PAERSCOLLIDE0:
		case MAP_PAERSCOLLIDE1:
		case MAP_PAERSCOLLIDE2:
		case MAP_PAERSCOLLIDE3:
		case MAP_PAERSCOLLIDE4:
			CopyMemory(m_byCollide[nIndex-MAP_PAERSCOLLIDE0],pVoid,dwSize);
			break;
		case MAP_MAPFLAG0:
			CopyMemory(getMapFlag(),pVoid,dwSize);
			break;
		case MAP_OBJECT:
			m_strObjectFileName = (LPCSTR)pVoid;
			break;
		}
		delete (LPBYTE)pVoid;
        cBuff[0] = 0;
	}
	
	return true;
}
Ejemplo n.º 10
0
int getServiceFromYAML(maps* conf, char* file,service** service,char *name){
  FILE *fh = fopen("test.yml", "r");
  if(current_content!=NULL){
    freeMap(&current_content);
    free(current_content);
    current_content=NULL;
  }
#ifdef DEBUG_SERVICE_CONF
  fprintf(stderr,"(STARTING)FREE current_element\n");
#endif
  if(current_element!=NULL){
    freeElements(&current_element);
    free(current_element);
    current_element=NULL;
  }
  my_service=NULL;
  
  my_service=*service;
  my_service->name=strdup(name);
  my_service->content=NULL;
  my_service->metadata=NULL;
  my_service->inputs=NULL;
  my_service->outputs=NULL;
  fh = fopen(file,"r");
  if (fh==NULL){
    fprintf(stderr,"error : file not found\n") ;
    return -1;
  }
  yaml_parser_t parser;
  yaml_token_t  token;   /* new variable */

  /* Initialize parser */
  if(!yaml_parser_initialize(&parser))
    fputs("Failed to initialize parser!\n", stderr);
  if(fh == NULL)
    fputs("Failed to open file!\n", stderr);
  /* Set input file */
  yaml_parser_set_input_file(&parser, fh);
  /* BEGIN new code */
  int level=0;
  int plevel=level;
  int ilevel=-1;
  int blevel=-1;
  int ttype=0;
  int wait_metadata=-1;
  char *cur_key;
  do {
    yaml_parser_scan(&parser, &token);
    switch(token.type)
    {
    /* Stream start/end */
    case YAML_STREAM_START_TOKEN: 
#ifdef DEBUG_YAML
      puts("STREAM START"); 
#endif
      break;
    case YAML_STREAM_END_TOKEN:   
#ifdef DEBUG_YAML
      puts("STREAM END");   
#endif
      break;
    /* Token types (read before actual token) */
    case YAML_KEY_TOKEN:   
#ifdef DEBUG_YAML
      printf("(Key token)   "); 
#endif
      ttype=0;
      break;
    case YAML_VALUE_TOKEN: 
#ifdef DEBUG_YAML
      printf("(Value token) "); 
#endif
      ttype=1;
      break;
    /* Block delimeters */
    case YAML_BLOCK_SEQUENCE_START_TOKEN: 
#ifdef DEBUG_YAML
      puts("<b>Start Block (Sequence)</b>"); 
#endif
      break;
    case YAML_BLOCK_ENTRY_TOKEN:          
#ifdef DEBUG_YAML
      puts("<b>Start Block (Entry)</b>");    
#endif
      break;
    case YAML_BLOCK_END_TOKEN:      
      blevel--;
      if(ilevel>=0)
	ilevel--;
#ifdef DEBUG_YAML
      printf("<b>End block</b> (%d,%d,%d,%d)\n", blevel,level,ilevel,ttype); 
#endif
      break;
    /* Data */
    case YAML_BLOCK_MAPPING_START_TOKEN:  
#ifdef DEBUG_YAML
      puts("[Block mapping]");            
#endif
      blevel++;
      break;
    case YAML_SCALAR_TOKEN:  
      if(ttype==0){
	cur_key=zStrdup((char *)token.data.scalar.value);
      }
      if(ttype==1){
	if(current_content==NULL){
	  current_content=createMap(cur_key,(char *)token.data.scalar.value);
	}else{
	  addToMap(current_content,cur_key,(char *)token.data.scalar.value);
	}
	free(cur_key);
	cur_key=NULL;
      }

      if(ttype==0 && blevel==0 && level==0 && strcasecmp((char *)token.data.scalar.value,"MetaData")==0 && blevel==0){
	addMapToMap(&my_service->content,current_content);
#ifdef DEBUG_YAML
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=1;
      }
      if(ttype==0 && blevel>0 && level>0 && strcasecmp((char *)token.data.scalar.value,"MetaData")==0){
	if(current_element->content==NULL && current_content!=NULL)
	  addMapToMap(&current_element->content,current_content);
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=1;
      }
      if(ttype==0 && strcasecmp((char *)token.data.scalar.value,"inputs")==0 && blevel==0){
	if(wait_metadata>0){
	  addMapToMap(&my_service->metadata,current_content);
	  wait_metadata=-1;
	}else{
	  if(current_content!=NULL && my_service->content==NULL)
	    addMapToMap(&my_service->content,current_content);
	}
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
	wait_metadata=false;
	level++;
      }
      if(ttype==0 && strcasecmp((char *)token.data.scalar.value,"outputs")==0 && blevel==1){
	level++;
#ifdef DEBUG_YAML
	dumpMap(current_content);
	printf("\n***\n%d (%d,%d,%d,%d)\n+++\n", current_element->defaults==NULL,blevel,level,ilevel,ttype); 
#endif
	if(current_element->defaults==NULL && current_content!=NULL && ilevel<0){
	  current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	  current_element->defaults->content=NULL;
	  current_element->defaults->next=NULL;
	  addMapToMap(&current_element->defaults->content,current_content);
#ifdef DEBUG_YAML
	  dumpElements(current_element);
	  dumpMap(current_content);
	  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	  freeMap(&current_content);
	  free(current_content);
	  current_content=NULL;
	}else{
	  if(current_content!=NULL && ilevel<=0){
	    addMapToIoType(&current_element->supported,current_content);
#ifdef DEBUG_YAML
	    dumpElements(current_element);
	    dumpMap(current_content);
	    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	    freeMap(&current_content);
	    free(current_content);
	    current_content=NULL;
	  }
	}
      }
      if(level==1 && strcasecmp((char *)token.data.scalar.value,"default")==0){
	ilevel=0;
      }
      if(level==1 && strcasecmp((char *)token.data.scalar.value,"supported")==0){
#ifdef DEBUG_YAML
	dumpMap(current_content);
	printf("\n***\n%d (%d,%d,%d,%d)\n+++\n", current_element->defaults==NULL,blevel,level,ilevel,ttype); 
#endif
	if(current_element->defaults==NULL && current_content!=NULL && ilevel<0){
	  current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	  current_element->defaults->content=NULL;
	  current_element->defaults->next=NULL;
	  addMapToMap(&current_element->defaults->content,current_content);
#ifdef DEBUG_YAML
	  dumpElements(current_element);
	  dumpMap(current_content);
	  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	  freeMap(&current_content);
	  free(current_content);
	  current_content=NULL;
	}else{
	  if(current_content!=NULL && ilevel<=0){
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	    }
	    addMapToMap(&current_element->supported->content,current_content);
#ifdef DEBUG_YAML
	    dumpElements(current_element);
	    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	    freeMap(&current_content);
	    free(current_content);
	    current_content=NULL;
	  }
	}
	ilevel=1;
      }


      if(strncasecmp((char *)token.data.scalar.value,"ComplexData",11)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"LiteralData",10)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"ComplexOutput",13)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"LiteralOutput",12)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"BoundingBoxOutput",13)==0 || 
	 strncasecmp((char *)token.data.scalar.value,"BoundingBoxData",12)==0){
	current_element->format=zStrdup((char *)token.data.scalar.value);
	free(cur_key);
	cur_key=NULL;
	if(wait_metadata>0 && current_content!=NULL){
	  addMapToMap(&current_element->metadata,current_content);
	  wait_metadata=-1;
	}else{
	  if(current_content!=NULL){
	    addMapToMap(&current_element->content,current_content);
	  }
	}
#ifdef DEBUG_YAML
	dumpMap(current_content);
	fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
	freeMap(&current_content);
	free(current_content);
	current_content=NULL;
#ifdef DEBUG_YAML
	dumpElements(current_element);
#endif
      }

      if(blevel==1 && level==1){
	if(current_element!=NULL && current_content!=NULL){
	  if(current_element->defaults==NULL){
	    current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	    current_element->defaults->content=NULL;
	    current_element->defaults->next=NULL;
	    addMapToMap(&current_element->defaults->content,current_content);
	  }else{
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	      addMapToMap(&current_element->supported->content,current_content);
	    }else
	      addMapToIoType(&current_element->supported,current_content);
	  }
	}
	if(current_element!=NULL){
	  if(my_service->inputs==NULL)
	    my_service->inputs=dupElements(current_element);
	  else
	    addToElements(&my_service->inputs,current_element);
	  freeElements(&current_element);
	  free(current_element);
	}
	plevel=level;
	current_element=(elements*)malloc(ELEMENTS_SIZE);
	current_element->name=zStrdup((char *)token.data.scalar.value);
	current_element->content=NULL;
	current_element->metadata=NULL;
	current_element->format=NULL;
	current_element->defaults=NULL;
	current_element->supported=NULL;
	current_element->next=NULL;
	
      }
      if(blevel==1 && level==2){
	if(current_element!=NULL && current_content!=NULL){
	  if(current_element->defaults==NULL){
	    current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
	    current_element->defaults->content=NULL;
	    current_element->defaults->next=NULL;
	    addMapToMap(&current_element->defaults->content,current_content);
	  }else{
	    if(current_element->supported==NULL){
	      current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	      current_element->supported->content=NULL;
	      current_element->supported->next=NULL;
	      addMapToMap(&current_element->supported->content,current_content);
	    }else
	      addMapToIoType(&current_element->supported,current_content);
	  }
	}
	if(current_element!=NULL){
	  if(plevel==level){
	    if(my_service->outputs==NULL)
	      my_service->outputs=dupElements(current_element);
	    else
	      addToElements(&my_service->outputs,current_element);
	  }else{
	    if(my_service->inputs==NULL)
	      my_service->inputs=dupElements(current_element);
	    else
	      addToElements(&my_service->inputs,current_element);
	  }
	  freeElements(&current_element);
	  free(current_element);
	}
	plevel=level;
	current_element=(elements*)malloc(ELEMENTS_SIZE);
	current_element->name=zStrdup((char *)token.data.scalar.value);
	current_element->content=NULL;
	current_element->metadata=NULL;
	current_element->format=NULL;
	current_element->defaults=NULL;
	current_element->supported=NULL;
	current_element->next=NULL;
	
      }


#ifdef DEBUG_YAML
      printf("scalar %s (%d,%d,%d,%d,%d)\n", token.data.scalar.value,blevel,level,plevel,ilevel,ttype); 
#endif
      break;
    /* Others */
    default:
      if(token.type==0){
	char tmp[1024];
	sprintf(tmp,"Wrong charater found in %s: \\t",name);
	setMapInMaps(conf,"lenv","message",tmp);
	return -1;
      }
#ifdef DEBUG_YAML
      printf("Got token of type %d\n", token.type);
#endif
      break;
    }
    if(token.type != YAML_STREAM_END_TOKEN )
      yaml_token_delete(&token);
  } while(token.type != YAML_STREAM_END_TOKEN);
  yaml_token_delete(&token);


#ifdef DEBUG_YAML
  fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
  if(current_element!=NULL && current_content!=NULL){
    if(current_element->defaults==NULL){
      current_element->defaults=(iotype*)malloc(IOTYPE_SIZE);
      current_element->defaults->content=NULL;
      current_element->defaults->next=NULL;
      addMapToMap(&current_element->defaults->content,current_content);
    }else{
      if(current_element->supported==NULL){
	current_element->supported=(iotype*)malloc(IOTYPE_SIZE);
	current_element->supported->content=NULL;
	current_element->supported->next=NULL;
	addMapToMap(&current_element->supported->content,current_content);
      }else
	addMapToIoType(&current_element->supported,current_content);
    }
#ifdef DEBUG_YAML
    dumpMap(current_content);
    fprintf(stderr,"MSG: %s %d \n",__FILE__,__LINE__);
#endif
    freeMap(&current_content);
    free(current_content);
    current_content=NULL;
  }
  if(current_element!=NULL){
    if(my_service->outputs==NULL)
      my_service->outputs=dupElements(current_element);
    else
      addToElements(&my_service->outputs,current_element);
    freeElements(&current_element);
    free(current_element);
    current_element=NULL;
  }
  /* END new code */

  /* Cleanup */
  yaml_parser_delete(&parser);
  fclose(fh);

#ifdef DEBUG_YAML
  dumpService(my_service);
#endif
  *service=my_service;

  return 1;
}
Ejemplo n.º 11
0
/////////////////////////////////////////////////////////////////////////////
// creates the Seafarers: Greater Catan (VI) map
/////////////////////////////////////////////////////////////////////////////
void CMapDatabase::createGreaterCatanVI(CS3DMap *pMap)
{
	//identifier
	pMap->m_uiID = MAP_SEA_GREATER_CATAN_VI;

	//last time edited
	pMap->m_timeEdit = COleDateTime::GetCurrentTime();

	//type of game
	pMap->m_iMode = MAP_SEAFARERS;

	//official map
	pMap->m_bOfficial = TRUE;

	//play to 18 points
	pMap->m_iPoints = 18;

	//map name
	pMap->m_strMapName = "Greater Catan (V/VI)";
	pMap->m_strMapCreator = "Jason Fugate";

	//9 allowed cards in hamd
	pMap->m_iAllowedCards = 9;

	//beefed up starting bank
	pMap->m_iBankRes = 25;

	//beefed up dev cards
	pMap->m_iDevTotal = 34;
	pMap->m_iDevCards[CARD_VICTORY] = 5;
	pMap->m_iDevCards[CARD_MONOPOLY] = 3;
	pMap->m_iDevCards[CARD_ROAD_BUILD] = 3;
	pMap->m_iDevCards[CARD_YEAR_PLENTY] = 3;
	pMap->m_iDevCards[CARD_SOLDIER] = 20;

	//uses chip laying algorithm
	pMap->m_bUseChipMethod = TRUE;

	//uses chitless tiles
	pMap->m_bHasChitlessTiles = TRUE;

	//there are 30 random tiles
	pMap->m_nRandomTiles = 30;

	//ports
	pMap->m_nPorts = 11;

	//chip texture file used
	pMap->m_iChipsUsed = MAP_USES_56_CHIPS | MAP_USES_SEA_CHIPS;	

	//min/max players
	pMap->m_iMinPlayers = 5;
	pMap->m_iMaxPlayers = 6;

	//number of land/sea tiles
	pMap->m_iLandTiles = 50;
	pMap->m_iSeaTiles = 53;

	//15 ships in this scenario
	pMap->m_iStockShips = 15;

	//extra cities in this scenario
	pMap->m_iStockCities = 8;

	//set the roll places
	pMap->m_iRollPlaces[0] = 15;
	pMap->m_iRollPlaces[1] = 48;
	pMap->m_iRollPlaces[2] = 84;
	pMap->m_iRollPlaces[3] = 86;
	pMap->m_iRollPlaces[4] = 53;
	pMap->m_iRollPlaces[5] = 17;

	//set the random resource amounts
	pMap->m_iRandomRes[RES_TIMBER] = 6;
	pMap->m_iRandomRes[RES_WHEAT] = 6;
	pMap->m_iRandomRes[RES_ORE] = 5;
	pMap->m_iRandomRes[RES_CLAY] = 5;
	pMap->m_iRandomRes[RES_SHEEP] = 6;
	pMap->m_iRandomRes[RES_GOLD] = 0;
	pMap->m_iRandomRes[RES_DESERT] = 2;
	pMap->m_iRandomRes[RES_OCEAN] = 0;
	pMap->m_iRandomRes[RES_PORT3] = 6;
	pMap->m_iRandomRes[RES_PORTTIMBER] = 1;
	pMap->m_iRandomRes[RES_PORTWHEAT] = 1;
	pMap->m_iRandomRes[RES_PORTORE] = 1;
	pMap->m_iRandomRes[RES_PORTCLAY] = 1;
	pMap->m_iRandomRes[RES_PORTSHEEP] = 1;

	//set up chitless tiles
	pMap->m_iChitlessTiles = 20;

	//set the amounts
	pMap->m_iChitlessRes[RES_TIMBER] = 4;
	pMap->m_iChitlessRes[RES_WHEAT] = 4;
	pMap->m_iChitlessRes[RES_ORE] = 4;
	pMap->m_iChitlessRes[RES_CLAY] = 4;
	pMap->m_iChitlessRes[RES_SHEEP] = 4;
	pMap->m_iChitlessRes[RES_GOLD] = 0;
	pMap->m_iChitlessRes[RES_DESERT] = 0;

	//set the chitless chits
	pMap->m_iChitlessChits = 7;

	//set the amounts
	pMap->m_nChitlessChit[0] = 1;
	pMap->m_nChitlessChit[1] = 1;
	pMap->m_nChitlessChit[2] = 1;
	pMap->m_nChitlessChit[3] = 1;
	pMap->m_nChitlessChit[4] = 0;
	pMap->m_nChitlessChit[5] = 0;
	pMap->m_nChitlessChit[6] = 0;
	pMap->m_nChitlessChit[7] = 1;
	pMap->m_nChitlessChit[8] = 1;
	pMap->m_nChitlessChit[9] = 1;
	pMap->m_nChitlessChit[10] = 0;

	//create the map
	createMap(MAP_BORDERS_XX_X_XX, pMap, coordsGreaterCatanVI);

	//start out zoomed out a little farther than normal
	pMap->m_dInitialDepth = 115.;

	//set initial rotation
	pMap->m_dInitialRot = -30.;
}
Ejemplo n.º 12
0
Archivo: ctor.hpp Proyecto: njoy/ENDFtk
Material( const Material& other ) :
  materialNo( other.materialNo ),
  fileVector( other.fileVector ),
  fileMap( createMap( this->fileVector ) ),
  bufferLimits( other.bufferLimits ){}
//-------------------------------------------- Constructeurs - destructeur
TransformerVisitor::TransformerVisitor(const xml::Node & XslTree)
{
	templatesMap = new mapXsl();
	createMap(XslTree);

} //----- Fin de OutputVisitor
Ejemplo n.º 14
0
Archivo: main.c Proyecto: gpard77/cs261
int main (int argc, const char * argv[]) {
	const char* filename;
	struct hashMap *hashTable;	
	int tableSize = 10;
	clock_t timer;
	FILE *fileptr;	
    /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.
     
     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc == 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/
    
    printf("opening file: %s\n", filename);
    
	timer = clock();
	
	hashTable = createMap(tableSize);	   
	
    /*... concordance code goes here ...*/
	fileptr = fopen(filename, "r");

	if (!fileptr)
	{
	   printf("Error Opening File.\n");
	}

	char *word = getWord(fileptr);
	//ValueType val;
	
	while (word != 0)
	{
	   //char *word = getWord(fileptr);
	   // Check table for word, insert if not found
	   if (containsKey(hashTable, word)== 0)
	   {
	      insertMap(hashTable, word, 1);
	   }
	   else
	   {
	       (*atMap(hashTable, word))++;
	   }
	   word = 0;
	   free(word);
	   word = getWord(fileptr);
	}

	fclose(fileptr);
	
	printf("\n");
	hashLink * temp;

	for (int i = 0; i < hashTable->tableSize; i++)
	{
	   temp = hashTable->table[i];
	   while (temp != 0)
	   {
	      printf("%s: %d\n", temp->key, temp->value);
	      temp = temp->next;
	   }
	}
	free(temp);	
	/*... concordance code ends here ...*/

	printMap(hashTable);
	timer = clock() - timer;
	printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
	printf("Table capacity = %d\n", capacity(hashTable));
	printf("Table load = %f\n", tableLoad(hashTable));
	
	printf("Deleting keys\n");
	
	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
	printMap(hashTable);
		
	deleteMap(hashTable);
	printf("\nDeleted the table\n");   
	return 0;
}
Ejemplo n.º 15
0
void gameClient(sf::RenderWindow & window,char * mapName){

        int i,/*displacementX=0,displacementY=0,*/ menu=0;
        gameMap_t map;

       // int redrawMMAP = 1;

        cursor_t gCur;
        gCur.status = 0;
        gCur.cell = NULL;



        player_t players;

        players.resourcesPlayer1 = 400;
        players.resourcesPlayer2 = 400;
      //  player_t player2;



        unsigned int currentPlayerTurn=0;

        selection_t select;

        select.status=0;

        select.cell=NULL;


        createMap(&map);




        /*
        Set textures.
        */
        sf::Texture background, interface_image,menu1,menu2,grind,cursor,pCourse,endTurn1,endTurn2,sel,enemy,fpT,spT,cT1,cT2,cB1,cB2;
        sf::Sprite gameBackground,gameInterface,gameMenu,gameGrind,gameCursor,aCell,gameEndTurn,cSel,cEnemy,cpT,cTc,cBc;
        menu1.loadFromFile("gameInterface/menu.png");

        fpT.loadFromFile("gameInterface/fpTurn.png");
        spT.loadFromFile("gameInterface/spTurn.png");

        enemy.loadFromFile("gameInterface/enemyCell.png");

        sel.loadFromFile("gameInterface/selected.png");
        menu2.loadFromFile("gameInterface/menuConfirmed.png");
        grind.loadFromFile("maps/grind.png");
        endTurn1.loadFromFile("gameInterface/endTurn.png");
        endTurn2.loadFromFile("gameInterface/endTurnConfirmed.png");
        cT1.loadFromFile("gameInterface/cTank.png");
        cT2.loadFromFile("gameInterface/cTankC.png");

        cB1.loadFromFile("gameInterface/cBuggy.png");
        cB2.loadFromFile("gameInterface/cBuggyC.png");
        //test

        addUnit(&map,window,0,TANK,15,0);

        addUnit(&map,window,0,BUGGY,12,0);

        addUnit(&map,window,0,TANK,9,0);


        addUnit(&map,window,1,TANK,27,18);


        addUnit(&map,window,1,BUGGY,30,18);

        addUnit(&map,window,1,TANK,33,18);

        addObject(&map,window,0,20,12);

        addObject(&map,window,0,10,10);

        addObject(&map,window,0,30,8);





        cpT.setPosition(130,0);



        cursor.loadFromFile("gameInterface/setCell.png");
        pCourse.loadFromFile("gameInterface/availableCell.png");




        background.loadFromFile(mapName);




        interface_image.loadFromFile("gameInterface/mainInterface.png");
        gameBackground.setTexture(background);
        cSel.setTexture(sel);
        aCell.setTexture(pCourse);
        gameGrind.setTexture(grind);
        gameInterface.setTexture(interface_image);
        cEnemy.setTexture(enemy);
        gameCursor.setTexture(cursor);

        drawMinMap(window,currentPlayerTurn,&map);




while (window.isOpen()){

         cameraMouseMove(window,&map);

         mouseEvents(window,&map);

         menu=gameSelection(window,gameMenu,menu1,menu2,gameEndTurn,endTurn1,endTurn2,cTc,cT1,cT2,cBc,cB1,cB2);

         gameBackground.setPosition(map.displacementX,map.displacementY);

         gameInterface.setPosition(-1,-1);

         gameMenu.setPosition(1700,0);
         gameEndTurn.setPosition(1500,5);
         cTc.setPosition(1680,750);

         cBc.setPosition(1680,890);

         selectUnit(&map,window,cSel,&select,currentPlayerTurn);

        if(select.status==1){
        cSel.setPosition(select.cell->X,select.cell->Y);
        }

         sf::Event event;


          if (sf::Mouse::isButtonPressed(sf::Mouse::Left)&&menu==1){
                    if(pauseMenu(window)==0){
                        break;
                    }
          }

            if (sf::Mouse::isButtonPressed(sf::Mouse::Left)&&menu>=3){

                    createUnit(&map,&players,currentPlayerTurn,menu,window,&select,gameBackground,gameInterface,gameMenu,gameEndTurn,cTc,cBc);
          }

           if (sf::Mouse::isButtonPressed(sf::Mouse::Left)&&menu==2){

                    isEnd(&map,window,endFn);

                    getOP(&map,&players);
                    getResources(&map,currentPlayerTurn,&players);
                     deleteSelect(&select);
                    overmind(&map,window,&select,aCell,cEnemy,&gCur,gameBackground,gameInterface,gameMenu,gameEndTurn,currentPlayerTurn,cTc,&players,cBc);


                    endTurn(&map);
                    Sleep(500);
          }



          if (sf::Mouse::isButtonPressed(sf::Mouse::Right)){

           deleteSelect(&select);

          }





         while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                window.close();
            }
        }


        window.clear(sf::Color::Black);
        window.draw(gameBackground);
        drawUnits(&map,window);
        if(cursorConfirm(window,&map,gameCursor,&gCur)==1){
        window.draw(gameCursor);
        }
        if(select.status==1){
                window.draw(cSel);
                findWay(&map,window,&select,aCell,cEnemy,&gCur,gameBackground,gameInterface,gameMenu,gameEndTurn,currentPlayerTurn,cTc,&players,cBc);

        }
        window.draw(gameInterface);

        if(select.status==1){
           pData(window,&select);
        }



        window.draw(gameMenu);
        window.draw(gameEndTurn);

        drawMinMap(window,currentPlayerTurn,&map);




        drawPlayer(window,currentPlayerTurn,&players);

        window.draw(cTc);

        window.draw(cBc);



        window.display();







}

}
Ejemplo n.º 16
0
/////////////////////////////////////////////////////////////////////////////
// creates the Seafarers: Five Islands (V) map
/////////////////////////////////////////////////////////////////////////////
void CMapDatabase::createFiveIslandsV(CS3DMap *pMap)
{
	//identifier
	pMap->m_uiID = MAP_SEA_FIVE_ISLANDS_V;

	//last time edited
	pMap->m_timeEdit = COleDateTime::GetCurrentTime();

	//type of game
	pMap->m_iMode = MAP_SEAFARERS;

	//official map
	pMap->m_bOfficial = TRUE;

	//play to 12 points
	pMap->m_iPoints = 12;

	//map name
	pMap->m_strMapName = "Five Islands (V)";
	pMap->m_strMapCreator = "Jason Fugate";

	//9 allowed cards in hamd
	pMap->m_iAllowedCards = 9;

	//beefed up starting bank
	pMap->m_iBankRes = 25;

	//beefed up dev cards
	pMap->m_iDevTotal = 34;
	pMap->m_iDevCards[CARD_VICTORY] = 5;
	pMap->m_iDevCards[CARD_MONOPOLY] = 3;
	pMap->m_iDevCards[CARD_ROAD_BUILD] = 3;
	pMap->m_iDevCards[CARD_YEAR_PLENTY] = 3;
	pMap->m_iDevCards[CARD_SOLDIER] = 20;

	//this map uses the initial ship requirements
	pMap->m_bRequiresInitialShips = TRUE;

	//there are no random tiles
	pMap->m_nRandomTiles = 0;

	//ports
	pMap->m_nPorts = 10;

	//chip texture file used
	pMap->m_iChipsUsed = MAP_USES_SEA_CHIPS;	

	//min/max players (five player only)
	pMap->m_iMinPlayers = 5;
	pMap->m_iMaxPlayers = 5;

	//number of land/sea tiles
	pMap->m_iLandTiles = 27;
	pMap->m_iSeaTiles = 58;

	//15 ships in this scenario
	pMap->m_iStockShips = 15;

	//set the extra points
	pMap->m_nBonus1 = 1;
	pMap->m_nBonus2 = 2;

	//set the random resource amounts
	pMap->m_iRandomRes[RES_TIMBER] = 0;
	pMap->m_iRandomRes[RES_WHEAT] = 0;
	pMap->m_iRandomRes[RES_ORE] = 0;
	pMap->m_iRandomRes[RES_CLAY] = 0;
	pMap->m_iRandomRes[RES_SHEEP] = 0;
	pMap->m_iRandomRes[RES_GOLD] = 0;
	pMap->m_iRandomRes[RES_DESERT] = 0;
	pMap->m_iRandomRes[RES_OCEAN] = 0;
	pMap->m_iRandomRes[RES_PORT3] = 5;
	pMap->m_iRandomRes[RES_PORTTIMBER] = 1;
	pMap->m_iRandomRes[RES_PORTWHEAT] = 1;
	pMap->m_iRandomRes[RES_PORTORE] = 1;
	pMap->m_iRandomRes[RES_PORTCLAY] = 1;
	pMap->m_iRandomRes[RES_PORTSHEEP] = 1;

	//create the map
	createMap(MAP_BORDERS_XX_X, pMap, coordsFiveIslandsV);

	//start out zoomed out a little farther than normal
	pMap->m_dInitialDepth = 100.;
}
Ejemplo n.º 17
0
void setup(){
	map = createMap(4, getHashCode, comparator);
	map2 = createMap(4, getHashCode2, comparator2);
}
Ejemplo n.º 18
0
/**
 * Load a Ruby file then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by refernce as Ruby Hash.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param real_inputs the maps containing the inputs
 * @param real_outputs the maps containing the outputs
 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1 
 *  if the service failed to load or throw error at runtime.
 */
int zoo_ruby_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
#if RUBY_API_VERSION_MAJOR >= 2 || RUBY_API_VERSION_MINOR == 9
  ruby_sysinit(&argc,&argv);
  RUBY_INIT_STACK;
#endif
  ruby_init();
  maps* m=*main_conf;
  maps* inputs=*real_inputs;
  maps* outputs=*real_outputs;
  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
  char *ntmp=tmp0->value;
  map* tmp=NULL;
  ruby_init_loadpath();
  ruby_script("ZOO_EMBEDDED_ENV");
  
  VALUE klass=rb_define_module("Zoo");
  rb_define_const(klass,"SERVICE_SUCCEEDED",INT2FIX(3));
  rb_define_const(klass,"SERVICE_FAILED",INT2FIX(4));
  typedef VALUE (*HOOK)(...);
  rb_define_module_function(klass,"Translate",reinterpret_cast<HOOK>(RubyTranslate),-1);
  rb_define_module_function(klass,"UpdateStatus",reinterpret_cast<HOOK>(RubyUpdateStatus),-1);

  int error = 0;
		
  ID rFunc=Qnil;
  tmp=getMap(s->content,"serviceProvider");
  if(tmp!=NULL){
#if RUBY_VERSION_MINOR == 8
    const char* script = ruby_sourcefile = rb_source_filename(tmp->value);
    rb_protect(LoadWrap, reinterpret_cast<VALUE>(script), &error);
#else
    rb_load_protect(rb_str_new2(tmp->value), 0, &error);
#endif
    if(error) {
      ruby_trace_error(m);
      return -1;
    }
#if RUBY_VERSION_MINOR == 8
    ruby_exec();
#else
    ruby_exec_node(NULL);
#endif
  }
  else{
    map* err=createMap("text","Unable to parse serviceProvider please check your zcfg file.");
    addToMap(err,"code","NoApplicableCode");
    printExceptionReportResponse(m,err);
    return -1;
  }
  int res=SERVICE_FAILED;
  rFunc=rb_intern(s->name);
  if(rFunc!=Qnil){
    VALUE arg1=RubyHash_FromMaps(m);
    VALUE arg2=RubyHash_FromMaps(inputs);
    VALUE arg3=RubyHash_FromMaps(outputs);
    VALUE rArgs[3]={arg1,arg2,arg3};
    if (!rArgs)
      return -1;
    struct my_callback data;
    data.obj=Qnil;
    data.method_id=rFunc;
    data.nargs=3;
    data.args[0]=rArgs[0];
    data.args[1]=rArgs[1];
    data.args[2]=rArgs[2];
    typedef VALUE (*HOOK)(VALUE);
    VALUE tres=rb_protect(reinterpret_cast<HOOK>(FunCallWrap),(VALUE)(&data),&error);
    if (TYPE(tres) == T_FIXNUM) {
      res=FIX2INT(tres);
      freeMaps(real_outputs);
      free(*real_outputs);
      freeMaps(main_conf);
      free(*main_conf);
      *main_conf=mapsFromRubyHash(arg1);
      *real_outputs=mapsFromRubyHash(arg3);
#ifdef DEBUG
      dumpMaps(*main_conf);
      dumpMaps(*real_outputs);
#endif
    }else{
      ruby_trace_error(m);
      res=-1;
    }
  }
  else{
    char tmpS[1024];
    sprintf(tmpS, "Cannot find the %s function in the %s file.\n", s->name, tmp->value);
    map* tmps=createMap("text",tmpS);
    printExceptionReportResponse(m,tmps);
    res=-1;
  }
  ruby_finalize();
  return res;
}
Ejemplo n.º 19
0
/**
 * Convert a JavaScript Object to a maps
 *
 * @param cx the JavaScript context
 * @param t the JavaScript Object to convert
 * @return a new maps containing the JavaScript Object
 */
maps* mapsFromJSObject(JSContext *cx,jsval t){
  maps *res=NULL;
  maps *tres=NULL;
  jsint oi=0;
  JSObject* tt=JSVAL_TO_OBJECT(t);
  if(JS_IsArrayObject(cx,tt)){
#ifdef JS_DEBUG
    fprintf(stderr,"Is finally an array !\n");
#endif
  }
  else{
#ifdef JS_DEBUG
    fprintf(stderr,"Is not an array !\n");
#endif
    JSIdArray *idp=JS_Enumerate(cx,tt);
    if(idp!=NULL) {
      int index;
      jsdouble argNum;
#ifdef JS_DEBUG
      fprintf(stderr,"Properties length :  %d \n",idp->length);
#endif
      
      for (index=0,argNum=idp->length;index<argNum;index++) { 
	jsval id = idp->vector[index];
	jsval vp;
	JS_IdToValue(cx,id,&vp);
	char *tmp;
	JSString *jsmsg;
	size_t len1;
	jsmsg = JS_ValueToString(cx,vp);
	len1 = JS_GetStringLength(jsmsg);
	
	tmp=JS_EncodeString(cx,jsmsg);
	tres=createMaps(tmp);

	jsval nvp=JSVAL_NULL;
	if((JS_GetProperty(cx, tt, tmp, &nvp)==JS_FALSE)){
#ifdef JS_DEBUG
	  fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
#endif
	}
	free(tmp);
	JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
	JS_ValueToObject(cx,nvp,&nvp1);
	jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
	if(JSVAL_IS_OBJECT(nvp1j)){
	  tres->content=mapFromJSObject(cx,nvp1j);
	}

	jsval nvp0=JSVAL_NULL;
	JSObject *nvp01=JSVAL_TO_OBJECT(JSVAL_NULL);
	if((JS_GetProperty(cx, nvp1, "child", &nvp0)==JS_FALSE)){
#ifdef JS_DEBUG
	  fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
#endif
	}
	JS_ValueToObject(cx,nvp0,&nvp01);
	jsval nvp01j=OBJECT_TO_JSVAL(nvp01);
	if(!JSVAL_IS_NULL(nvp01j)){
	  tres->child=mapsFromJSObject(cx,nvp01j);
	}

	if(res==NULL)
	  res=dupMaps(&tres);
	else
	  addMapsToMaps(&res,tres);
	freeMaps(&tres);
	free(tres);
	tres=NULL;
      }
      JS_DestroyIdArray(cx,idp);
    }
  }

  jsuint len;
  JSBool hasLen=JS_GetArrayLength(cx, tt, &len);
#ifdef JS_DEBUG
  if(hasLen==JS_FALSE){
    fprintf(stderr,"outputs array is empty\n");
  }
  fprintf(stderr,"outputs array length : %d\n",len);
#endif
  for(oi=0;hasLen && oi < len;oi++){
#ifdef JS_DEBUG
    fprintf(stderr,"outputs array length : %d step %d \n",len,oi);
#endif
    jsval tmp1;
    JSBool hasElement=JS_GetElement(cx,tt,oi,&tmp1);
    JSObject *otmp1=JSVAL_TO_OBJECT(tmp1);
    JSIdArray *idp=JS_Enumerate(cx,otmp1);
    if(idp!=NULL) {
      int index;
      jsdouble argNum;
#ifdef JS_DEBUG
      fprintf(stderr,"Properties length :  %d \n",idp->length);
#endif
      tres=(maps*)malloc(MAPS_SIZE);
      tres->name=NULL;
      tres->content=NULL;
      tres->next=NULL;

      for (index=0,argNum=idp->length;index<argNum;index++) { 
	jsval id = idp->vector[index];
	jsval vp;
	JS_IdToValue(cx,id,&vp);
	char *tmp;
	JSString *jsmsg;
	size_t len1;
	jsmsg = JS_ValueToString(cx,vp);
	len1 = JS_GetStringLength(jsmsg);
	tmp=JS_EncodeString(cx,jsmsg);
#ifdef JS_DEBUG
	fprintf(stderr,"Enumerate id : %d => %s\n",oi,tmp);
#endif
	jsval nvp=JSVAL_NULL;
	if((JS_GetProperty(cx, JSVAL_TO_OBJECT(tmp1), tmp, &nvp)==JS_FALSE)){
#ifdef JS_DEBUG
	  fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
#endif
	}
	free(tmp);
	if(JSVAL_IS_OBJECT(nvp)){
#ifdef JS_DEBUG
	  fprintf(stderr,"JSVAL NVP IS OBJECT\n");
#endif
	}

	JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
	JS_ValueToObject(cx,nvp,&nvp1);
	jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
	if(JSVAL_IS_OBJECT(nvp1j)){
	  JSString *jsmsg1;
	  char *tmp1, *tmp2;
	  JSObject *nvp2=JSVAL_TO_OBJECT(JSVAL_NULL);
	  jsmsg1 = JS_ValueToString(cx,nvp1j);
	  len1 = JS_GetStringLength(jsmsg1);
	  tmp1=JS_EncodeString(cx,jsmsg1);
	  tmp2=JS_EncodeString(cx,jsmsg);
#ifdef JS_DEBUG
	  fprintf(stderr,"JSVAL NVP1J IS OBJECT %s = %s\n",JS_EncodeString(cx,jsmsg),tmp1);
#endif
	  if(strcasecmp(tmp1,"[object Object]")==0){
	    tres->name=zStrdup(tmp2);
	    tres->content=mapFromJSObject(cx,nvp1j);
	  }
	  else
	    if(strcasecmp(tmp2,"name")==0){
	      tres->name=zStrdup(tmp1);
	    }
	    else{
	      if(tres->content==NULL)
		tres->content=createMap(tmp2,tmp1);
	      else
		addToMap(tres->content,tmp2,tmp1);
	    }
	  free(tmp1);
	  free(tmp2);
	}
#ifdef JS_DEBUG
	else
	  fprintf(stderr,"JSVAL NVP1J IS NOT OBJECT !!\n");
#endif
      }
#ifdef JS_DEBUG
      dumpMaps(tres);
#endif
      if(res==NULL)
	res=dupMaps(&tres);
      else
	addMapsToMaps(&res,tres);
      freeMaps(&tres);
      free(tres);
      tres=NULL;
      JS_DestroyIdArray(cx,idp);
    }
  }
#ifdef JS_DEBUG
  dumpMaps(res);
#endif
  return res;
}
Ejemplo n.º 20
0
int main (int argc, const char * argv[]) {
	char *word;
	ValueType *value;
	const char* filename;
	struct hashMap *hashTable;
	int tableSize = 10;
	clock_t timer;
	FILE *fileptr;	
    /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.
     
     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc == 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/
    
    printf("opening file: %s\n", filename);
    
	timer = clock();
	
	hashTable = createMap(tableSize);	   
	
	/*... concordance code goes here ...*/
	fileptr = fopen(filename, "r");
	
	
	while(1){
		
		word = getWord(fileptr);
		if(word == NULL){
			break;
		}		
		value = atMap(hashTable, word);
		if(value == NULL)
		{
			value = malloc(sizeof(int*));
			*((int*)value) = 1;
		}
		else if(value != NULL)
		{
			*((int *)value) += 1;
		}
		insertMap(hashTable, word, ((void *)value));
	
	}
   
			
	/*... concordance code ends here ...*/
	

	printMap(hashTable);
	timer = clock() - timer;
	printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
	printf("Table capacity = %d\n", capacity(hashTable));
	printf("Table load = %f\n", tableLoad(hashTable));
	
	printf("Deleting keys\n");
	
	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
	printMap(hashTable);


		
	deleteMap(hashTable);
	printf("\nDeleted the table\n");   
	return 0;
}
Ejemplo n.º 21
0
DePee::DePee(osg::Group* parent, osg::Group* subgraph, unsigned width, unsigned height)
{
    _renderToFirst = false;

    _isSketchy =false;
    _isColored = false;
    _isEdgy = true;
    _isCrayon = false;

    _normalDepthMapProgram = Utility::createProgram("shaders/depthpeel_normaldepthmap.vert","shaders/depthpeel_normaldepthmap.frag");
    _colorMapProgram = Utility::createProgram("shaders/depthpeel_colormap.vert","shaders/depthpeel_colormap.frag" );
    _edgeMapProgram = Utility::createProgram("shaders/depthpeel_edgemap.vert", "shaders/depthpeel_edgemap.frag");

    _parent = new osg::Group;
    parent->addChild(_parent.get());
    _subgraph = subgraph;

    _width = width;
    _height = height;
    _texWidth = width;
    _texHeight = height;

    assert(parent);
    assert(subgraph);

    _fps = 0;
    _colorCamera = 0;

    _sketchy = new osg::Uniform("sketchy", false);
    _colored = new osg::Uniform("colored", false);
    _edgy = new osg::Uniform("edgy", true);
    _sketchiness = new osg::Uniform("sketchiness", (float) 1.0);

    _normalDepthMap0  = Utility::newColorTexture2D(_texWidth, _texHeight, 32);
    _normalDepthMap1  = Utility::newColorTexture2D(_texWidth, _texHeight, 32);
    _edgeMap = Utility::newColorTexture2D(_texWidth, _texHeight, 8);
    _colorMap = Utility::newColorTexture2D(_texWidth, _texHeight, 8);

    //create a noise map...this doesn't end up in a new rendering pass
    (void) createMap(NOISE_MAP);

    //the viewport aligned quad
    _quadGeode = Utility::getCanvasQuad(_width, _height);


    //!!!Getting problems if assigning unit to texture in depth peeling subgraph and removing depth peeling steps!!!
    //That's why it is done here
    osg::StateSet* stateset = _parent->getOrCreateStateSet();
    stateset->setTextureAttributeAndModes(1, _normalDepthMap0.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(2, _normalDepthMap1.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(3, _edgeMap.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(4, _colorMap.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(5, _noiseMap.get(), osg::StateAttribute::ON);

    // render the final thing
    (void) createFinal();

    //take one step initially
    addDePeePass();

    //render head up display
    (void) createHUD();
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
  if (argc < 4){
    printf( "Usage: %s <servicename> <directory>|<definition_file> <REQUEST> [<functionname> <param_1>[...<param_n>]]\n", basename(argv[0]) );
    return 1;
  }
 
  map* outputs=NULL;
  /**
   * Parsing inputs (need a loop over all files in the service path !!)
   */
  maps* m;
  m=(maps*)malloc(MAP_SIZE);
  conf_read("main.cfg",m);
  map* tmpm=getMapFromMaps(m,"main","serverAddress");
  int toto=count(tmpm);
  //printf(" - %i \n",toto);

  if(tmpm!=NULL)
    SERVICE_URL=strdup(tmpm->value);
  else
    SERVICE_URL=DEFAULT_SERVICE_URL;

  service* s[100];
  service* s1;
  int scount=0;

  if(strcmp(argv[3],"GetCapabilities")==0){
    int i=0;
    struct dirent *dp;
    DIR *dirp = opendir(argv[1]);
    int t;
    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
    xmlNodePtr n = printGetCapabilitiesHeader(doc,argv[2],m);
    
    int saved_stdout = dup(fileno(stdout));
    stdout = freopen("/dev/null" , "w" , stdout);
    while ((dp = readdir(dirp)) != NULL)
      if(strstr(dp->d_name,".zcfg")!=0){
	char toto1[1024];
	sprintf(toto1,"%s%s",argv[1],dp->d_name);
	char *toto=toto1;
	s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
	//s[scount]=(service*)malloc(sizeof(service*));
	//#ifdef DEBUG
	fprintf(stderr,"#################\n%s\n#################\n",toto1);
	//printf("|(1)");
	//#endif
	t=getServiceFromFile(toto1,&s1);
	
	//printf("|(2)");
	printGetCapabilitiesForProcess(m,n,s1);
	/**
	 * Valgrind told us that there is an issue regarding a 
	 * "conditional jump or move depends on uninitialised value(s)" for
	 * freeIOType
	 */
	//freeService(&s1);
	scount++;
      }
    char buf[20];
    sprintf(buf, "/dev/fd/%d", saved_stdout);
    stdout = freopen(buf , "w" , stdout);

    printDocument(doc);
    fflush(stdout);
    free(m);
    return 0;
  }
  else{
    s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
    //s[0]=(service*)malloc(sizeof(service*));
    int t=getServiceFromFile(argv[1],&s1);
    if(strcmp(argv[3],"DescribeProcess")==0){
      printDescribeProcessResponse(s1,argv[2]);
      //dumpMaps(m);
      //free(s1);
      return 0;
    }
    else
      if(strcmp(argv[3],"Execute")!=0){
	fprintf(stderr,"");
	//free(s);
	return 0;
      }
  }
  //dumpService(s);
  s[0]=s1;
  map* inputs=NULL;
  elements* c_inputs=s1->inputs;
  int j;
  for(j=0;j<argc-5;j++){
    //dumpElements(c_inputs);
    if(inputs!=NULL)
      addToMap(inputs,c_inputs->name,argv[j+5]);
    else
      inputs=createMap(c_inputs->name,argv[j+5]);
    if(c_inputs->next!=NULL || j+1>=argc-5)
      c_inputs=c_inputs->next;
    else{
      map* tmps=createMap("text","ERROR you provided more inputs than requested.");
      printExceptionReportResponse(m,tmps);
      //printf("ERROR you provided more inputs than requested.");
      return -1;
    }
#ifdef DEBUG
    printf("ARGV1 %d %s\n",j,inputs->value);
#endif
  }

#ifdef DEBUG
  dumpMap(inputs);
#endif

  const struct tm *tm;
  size_t len;
  time_t now;
  char *sDate;
  
  now = time ( NULL );
  tm = localtime ( &now );

  sDate = new char[TIME_SIZE];

  len = strftime ( sDate, TIME_SIZE, "%d-%B-%YT%I:%M:%SZ", tm );

#ifdef DEBUG
  printf("Trying to load %s\n", argv[2]);
#endif
  void* so = dlopen(argv[2], RTLD_LAZY);
  char *errstr;
  errstr = dlerror();
  if( so != NULL ) {
    typedef int (*execute_t)(map**,map**);
#ifdef DEBUG
    printf("Library loaded %s \n",errstr);
#endif
    execute_t execute=(execute_t)dlsym(so,argv[4]);
#ifdef DEBUG
    errstr = dlerror();
    printf("Function loaded %s\n",errstr);
#endif	

    /**
     * Need to check if we need to fork to load a status enabled 
     */
    char _toto[10];
    sprintf(_toto,"input_%i",argc-5);
    map* toto=getMap(inputs,_toto);
    if(strcmp(argv[argc-1],"bg")!=0){
#ifdef DEBUG
      printf("RUN IN NORMAL MODE \n");
#endif
      int res=execute(&inputs,&outputs);
#ifdef DEBUG
      printf("RUNNED IN NORMAL MODE \n");
      dumpMap(inputs);
      dumpMap(outputs);
#endif
      printProcessResponse(m,getpid(),s[0],argv[2],res,inputs,outputs);
    }
    else{
      pid_t   pid;
      int cpid=getpid();
      pid = fork ();
      if (pid > 0) {
	/**
	 * dady :
	 * set status to SERVICE_ACCEPTED
	 */
	printProcessResponse(m,pid,s[0],argv[2],SERVICE_ACCEPTED,inputs,outputs);
      }else if (pid == 0) {
	/* son */
	if (signal(SIGINT, sigint_handler) == SIG_ERR) {
	  printf("signal");
	  map* tmps=createMap("text","father received sigint.");
	  printExceptionReportResponse(m,tmps);
	  exit(1);
	}
#ifdef DEBUG
	printf("RUN IN BACKGROUND MODE \n");
#endif
	char tmp1[256];
	sprintf(tmp1,"service/temp/%s_%d.xml",argv[2],getpid());
	stdout = freopen(tmp1 , "w+" , stdout);
	/**
	 * set status to SERVICE_STARTED
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],SERVICE_STARTED,inputs,outputs);
	fflush(stdout);
	rewind(stdout);
	int t=execute(&inputs,&outputs);
	/**
	 * set status to status code returned by the service function
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],t,inputs,outputs);
      } else {
	/* error */
      }
    }
#ifdef DEBUG
    errstr = dlerror();
    printf("Function successfully loaded %s, unloading now.\n",errstr);
#endif
    dlclose(so);
  }
  else {
#ifdef DEBUG
    printf("C Library can't be loaded %s \n",errstr);
#endif
    python_support(m,s[0],argc,argv,inputs,outputs);
  }
  return 0;
}
Ejemplo n.º 23
0
//
// メインプログラム
//
int main()
{
    // GLFW を初期化する
    if (glfwInit() == GL_FALSE)
    {
        // 初期化に失敗した
        std::cerr << "Can't initialize GLFW" << std::endl;
        return 1;
    }

    // プログラム終了時の処理を登録する
    atexit(cleanup);

    // ウィンドウを作成する
    Window window("Irradiance Mapping", 960, 540);

    // OpenGL の初期設定
    glClearColor(0.3f, 0.5f, 0.8f, 0.0f);
    glEnable(GL_NORMALIZE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_MULTISAMPLE);

    // 陰影付けを無効にする
    glDisable(GL_LIGHTING);

    // テクスチャ
    GLuint imap[mapcount], emap[mapcount];
    glGenTextures(mapcount, imap);
    glGenTextures(mapcount, emap);

    // テクスチャの読み込み
    for (size_t i = 0; i < mapcount; ++i)
    {
#if USEMAP
        loadMap(irrmaps[i], envmaps[i], imap[i], emap[i]);
#else
        createMap(skymaps[i], skysize, imap[i], imapsize, isamples, emap[i], emapsize, esamples, ambient, shininess);
#endif
    }

    // 放射照度マップのかさ上げに使うテクスチャユニットの設定
    glActiveTexture(GL_TEXTURE0);
    glEnable(GL_TEXTURE_2D);
    irradiance();

    // 放射照度マップのかさ上げに使うテクスチャユニットの設定
    glActiveTexture(GL_TEXTURE1);
    glEnable(GL_TEXTURE_2D);
    diffuse();

    // 環境マップの加算に使うテクスチャユニットの設定
    glActiveTexture(GL_TEXTURE2);
    glEnable(GL_TEXTURE_2D);
    reflection();

    // 材質データ
    GLuint ng;
    GLuint (*group)[2];
    GLfloat (*amb)[4], (*diff)[4], (*spec)[4], *shi;

    // 形状データ
    GLuint nv;
    GLfloat (*pos)[3], (*norm)[3];

    // 形状データの読み込み
    ggLoadObj(filename, ng, group, amb, diff, spec, shi, nv, pos, norm, false);

    // ウィンドウが開いている間繰り返す
    while (window.shouldClose() == GL_FALSE)
    {
        // ウィンドウを消去する
        window.clear();

        // テクスチャの選択
        const int select(window.getSelection() % mapcount);

        // 明るさ
        GLfloat brightness[4];
        window.getBrightness(brightness);

        // 放射照度マップのかさ上げ
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, imap[select]);
        glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, brightness);

        // 拡散反射光強度の算出
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, imap[select]);

        // 環境マッピング
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, emap[select]);

        // モデルビュー変換行列の設定
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        // 視点の移動
        glTranslatef(window.getPosition()[0], window.getPosition()[1], window.getPosition()[2]);

        // トラックボール処理による回転
        glMultMatrixf(window.getTb());

        // シーンの描画
        scene(ng, group, diff, spec, nv, pos, norm);

        // 床の描画
        floor(5, -1.0f);

        // カラーバッファを入れ替えてイベントを取り出す
        window.swapBuffers();
    }
}
Ejemplo n.º 24
0
//---------------------------------------------------------------------------
CGridMap::CGridMap ( uint8_t* data, int numCellsX, int numCellsY,
                     float cellSize )
{
  createMap ( data, numCellsX, numCellsY, cellSize );
}
Ejemplo n.º 25
0
int main (int argc, const char * argv[]) {
    const char* filename;
    struct hashMap *hashTable;
    int tableSize = 10;
    clock_t timer;
    FILE *fileptr;
    /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.

     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc >= 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/

    printf("opening file: %s\n", filename);

    fileptr = fopen(filename, "r");
    if(fileptr == NULL) {
        char err[255];
        sprintf(err, "Failure opening file %s; exiting.\n", filename);
        perror(err);
        exit(EXIT_FAILURE);
    }

    timer = clock();

    hashTable = createMap(tableSize);

    char *curr;
    ValueType *val;

    while((curr = getWord(fileptr)) != NULL) {
        if((val = atMap(hashTable, curr)) != NULL)
            (*val)++;
            //insertMap(hashTable, curr, (*val)+1);
        else
            insertMap(hashTable, curr, 1);
        free(curr);
    }

    fclose(fileptr);
    //fclose(outfileptr);

    printMap(hashTable);
    timer = clock() - timer;
    printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
    printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
    printf("Table capacity = %d\n", capacity(hashTable));
    printf("Table load = %f\n", tableLoad(hashTable));

    printf("Deleting keys\n");

    removeKey(hashTable, "and");
    removeKey(hashTable, "me");
    removeKey(hashTable, "the");
    //printMap(hashTable);

    deleteMap(hashTable);
    printf("\nDeleted the table\n");
    return 0;
}
Ejemplo n.º 26
0
int main (int argc, const char * argv[]) {
	char *fn; /* File name */
	struct hashMap *hashTable, *hashTable2;
	FILE *filePtr;

	fn = "text1.txt";/* the file name and path */
	printf("Opening file: %s \n", fn);
	filePtr = fopen(fn, "r");
	hashTable = createMap(40, 1);
  char *word;
  while((word = getWord(filePtr)) != '\0') {
      insertMap(hashTable, word, 1);
  }

  printf("--------------- Testing contains --------------- \n");

  assertTrue(containsKey(hashTable, "it") == 1, "Search for 'it'");
  assertTrue(containsKey(hashTable, "comparison") == 1, "Search for 'comparison'");
  assertTrue(containsKey(hashTable, "period") == 1, "Search for 'period'");
  assertTrue(containsKey(hashTable, "despair") == 1, "Search for 'despair'");
    assertTrue(containsKey(hashTable, "deriop") == 0, "Search for 'deriop'");
    assertTrue(containsKey(hashTable, "yuck") == 0, "Search for 'yuck'");

    printf("--------------- Testing table stats --------------- \n");

    assertTrue(hashTable->tableSize == 40, "Test table size");
    assertTrue(fullBuckets(hashTable) == 30, "Test full buckets");
    assertTrue(emptyBuckets(hashTable) == 10, "Test empty buckets");
    assertTrue(linkCount(hashTable) == 59, "Test link count");

    printf("--------------- Testing remove --------------- \n");

    removeKey(hashTable, "yuck"); /* Should print some type of 'not found' message */
    removeKey(hashTable, "despair");
    assertTrue(containsKey(hashTable, "despair") == 0, "Search for 'despair'");

    printf("--------------- Printing hash table --------------- \n");

    printMap(hashTable);

    deleteMap(hashTable);

    printf("--------------- New table - same text file - new hash --------------- \n");

    fn = "text1.txt";/* the file name and path */
		printf("Opening file: %s \n", fn);
		filePtr = fopen(fn, "r");
		hashTable2 = createMap(40, 2);

    while((word = getWord(filePtr)) != '\0') {
        insertMap(hashTable2, word, 1);
    }

    printf("--------------- Testing table stats 2 --------------- \n");

    assertTrue(hashTable2->tableSize == 80, "Test table size");
    assertTrue(fullBuckets(hashTable2) == 38, "Test full buckets");
    assertTrue(emptyBuckets(hashTable2) == 42, "Test empty buckets");
    assertTrue(linkCount(hashTable2) == 59, "Test link count");

    printf("Closing file: %s \n", fn);
		fclose(filePtr);

	/* Concordance testing	*/




	struct hashMap * concord;

  fn = "text2.txt";
	printf("Opening file: %s \n", fn);
	filePtr = fopen(fn, "r");
	concord = createMap(10, 2);


    while((word = getWord(filePtr)) != '\0') {
        concordance(concord, word);
    }

    printf("--------------- Concordance table stats --------------- \n");

    printf("table size: %d \n", concord->tableSize);
    printf("full buckets: %d \n", fullBuckets(concord));
    printf("empty buckets: %d \n", emptyBuckets(concord));
    printf("link count: %d \n", linkCount(concord));



    /*Test further on your own */

	return 0;
}
Ejemplo n.º 27
0
DataGrid::DataGrid(unsigned const int w, unsigned const int h) {
	_width = _height = 0;
	_data = 0;
	createMap(w, h);
}
Ejemplo n.º 28
0
int main (int argc, const char * argv[]) {
	const char* filename;
	struct hashMap *hashTable;	
	int tableSize = 1000;
	clock_t timer;
	FILE *fileptr;	
 	   /*
     this part is using command line arguments, you can use them if you wish
     but it is not required. DO NOT remove this code though, we will use it for
     testing your program.
     
     if you wish not to use command line arguments manually type in your
     filename and path in the else case.
     */
    if(argc == 2)
        filename = argv[1];
    else
        filename = "input1.txt"; /*specify your input text file here*/
    
    printf("opening file: %s\n", filename);
    
	timer = clock();
	
	/*... concordance code goes here ...*/

       	hashTable = createMap(tableSize); 
       
	fileptr = fopen(filename, "r");
//	char *character = "";

	 
//	ValueType* val; 
//	val = atMap(hashTable, character); 
/*
 * I couldnt figure out how to properly set up the concordance*/
		
		insertMap(hashTable, getWord(fileptr), 0); 
		insertMap(hashTable, getWord(fileptr), 0);
		insertMap(hashTable, getWord(fileptr), 0); 
		insertMap(hashTable, getWord(fileptr), 0); 

	
	fclose(fileptr);   		
	/*... concordance code ends here ...*/

	printMap(hashTable);
	timer = clock() - timer;
	printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
   	printf("Table count = %d\n", size(hashTable));


printf("Table load = %f\n", tableLoad(hashTable));
	
	printf("Deleting keys\n");
	
	removeKey(hashTable, "and");
	removeKey(hashTable, "me");
	removeKey(hashTable, "the");
	printMap(hashTable);
		
	deleteMap(hashTable);
	printf("\nDeleted the table\n");   
	return 0;
}
Ejemplo n.º 29
0
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(caQtDM);
#ifdef MOBILE
    Q_INIT_RESOURCE(qtcontrols);
#endif
    QApplication app(argc, argv);
    QApplication::setOrganizationName("Paul Scherrer Institut");
    QApplication::setApplicationName("caQtDM");

#ifdef MOBILE_ANDROID
    app.setStyle(QStyleFactory::create("fusion"));
#endif

    // we do not want numbers with a group separators
    QLocale loc = QLocale::system();
    loc.setNumberOptions(QLocale::OmitGroupSeparator);
    loc.setDefault(loc);

    QString fileName = "";
    QString macroString = "";
    QString geometry = "";
    QString macroFile = "";
    QMap<QString, QString> options;
    options.clear();

    searchFile *s = new searchFile("caQtDM_stylesheet.qss");
    QString fileNameFound = s->findFile();
    if(fileNameFound.isNull()) {
        printf("caQtDM -- file <caQtDM_stylesheet.qss> could not be loaded, is 'CAQTDM_DISPLAY_PATH' <%s> defined?\n", qasc(s->displayPath()));
    } else {
        QFile file(fileNameFound);
        file.open(QFile::ReadOnly);
        QString StyleSheet = QLatin1String(file.readAll());
        printf("caQtDM -- file <caQtDM_stylesheet.qss> loaded as the default application stylesheet\n");
        app.setStyleSheet(StyleSheet);
        file.close();
    }

    int	in, numargs;
    bool attach = false;
    bool minimize= false;
    bool nostyles = false;
    bool printscreen = false;
    bool resizing = true;

    for (numargs = argc, in = 1; in < numargs; in++) {
        //qDebug() << argv[in];
        if ( strcmp (argv[in], "-display" ) == 0 ) {
            in++;
            printf("caQtDM -- display <%s>\n", argv[in]);
        } else if ( strcmp (argv[in], "-macro" ) == 0 ) {
            in++;
            printf("caQtDM -- macro <%s>\n", argv[in]);
            macroString = QString(argv[in]);
        } else if ( strcmp (argv[in], "-attach" ) == 0 ) {
            printf("caQtDM -- will attach to another caQtDM if running\n");
            attach = true;
        } else if ( strcmp (argv[in], "-noMsg" ) == 0 ) {
            printf("caQtDM -- will minimize its main windows\n");
            minimize = true;
        } else if( strcmp (argv[in], "-macrodefs" ) == 0) {
            in++;
            printf("caQtDM -- will load macro string from file <%s>\n", argv[in]);
            macroFile = QString(argv[in]);
        } else if ( strcmp (argv[in], "-noStyles" ) == 0 ) {
            printf("caQtDM -- will not replace the default application stylesheet caQtDM_stylesheet.qss\n");
            nostyles = true;
        } else if ( strcmp (argv[in], "-x" ) == 0 ) {

        } else if ( strcmp (argv[in], "-displayFont" ) == 0 ) {
             in++;
        } else if(!strcmp(argv[in],"-help") || !strcmp(argv[in],"-h") || !strcmp(argv[in],"-?")) {
             in++;
                 printf("Usage:\n"
                   "  caQtDM[X options]\n"
                   "  [-help | -h | -?]\n"
                   "  [-x]\n"
                   "  [-attach]\n"
                   "  [-noMsg]\n"
                   "  [-noStyles]      works only when not attaching\n"
                   "  [-macro \"xxx=aaa,yyy=bbb, ...\"]\n"
                   "  [-macrodefs filename] will load macro definitions from file\n"
                   "  [-dg [<width>x<height>][+<xoffset>-<yoffset>]\n"
                   "  [-httpconfig] will display a network configuration screen at startup\n"
                   "  [-print] will print file and exit\n"
                   "  [-noResize] will prevent resizing\n"
                   "  [-cs defaultcontrolsystempluginname]\n"
                   "  [-option \"xxx=aaa,yyy=bbb, ...\"] options for cs plugins\n"
                   "  [file]\n"
                   "  [&]\n"
                   "\n"
                   "  -x -displayFont -display are ignored !\n\n");
                 exit(1);
        } else if((!strcmp(argv[in],"-displayGeometry")) || (!strcmp(argv[in],"-dg"))) {
            // [-dg [xpos[xypos]][+xoffset[+yoffset]]
             in++;
             geometry = QString(argv[in]);
        } else if(!strcmp(argv[in], "-print")) {
             printscreen = true;
             minimize = true;
             resizing = false;
        } else if(!strcmp(argv[in], "-noResize")) {
            resizing = false;
        } else if(!strcmp(argv[in], "-httpconfig")) {
            HTTPCONFIGURATOR = true;
        } else if(!strcmp(argv[in], "-cs")) {
            in++;
            options.insert("defaultPlugin", QString(argv[in]));
        } else if ( strcmp (argv[in], "-option" ) == 0 ) {
            in++;
            printf("caQtDM -- option <%s>\n", argv[in]);
            createMap(options, QString(argv[in]));
        } else if (strncmp (argv[in], "-" , 1) == 0) {
            /* unknown application argument */
            printf("caQtDM -- Argument %d = [%s] is unknown!, possible -attach -macro -noMsg -noStyles -dg -x -print -httpconfig -noResize\n",in,argv[in]);
        } else {
            printf("caQtDM -- file = <%s>\n", argv[in]);
            fileName = QString(argv[in]);
            break;
        }
    }

    // must be always true for mobile plattforms
#ifdef MOBILE
     HTTPCONFIGURATOR = true;
#endif

    if(!nostyles) {
        s = new searchFile("stylesheet.qss");
        fileNameFound = s->findFile();
        if(fileNameFound.isNull()) {
            printf("caQtDM -- file <stylesheet.qss> could not be loaded, is 'CAQTDM_DISPLAY_PATH' <%s> defined?\n", qasc(s->displayPath()));
        } else {
            QFile file(fileNameFound);
            file.open(QFile::ReadOnly);
            QString StyleSheet = QLatin1String(file.readAll());
            printf("caQtDM -- file <stylesheet.qss> replaced the default stylesheet\n");
            app.setStyleSheet(StyleSheet);
            file.close();
        }
    }

    // load macro definitions from file (located in this directory or in the caQTDM_DISPLAY_PATH)
    if(macroFile.length() > 0) {
        s = new searchFile(macroFile);
        fileNameFound = s->findFile();
        if(fileNameFound.isNull()) {
            printf("caQtDM -- file <stylesheet.qss> could not be loaded, is 'CAQTDM_DISPLAY_PATH' <%s> defined?\n", qasc(s->displayPath()));
        } else {
            QFile file(fileNameFound);
            file.open(QFile::ReadOnly);
            macroString = QLatin1String(file.readAll());
            file.close();
        }
    }

#ifdef IO_OPTIMIZED_FOR_TABWIDGETS
    printf("caQtDM -- viewer will disable monitors for hidden pages of QTabWidgets, in case of problems\n");
    printf("          you may disable this by not defining IO_OPTIMIZED_FOR_TABWIDGETS in qtdefs.pri\n");
#else
    printf("caQtDM -- viewer will not disable monitors for hidden pages of QTabWidgets\n");
    printf("          you may enable this by defining IO_OPTIMIZED_FOR_TABWIDGETS in qtdefs.pri\n");
#endif

#ifndef CONFIGURATOR
    QString displayPath = (QString)  qgetenv("CAQTDM_URL_DISPLAY_PATH");
    if(displayPath.length() > 0) {
         printf("caQtDM -- files will be downloaded from <%s> when not locally found\n", qasc(displayPath));
    } else {
        printf("caQtDM -- files will not be downloaded from an url when not locally found, while CAQTDM_URL_DISPLAY_PATH is not defined\n");
    }
#endif

    FileOpenWindow window (0, fileName, macroString, attach, minimize, geometry, printscreen, resizing, options);
    window.setWindowIcon (QIcon(":/caQtDM.ico"));
    window.show();
    window.move(0,0);

    if (signal(SIGINT, unixSignalHandler) == SIG_ERR) {
        qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__);
    }
    if (signal(SIGTERM, unixSignalHandler) == SIG_ERR) {
        qFatal("ERR - %s(%d): An error occurred while setting a signal handler.\n", __FILE__,__LINE__);
    }

    QObject::connect(&app, SIGNAL(aboutToQuit()), &window, SLOT(doSomething()));

    return app.exec();
}
Ejemplo n.º 30
0
int main (int argc, const char * argv[]) {
    const char* filename;
    struct hashMap *hashTable;
    int tableSize = 10;
    clock_t timer;
    FILE *fileptr;
    /*
     Optional command line argument usage for filename
    if(argc == 2)
    //    filename = argv[1];
    //else*/
    filename = "input2.txt"; /*specify your input text file here*/

    printf("opening file: %s\n", filename);

    timer = clock(); /*Used to calculate efficiency*/
    hashTable = createMap(tableSize);	   /*Create a new hashMap*/
    fileptr = fopen(filename, "r");/*Open the file*/
    assert(fileptr != NULL);/*Check that the file opened properly*/
    int * value;/*Used to receive the value at the key*/


    for (char* word = getWord(fileptr); word != NULL; word = getWord(fileptr)) /*While the file hasn't reached the end*/
    {
        if (containsKey(hashTable, word) == 1) {
            /*If the key is already in the hash table, get the current value at that key and increment it by 1.
            Then reinsert that key with the new value*/
            value = atMap(hashTable, word);
            *value+=1;
            insertMap(hashTable, word, *value);
        }

        else
            insertMap(hashTable, word, 1); /*else insert the key with a value of 1*/
    }


    fclose(fileptr);/*close the file*/

    printMap(hashTable);/*Print the keys and values in the hashMap*/


    timer = clock() - timer;
    /*Print statements for testing purposes*/
    printf("\nconcordance ran in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
    printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
    printf("Table capacity = %d\n", capacity(hashTable));
    printf("Table load = %f\n", tableLoad(hashTable));


    /*Test the removeKey function*/
    printf("Deleting keys\n");
    removeKey(hashTable, "and");
    removeKey(hashTable, "me");
    removeKey(hashTable, "the");

    printf("Table emptyBuckets = %d\n", emptyBuckets(hashTable));
    printf("Table count = %d\n", size(hashTable));
    printf("Table capacity = %d\n", capacity(hashTable));
    printf("Table load = %f\n", tableLoad(hashTable));
    printMap(hashTable);

    /*Delete the hashMap*/
    deleteMap(hashTable);
    printf("\nDeleted the table\n");
    return 0;
}