Exemple #1
0
void Field::backgroundInit(FileReader & reader) {

	SceneNode * background = new SceneNode(&sceneRoot, "Background");
	sceneRoot.attachChild(background);
	std::string s;
	std::map <int, std::string> tilemap;
	s = reader.readLine();

	while (s != "?<>?") {

		if (!s.empty()) {

			int pos = s.find_first_of('?');
			std::string sSub = s.substr(0, pos);
			int key = atoi(sSub.c_str());
			int pos2 = s.find_first_of('?', pos + 1);
			sSub = s.substr(pos + 2, pos2 - (pos + 2));
			tilemap.insert(std::make_pair(key, sSub));
			std::string filepath = s.substr(pos2 + 2);
			ResourceHolder <sf::Texture> texture;
			texture.loadFromFile(filepath);
			textures.insert(std::make_pair(sSub, texture));
		}

		s = reader.readLine();

	}

	s = reader.readLine();
	int y = 0;

	while (s != "?<>?") {

		int x = 0;

		if (!s.empty()) {

			for (std::string::iterator it = s.begin(); it != s.end(); it++) {

				int nr = *it - '0';
				std::string id = tilemap.at(nr);

				backgroundTile * tile = new backgroundTile(id, textures.at(id).getResource(), sf::Vector2f(x, y), tileDimensions, background);
				background->attachChild(tile);
				x += tileDimensions.x;
			}
			fieldDimensions.x = x / tileDimensions.x;
			y += tileDimensions.y;

		}

		s = reader.readLine();

	}

	fieldDimensions.y = y / tileDimensions.y;
}
Exemple #2
0
//Initializ the spaceship
Spaceship::Spaceship(Type type, ResourceHolder<sf::Texture, Textures::ID>& textureHolder, SceneNode * foreground, unsigned int team) :
    type(type), //The type, to define the behavior
    sprite(textureHolder.get(spaceshipData[type].textureID)), //Initilize the sprite
    deltaV(spaceshipData[type].deltaV), //Initialize the deltaV
    maxV(spaceshipData[type].maxV), //Initialize the maxV
    foregroundLayer(foreground), //Initialize the foregorund pointer
    hp(spaceshipData[type].hp), //Initialize the hitpoints
    trajectory(new Trajectory()),
    id(maxId++)
{
    //attach the trajectory in the scene graph
    attachChild(trajectory);

    //Set the category
    category = Command::Spaceship;

    //Center the origin
    sf::FloatRect bounds = sprite.getLocalBounds();
    sprite.setOrigin(bounds.width/2.f, bounds.height/2.f);

    //Get the ID
    setTeam(team);

    //Add the weapons
    for(Weapon::WeaponPrototype prototype : spaceshipData[type].weapons)
    {
        Weapon * weapon = new Weapon(prototype.type, foreground, textureHolder);
        weapon->setRotation(prototype.rotation);
        weapon->setPosition(prototype.position);
        weapon->setTeam(team);
        attachChild(weapon);
    }
}
Exemple #3
0
Item::Item(RenderLayers layer, const std::string &textureId, 
        const ResourceHolder<sf::Texture> &textureHolder)
: SpriteNode(layer, textureHolder.get(textureId), true, false)
//, m_sprite{ textureHolder.get(textureId) }
, m_rotationPoint{ 0.f, 0.f }
{
    /*
    sf::FloatRect bounds = m_sprite.getLocalBounds();
    m_sprite.setOrigin(bounds.width / 2.f, bounds.height / 2.f);
    setWidth(bounds.width);
    setHeight(bounds.height);
    */
    
}
	//----------------------------------------------------------------------------------
	bool IResourcePtr::operator==(IResourcePtr& res) const{
		// check whenver given one is null
		if (res.isNull()){
			if (isNull())  return true;
			if (!isNull()) return false;
		}else{
			if (isNull())  return false;		
		}
		
		// check for holders
		ResourceHolder* A = getResourceHolder().get();
		ResourceHolder* B = res.getResourceHolder().get();
		if (A == B) return true;
		
		// At this point, both holders cannot be NULL
		if (A->getResource()->isResEmpty() || B->getResource()->isResEmpty()) return false;
		if (A->getResource() == B->getResource()) return true;
		
		return false;
	}
Exemple #5
0
int main()
{
	srand(time(0));
	ResourceHolder<sf::Font, Fonts::ID> fonts;
	ResourceHolder<sf::Texture, Textures::ID> textures;
	//ResourceHolder<sf::SoundBuffer, Sounds::ID> sounds;
	try
	{
		fonts.load(Fonts::WhiteRabbit, "Assets/whiterabbit.ttf");
		textures.load(Textures::Buttons, "Assets/buttons.png");
		textures.load(Textures::Timtam, "Assets/cmcquiz.png");
	}
	catch(std::runtime_error &e)
	{
		//would be better off using a log file for release code.
		return 1;
	}

	Window mainWindow(sf::Vector2f(800, 600), "Soft Eng Game");

	
	Button mainPlayButton(textures.get(Textures::Buttons), sf::Vector2f(250,  75), sf::Vector2f(25, 500),
		sf::IntRect(0, 0, 250, 75), sf::IntRect(0, 75, 250,  75));
	Button mainQuitButton(textures.get(Textures::Buttons), sf::Vector2f(250,  75), sf::Vector2f(525, 500),
		sf::IntRect(0, 150, 250, 75), sf::IntRect(0, 225, 250,  75));

	//QuizSelect stuff
	Button quizMenuContinue(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(250, 500),
		sf::IntRect(0, 300, 250, 75), sf::IntRect(0, 375, 250, 75));

	sf::Text selectQuiz("Select Quiz", fonts.get(Fonts::WhiteRabbit), 24);
	selectQuiz.setPosition(150, 150);
	sf::Text selectTime("Select Time", fonts.get(Fonts::WhiteRabbit), 24);
	selectTime.setPosition(500, 150);

	std::vector<QuestionButton> quizButtons;
	std::vector<std::string> quizFilenames;
	Util::getFilenamesInDir(quizFilenames, "Quizes");
	for(int i = 0; i < quizFilenames.size(); i++)
	{
		quizButtons.push_back(QuestionButton(quizFilenames[i], fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(200, 100), sf::Vector2f(100, 200 +( i * 100)), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));
	}

	std::vector<QuestionButton> timerButtons;
	timerButtons.push_back(QuestionButton("15", fonts.get(Fonts::WhiteRabbit), 48, sf::Vector2f(200, 100), sf::Vector2f(500, 200), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));
	timerButtons.push_back(QuestionButton("25", fonts.get(Fonts::WhiteRabbit), 48, sf::Vector2f(200, 100), sf::Vector2f(500, 300), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));
	timerButtons.push_back(QuestionButton("35", fonts.get(Fonts::WhiteRabbit), 48, sf::Vector2f(200, 100), sf::Vector2f(500, 400), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));

	//EndMenu Stuff
	Button endRetry(textures.get(Textures::Buttons), sf::Vector2f(250, 75), sf::Vector2f(25, 500),
		sf::IntRect(0, 450, 250, 75), sf::IntRect(0, 525, 250, 75)); 
	Button endQuit(textures.get(Textures::Buttons), sf::Vector2f(250,  75), sf::Vector2f(525, 500),
		sf::IntRect(0, 150, 250, 75), sf::IntRect(0, 225, 250,  75));

	sf::Vector2f endLogoPos(100, 0);

	std::vector<QuestionButton> endAnswers;
	endAnswers.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(640, 120), sf::Vector2f(80, 120), sf::Color(116, 40, 148, 255), sf::Color(116, 40, 148, 255)));
	endAnswers.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(640, 120), sf::Vector2f(80, 250), sf::Color::Green, sf::Color::Green));
	endAnswers.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 24, sf::Vector2f(640, 120), sf::Vector2f(80, 380), sf::Color::Red, sf::Color::Red));

	
	


	//MAIN MENU
	Menu startMenu(mainWindow.getWindow(), mainPlayButton, mainQuitButton, 10, 20, 15, 45, textures.get(Textures::Timtam),
		sf::Vector2f(75, 200));
		

	bool play = startMenu.run();
	
	
	while(play)
	{
		play = false;
		//quiz reader, gets a list of quizes from a dir and displays them.
		//pick one and return with that number.

		//pick a filename / quiz file.
		std::string quizFile;

		//QUIZ CHOICE AND TIMER MENU
		QuizMenu quizMenu(mainWindow.getWindow(), quizMenuContinue, selectQuiz, selectTime, quizButtons, timerButtons, 
			textures.get(Textures::Timtam), sf::Vector2f(100, 0));

		int timeToAns = 0;
		timeToAns = quizMenu.run(quizFile);
		//use the quiz at that index.

		if(timeToAns == 15 || timeToAns == 25 || timeToAns == 35)
		{
			//get the list of Q's
			Quiz quiz = Util::getQuiz("Quizes/" + quizFile, timeToAns);

			std::vector<QuestionButton> questionButtons;
			questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(640, 120), sf::Vector2f(80, 210), sf::Color(116, 40, 148, 255), sf::Color(116, 40, 148, 255)));
			questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(80, 340), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));
			questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(80, 470), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));
			questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(420, 340), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));
			questionButtons.push_back(QuestionButton("", fonts.get(Fonts::WhiteRabbit), 18, sf::Vector2f(300, 120), sf::Vector2f(420, 470), sf::Color(116, 40, 148, 255), sf::Color(181, 103, 214, 255)));

			std::vector<AnswerCombo> answers;


		
			Game game(&mainWindow.getWindow(), quiz, questionButtons, 
				sf::Sprite(textures.get(Textures::Timtam), 
				sf::IntRect(0, 0, textures.get(Textures::Timtam).getSize().x, textures.get(Textures::Timtam).getSize().y)),
				fonts.get(Fonts::WhiteRabbit),
				32,
				sf::Color::Black);
			answers = game.run();

			if(answers.size() > 0)
			{
				//takes in answers.
				EndMenu endMenu(&mainWindow.getWindow(), endRetry, endQuit, textures.get(Textures::Timtam), endLogoPos,
					answers, endAnswers);
				play = endMenu.run();
			}
		}
	}
	

	return 0;
}
bool RestImportHandler::createByKeyValueList () {
  size_t numCreated = 0;
  size_t numError = 0;
  size_t numEmpty = 0;
  
  vector<string> const& suffix = _request->suffix();

  if (suffix.size() != 0) {
    generateError(HttpResponse::BAD,
                  TRI_ERROR_HTTP_SUPERFLUOUS_SUFFICES,
                  "superfluous suffix, expecting " + DOCUMENT_IMPORT_PATH + "?collection=<identifier>");
    return false;
  }
  
  const bool waitForSync = extractWaitForSync();

  // extract the collection name
  bool found;
  const string& collection = _request->value("collection", found);

  if (! found || collection.empty()) {
    generateError(HttpResponse::BAD,
                  TRI_ERROR_ARANGO_COLLECTION_PARAMETER_MISSING,
                  "'collection' is missing, expecting " + DOCUMENT_IMPORT_PATH + "?collection=<identifier>");
    return false;
  }
 
  // read line number (optional) 
  const string& lineNumValue = _request->value("line", found);
  int64_t lineNumber = 0;
  if (found) {
    lineNumber = StringUtils::int64(lineNumValue);
  }

  
  size_t start = 0;
  string body(_request->body(), _request->bodySize());
  size_t next = body.find('\n', start);
  
  if (next == string::npos) {
    generateError(HttpResponse::BAD,
                  TRI_ERROR_HTTP_BAD_PARAMETER,
                  "no JSON list in second line found");
    return false;            
  }
 
  ResourceHolder holder;
  TRI_json_t* keys = 0;
    
  string line = body.substr(start, next);
  StringUtils::trimInPlace(line, "\r\n\t ");

  // get first line
  if (line != "") { 
    keys = parseJsonLine(line);
    if (! holder.registerJson(TRI_UNKNOWN_MEM_ZONE, keys)) {
      LOGGER_WARNING("no JSON data in first line");
      generateError(HttpResponse::BAD,
                    TRI_ERROR_HTTP_BAD_PARAMETER,
                    "no JSON string list in first line found");
      return false;      
    }
    
    if (keys->_type == TRI_JSON_LIST) {
      if (! checkKeys(keys)) {
        LOGGER_WARNING("no JSON string list in first line found");
        generateError(HttpResponse::BAD,
                      TRI_ERROR_HTTP_BAD_PARAMETER,
                      "no JSON string list in first line found");
        return false;        
      }
      start = next + 1;
    }
    else {
      LOGGER_WARNING("no JSON string list in first line found");
      generateError(HttpResponse::BAD,
                    TRI_ERROR_HTTP_BAD_PARAMETER,
                    "no JSON string list in first line found");
      return false;      
    }        
  }
  else {
    LOGGER_WARNING("no JSON string list in first line found");
    generateError(HttpResponse::BAD,
                  TRI_ERROR_HTTP_BAD_PARAMETER,
                  "no JSON string list in first line found");
    return false;      
  }        
  
  if (! checkCreateCollection(collection, TRI_COL_TYPE_DOCUMENT)) {
    return false;
  }

  
  // find and load collection given by name or identifier
  SingleCollectionWriteTransaction<StandaloneTransaction<RestTransactionContext>, UINT64_MAX> trx(_vocbase, _resolver, collection);
  
  // .............................................................................
  // inside write transaction
  // .............................................................................
 
  int res = trx.begin();
  if (res != TRI_ERROR_NO_ERROR) {
    generateTransactionError(collection, res);
    return false;
  }
  
  TRI_primary_collection_t* primary = trx.primaryCollection();
  const TRI_voc_cid_t cid = trx.cid();
  const bool isEdgeCollection = (primary->base._info._type == TRI_COL_TYPE_EDGE);

  trx.lockWrite();
      
  // .............................................................................
  // inside write transaction
  // .............................................................................

  while (next != string::npos && start < body.length()) {
    lineNumber++;

    next = body.find('\n', start);

    if (next == string::npos) {
      line = body.substr(start);
    }
    else {
      line = body.substr(start, next - start);
      start = next + 1;      
    }
    
    StringUtils::trimInPlace(line, "\r\n\t ");
    if (line.length() == 0) {
      ++numEmpty;
      continue;
    }
    
    TRI_json_t* values = parseJsonLine(line);

    if (values) {
      // got a json document or list
      TRI_json_t* json;
      
      // build the json object from the list
      json = createJsonObject(keys, values, line);
      TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, values);
        
      if (json == 0) {
        ++numError;          
        continue;
      }

      // now save the document
      TRI_doc_mptr_t document;

      if (isEdgeCollection) {
        const char* from = extractJsonStringValue(json, "_from");

        if (from == 0) {
          LOGGER_WARNING("missing '_from' attribute at line " << lineNumber);
          TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);      
          ++numError;
          continue;
        }

        const char* to = extractJsonStringValue(json, "_to");
        if (to == 0) {
          LOGGER_WARNING("missing '_to' attribute at line " << lineNumber);
          TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);      
          ++numError;
          continue;
        }

        TRI_document_edge_t edge;
  
        edge._fromCid = cid;
        edge._toCid = cid;
        edge._fromKey = 0;
        edge._toKey = 0;
  
        int res1 = parseDocumentId(from, edge._fromCid, edge._fromKey);
        int res2 = parseDocumentId(to, edge._toCid, edge._toKey);

        if (res1 == TRI_ERROR_NO_ERROR && res2 == TRI_ERROR_NO_ERROR) {
          res = trx.createEdge(&document, json, waitForSync, &edge, false);
        }

        if (edge._fromKey != 0) {
          TRI_Free(TRI_CORE_MEM_ZONE, edge._fromKey);
        }
        if (edge._toKey != 0) {
          TRI_Free(TRI_CORE_MEM_ZONE, edge._toKey);
        }
      }
      else {
        // do not acquire an extra lock
        res = trx.createDocument(&document, json, waitForSync, false);
      }


      if (res == TRI_ERROR_NO_ERROR) {
        ++numCreated;
      }
      else {
        LOGGER_WARNING("creating document failed with error: " << TRI_errno_string(res));
        logDocument(json);
        ++numError;
      }
      
      TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);      
    }
    else {
      LOGGER_WARNING("no valid JSON data in line: " << line);            
      ++numError;
    }
            
  }
  
  // we'll always commit, even if previous errors occurred
  res = trx.commit();
  
  // .............................................................................
  // outside write transaction
  // .............................................................................
  
  if (res != TRI_ERROR_NO_ERROR) {
    generateTransactionError(collection, res);
  }
  else {
    // generate result
    generateDocumentsCreated(numCreated, numError, numEmpty);
  }
  
  return true;
}
bool RestImportHandler::createByDocumentsList () {
  size_t numCreated = 0;
  size_t numError = 0;
  
  vector<string> const& suffix = _request->suffix();

  if (suffix.size() != 0) {
    generateError(HttpResponse::BAD,
                  TRI_ERROR_HTTP_SUPERFLUOUS_SUFFICES,
                  "superfluous suffix, expecting " + DOCUMENT_IMPORT_PATH + "?type=array&collection=<identifier>");
    return false;
  }
  
  const bool waitForSync = extractWaitForSync();

  // extract the collection name
  bool found;
  const string& collection = _request->value("collection", found);

  if (! found || collection.empty()) {
    generateError(HttpResponse::BAD,
                  TRI_ERROR_ARANGO_COLLECTION_PARAMETER_MISSING,
                  "'collection' is missing, expecting " + DOCUMENT_IMPORT_PATH + "?collection=<identifier>");
    return false;
  }

  ResourceHolder holder;
  
  char* errmsg = 0;
  TRI_json_t* documents = TRI_Json2String(TRI_UNKNOWN_MEM_ZONE, _request->body(), &errmsg);

  if (! holder.registerJson(TRI_UNKNOWN_MEM_ZONE, documents)) {
    if (errmsg == 0) {
      generateError(HttpResponse::BAD, 
                    TRI_ERROR_HTTP_CORRUPTED_JSON,
                    "cannot parse json object");
    }
    else {
      generateError(HttpResponse::BAD, 
                    TRI_ERROR_HTTP_CORRUPTED_JSON,
                    errmsg);

      TRI_FreeString(TRI_CORE_MEM_ZONE, errmsg);
    }
    return false;
  }

  if (documents->_type != TRI_JSON_LIST) {
    generateError(HttpResponse::BAD,
                  TRI_ERROR_HTTP_BAD_PARAMETER,
                  "expecting a JSON array in the request");
    return false;
  }
  
  if (! checkCreateCollection(collection, TRI_COL_TYPE_DOCUMENT)) {
    return false;
  }
  
  // find and load collection given by name or identifier
  SingleCollectionWriteTransaction<StandaloneTransaction<RestTransactionContext>, UINT64_MAX> trx(_vocbase, _resolver, collection);
  
  // .............................................................................
  // inside write transaction
  // .............................................................................
 
  int res = trx.begin();
  if (res != TRI_ERROR_NO_ERROR) {
    generateTransactionError(collection, res);
    return false;
  }
  
  TRI_primary_collection_t* primary = trx.primaryCollection();
  const TRI_voc_cid_t cid = trx.cid();
  const bool isEdgeCollection = (primary->base._info._type == TRI_COL_TYPE_EDGE);
  
  trx.lockWrite();

  for (size_t i = 0; i < documents->_value._objects._length; ++i) {
    TRI_json_t* values = (TRI_json_t*) TRI_AtVector(&documents->_value._objects, i);

    if (values == 0 || values->_type != TRI_JSON_ARRAY) {
      LOGGER_WARNING("invalid JSON type (expecting array) at position " << (i + 1));
      ++numError;
    }
    else {
      // now save the document
      TRI_doc_mptr_t document;
  
      if (isEdgeCollection) {
        const char* from = extractJsonStringValue(values, "_from");

        if (from == 0) {
          LOGGER_WARNING("missing '_from' attribute at position " << (i + 1));
          ++numError;
          continue;
        }

        const char* to = extractJsonStringValue(values, "_to");
        if (to == 0) {
          LOGGER_WARNING("missing '_to' attribute at position " << (i + 1));
          ++numError;
          continue;
        }

        TRI_document_edge_t edge;
  
        edge._fromCid = cid;
        edge._toCid = cid;
        edge._fromKey = 0;
        edge._toKey = 0;
  
        int res1 = parseDocumentId(from, edge._fromCid, edge._fromKey);
        int res2 = parseDocumentId(to, edge._toCid, edge._toKey);

        if (res1 == TRI_ERROR_NO_ERROR && res2 == TRI_ERROR_NO_ERROR) {
          res = trx.createEdge(&document, values, waitForSync, &edge, false);
        }

        if (edge._fromKey != 0) {
          TRI_Free(TRI_CORE_MEM_ZONE, edge._fromKey);
        }
        if (edge._toKey != 0) {
          TRI_Free(TRI_CORE_MEM_ZONE, edge._toKey);
        }
      }
      else {
        // do not acquire an extra lock
        res = trx.createDocument(&document, values, waitForSync, false);
      }


      if (res == TRI_ERROR_NO_ERROR) {
        ++numCreated;
      }
      else {
        LOGGER_WARNING("creating document failed with error: " << TRI_errno_string(res));
        logDocument(values);
        ++numError;
      }
    }
  }

  // this will commit, even if previous errors occurred
  res = trx.commit();

  // .............................................................................
  // outside write transaction
  // .............................................................................

  if (res != TRI_ERROR_NO_ERROR) {
    generateTransactionError(collection, res);
  }
  else {
    // generate result
    size_t numEmpty = 0;
    generateDocumentsCreated(numCreated, numError, numEmpty);
  }
  
  return true;
}