Esempio n. 1
0
Player::Player(int playerNum, const vec3f& rot, Color col)
    : rot(rot), color(col), playerNum(playerNum) {
	Map* map = (Map*)getGame()->getObjectByName("map");
	pos = vec3f(map->getStartingPos(col).x,map->getStartingPos(col).y-0.6,0);
	fullTransform = glm::translate(mat4f(1.0f),pos);
	this->setName("player"+char('0'+playerNum));
	model.mesh = Meshes.get("brushidle0");
	model.program = Programs.get("deferredModel");
	renderer = (DeferredContainer*)getGame()->getObjectByName("deferred");

	modelAabb = model.mesh->getBoundingBox();
	modelOffset = glm::translate(mat4f(1.0f), -modelAabb.getCenter()+vec3f(0,0,0.5));

	velocity = vec3f(0.0f, JUMP_IMPULSE*0.65f, 0.0f);

	colliding = false;

	totalForce = vec3f(0.0f);
	animState = Player::JUMP;

	animCount = 0.0f;
	animTime = randomFloat(0.1f, 0.4f);

	anim = "idle";
	animIter = 0;

	scale = vec3f(0.30f/modelAabb.getRadius());

	emitter = new LightParticleEmitter(vec3f(1),color-1);
	emitter->addTo(this);
}
Esempio n. 2
0
void SuspendedUserInterface::renderHeader() const
{
   if(getGame()->isSuspended())
   {
      mGL->glColor(Colors::white);
      RenderUtils::drawCenteredString(vertMargin, MENU_TITLE_SIZE, "-- GAME SUSPENDED -- ");
   }
   else
   {
      mGL->glColor(Colors::red);
      RenderUtils::drawCenteredString(vertMargin, MENU_TITLE_SIZE, "!! GAME RESTARTED !! ");
   }

   string subtitle = "Not currently connected to any game server";

   if(getGame()->getConnectionToServer())
   {
      string name = getGame()->getConnectionToServer()->getServerName();
      if(name == "")
         subtitle = "Connected to game server with no name";
      else
         subtitle = "Connected to game server \"" + name + "\"";
   }

   mGL->glColor(Colors::green);
   RenderUtils::drawCenteredString(vertMargin + MENU_TITLE_SIZE + TITLE_SUBTITLE_GAP, MENU_SUBTITLE_SIZE, subtitle.c_str());
}
bool IterativeBestResponseVoter::makeMove() {
    if (getGame()==NULL) {
        return false;
    }

    currentBestWinner=getGame()->getWinner();
    bestPrefs.clear();
    
    PrefList tempPref;
    makeEveryOptionMove(candidateNumber, tempPref);
    int minDistance=candidateNumber*candidateNumber;
    vector<PrefList> winners;
    winners.clear();
    if (bestPrefs.size()>1) {
        for (long i=bestPrefs.size()-1; i>=0; i--) {
            if (truePrefs.distanceFromPref(bestPrefs[i])<minDistance) {
                minDistance=truePrefs.distanceFromPref(bestPrefs[i]);
            }
        }
        for (long i=bestPrefs.size()-1; i>=0; i--) {
            if (truePrefs.distanceFromPref(bestPrefs[i])==minDistance) {
                winners.push_back(bestPrefs[i]);
            }
        }
    } else {
        winners.push_back(bestPrefs[0]);
    }
    
    if (getGame()->getWinner()!=currentBestWinner) {
        publicPrefs=winners[0];
        return true;
    }
    return false;
}
Esempio n. 4
0
bool NexusZone::collide(BfObject *hitObject)
{
    if(isGhost())
        return false;

    // From here on out, runs on server only

    if( ! (isShipType(hitObject->getObjectTypeNumber())) )
        return false;

    Ship *theShip = static_cast<Ship *>(hitObject);

    if(theShip->mHasExploded)                             // Ignore collisions with exploded ships
        return false;

    GameType *gameType = getGame()->getGameType();
    NexusGameType *nexusGameType = NULL;

    if(gameType && gameType->getGameTypeId() == NexusGame)
        nexusGameType = static_cast<NexusGameType *>(getGame()->getGameType());

    if(nexusGameType && nexusGameType->isNexusOpen())      // Is the nexus open?
        nexusGameType->shipTouchNexus(theShip, this);

    return false;
}
Esempio n. 5
0
void testEnemyMovement()
{
    Enemy e = createTestEnemy();
    
    sput_fail_unless(distanceToEndOfPath(getNumberOfEnemies()) == e->enemyPath->pathLength, "Valid: Enemy has the correct number of steps to the end of its path");
    
    
    int enemyOriginX = e->x;
    int enemyOriginY = e->y;
    for(int i = 0; i < 200; i++) {
        moveEnemy(getNumberOfEnemies());
    }
    sput_fail_unless(e->x != enemyOriginX, "Valid: Enemy has changed X coordinate after 200 moves");
    sput_fail_unless(e->y != enemyOriginY, "Valid: Enemy has changed Y coordinate after 200 moves");
    sput_fail_unless(distanceToEndOfPath(getNumberOfEnemies()) == e->enemyPath->pathLength-(200*e->speed), "Valid: Enemy has the correct number of steps to the end of its path after 200 moves");
    
    int startingHealth = getHealth(getGame(NULL));
    int howFarToGo = distanceToEndOfPath(getNumberOfEnemies());
    int howManyMovesToEnd = (howFarToGo/e->speed)+1;
    for(int i = 0; i < howManyMovesToEnd; i++) {
        moveEnemy(getNumberOfEnemies());
    }
    
    
    sput_fail_unless(isDead(getNumberOfEnemies()), "Valid: Enemy has died after reaching end of path");
    sput_fail_unless(getHealth(getGame(NULL)) == startingHealth-e->damage, "Valid: Enemy has damaged health by correct amount at end of path");
    
}
Esempio n. 6
0
// Private helper function
void NexusFlagItem::dropFlags(U32 flags)
{
    if(!mMount.isValid())
        return;

    // This is server only, folks -- avoids problem with adding flag on client when it doesn't really exist on server
    if(isGhost())
        return;

    static const U32 MAX_DROP_FLAGS = 200;    // If we drop too many flags, things just get bogged down.  This limit is rarely hit.

    if(flags > MAX_DROP_FLAGS)
    {
        for(U32 i = MAX_DROP_FLAGS; i > 0; i--)
        {
            // By dividing and subtracting, it works by using integer divide, subtracting from "flags" left,
            // and the last loop is (i == 1), dropping exact amount using only limited FlagItems
            U32 flagValue = flags / i;

            getGame()->releaseFlag(mMount->getActualPos(), mMount->getActualVel(), flagValue);

            flags -= flagValue;
        }
    }
    else     // Normal situation
        for(U32 i = 0; i < flags; i++)
            getGame()->releaseFlag(mMount->getActualPos(), mMount->getActualVel());

    changeFlagCount(0);
}
Esempio n. 7
0
/**
 * This method determines whether a char is a member of the Game associated with this
 * GameAttempt. This is a core Hangman game functionality.
 * guess a char representing the player's guess
 * returns a bool indicating whether or not the guess was correct
 */
bool GameAttempt::guessLetter(char guess) {
   
   bool guessSuccess = false;
   
   if(!haveGuessed(guess)) {                                      //If this letter has not already been guessed
      setNumLetterGuesses(getNumLetterGuesses()+1);               //Increment number of letter guesses
      guesses.add(guess);                                         //Add letter to list of guessed chars
      if(getGame().getCharsInPhrase().contains(toupper(guess)) || //If this char is a correct guess
         getGame().getCharsInPhrase().contains(tolower(guess))){  
         guessSuccess = true;                                     // Mark this guess as correct
      }
      else {                                                      //New guess, but an incorrect one
         vector<char> newAlreadyGuessed = getAlreadyGuessed();
         newAlreadyGuessed.push_back(guess);
         sort(newAlreadyGuessed.begin(), newAlreadyGuessed.end());
         setAlreadyGuessed(newAlreadyGuessed);
         setNumWrongLetterGuesses(getNumWrongLetterGuesses() + 1);
      }
   }
   else {                                                         //Letter has been guessed. 
      if(getGame().getCharsInPhrase().contains(toupper(guess)) || //If this char is a correct guess
         getGame().getCharsInPhrase().contains(tolower(guess))){  
         guessSuccess = true;                                     // Mark this guess as correct
      }
   }
   
   return guessSuccess;                                        //Return success of the guess
}
// By rebuilding everything every tick, menus can be dynamically updated
void PlayerMenuUserInterface::idle(U32 timeDelta)
{
   clearMenuItems();

   GameConnection *conn = getGame()->getConnectionToServer();
   if(!conn)
      return;

   char c[] = "A";      // Dummy shortcut key
   for(S32 i = 0; i < getGame()->getClientCount(); i++)
   {
      ClientInfo *clientInfo = ((Game *)getGame())->getClientInfo(i);      // Lame!

      strncpy(c, clientInfo->getName().getString(), 1);        // Grab first char of name for a shortcut key

      // Will be used to show admin/player/robot prefix on menu
      PlayerType pt = clientInfo->isRobot() ? PlayerTypeRobot : (clientInfo->isAdmin() ? PlayerTypeAdmin : PlayerTypePlayer);    

      PlayerMenuItem *newItem = new PlayerMenuItem(i, clientInfo->getName().getString(), playerSelectedCallback, 
                                                   InputCodeManager::stringToInputCode(c), pt);
      newItem->setUnselectedColor(getGame()->getTeamColor(clientInfo->getTeamIndex()));

      addMenuItem(newItem);
   }

   sortMenuItems();

   if(action == PlayerActionKick)
      mMenuTitle = "CHOOSE PLAYER TO KICK";
   else if(action == PlayerActionChangeTeam)
      mMenuTitle = "CHOOSE WHOSE TEAM TO CHANGE";
   else
      TNLAssert(false, "Unknown action!");
}
Esempio n. 9
0
void LootState::selectGame(std::string preferredGame) {
  if (preferredGame.empty()) {
      // Get preferred game from settings.
    if (getGame() != "auto")
      preferredGame = getGame();
    else if (getLastGame() != "auto")
      preferredGame = getLastGame();
  }

  // Get iterator to preferred game.
  currentGame_ = find_if(begin(games_), end(games_), [&](Game& game) {
    return (preferredGame.empty() || preferredGame == game.FolderName()) && game.IsInstalled();
  });
  // If the preferred game cannot be found, get the first installed game.
  if (currentGame_ == end(games_)) {
    currentGame_ = find_if(begin(games_), end(games_), [](Game& game) {
      return game.IsInstalled();
    });
  }
  // If no game can be selected, throw an exception.
  if (currentGame_ == end(games_)) {
    BOOST_LOG_TRIVIAL(error) << "None of the supported games were detected.";
    throw GameDetectionError(translate("None of the supported games were detected."));
  }
}
Esempio n. 10
0
void MapHud::on_player_range_tile(int x, int y, Player * player) {
	int height_map = getGame()->get_display_layer()->get_map_height();
	if(player==getGame()->get_main_player()) {
		_texture->setPixelAt(CCPointMake(x,height_map-y-1), getGame()->get_display_layer()->get_sprite_map()[getGame()->get_display_layer()->get_tile_layer()->get_map_tile_matrix()[y][x]->get_id()].colorMap);
	}
	_texture->apply();
}
void BattleResultClientCommand::execute() {
    
    ReferenceCountPtr<Mapa> map = this->getGame()->getMapa();
    ReferenceCountPtr<Pais> paisAtacante = map->obtenerPais( getAttackerLand() );
    ReferenceCountPtr<Pais> paisDefensor = map->obtenerPais( getDefenderLand() );

    ReferenceCountPtr<Player> playerAtacante = getGame()->getPlayer( getAttackercolor() );
    ReferenceCountPtr<Player> playerDefensor = getGame()->getPlayer( getDefenderColor() );

    paisAtacante->removeArmies(getAttackerResult());
    paisDefensor->removeArmies(getDefenderResult());

    if ( paisDefensor->getArmyCount() == 0  ){
        std::string defLand = getDefenderLand();
        playerDefensor->removeConqueredLand(defLand);

        playerAtacante->addConqueredLand(defLand );
        paisAtacante->removeArmies( getConquest() );
        paisDefensor->addArmies(  getConquest() );
        std::vector<std::string> vecContinentes = getGame()->conformContinent(playerAtacante->getConqueredLandList() );
        for ( unsigned int i=0; i<vecContinentes.size();i++){
            //si playerAtacante no es dueño todavia de uno de los continentes conquistados segun vecContinentes
            if ( !playerAtacante->continentOwner( vecContinentes[i] ) )
                //seteo al continente actual como conquistado por el player atacante
                playerAtacante->addConqueredContinent(vecContinentes[i] );
        }
    }
}
void testStartNextWave()	{

    setCurrWaveNum(getGame(NULL)->currWaveNo+1);
    increaseEnemyNumbersThisWave(10);
    getGame(NULL)->deathCount = 0;
    sput_fail_unless(startNextWave() == 0, "Invalid: 10 enemies have not registered as dead yet");
    getGame(NULL)->deathCount = 10;
    sput_fail_unless(startNextWave() == 1, "Valid: 10 enemies have registered as dead");
}
Esempio n. 13
0
void HealthBar::init() {
	//load the texture of the pip. Pip is a really tiny little bar.
	pipTexture_ = getGame()->driver->getTexture("../assets/Textures/Stations/HealthPip32.png");

	//make the pip background invisible
	getGame()->driver->makeColorKeyTexture(pipTexture_, irr::core::position2d<s32>(0, 0));

	Component::init();
}
Esempio n. 14
0
void ChatUserInterface::renderHeader() const
{
   // Draw title, subtitle, and footer
   RenderUtils::drawCenteredString_fixed(vertMargin + MENU_TITLE_SIZE, MENU_TITLE_SIZE, Colors::green, "LOBBY CHAT");

   string subtitle = getSubtitle(getGame());

   S32 ypos = vertMargin + MENU_TITLE_SIZE + TITLE_SUBTITLE_GAP + MENU_SUBTITLE_SIZE;
   RenderUtils::drawCenteredString_fixed(ypos, MENU_SUBTITLE_SIZE, getGame()->getConnectionToServer() ? Colors::yellow : Colors::red, subtitle.c_str());
}
Esempio n. 15
0
DialogState::~DialogState()
{
    // Unpause the game when we are done with the dialogue
    getGame()->getSceneManager()->setPaused(false);
    getGame()->getPhysicsManager()->setPaused(false);

    mPages.clear();
    delete mDialogBox;
    delete mGameBackground;
}
Esempio n. 16
0
void DialogState::initialize()
{
    mDialogBox = new sf::Sprite(*getGame()->getResourceManager()->getTexture("Content/Textures/dialogbox.png"));
    mGameBackground = new sf::Sprite(*getGame()->getResourceManager()->getTexture("Content/Textures/background.png"));

    mDialogBox->move(sf::Vector2f(0,640-150));

    getGame()->getSceneManager()->setPaused(true);
    getGame()->getPhysicsManager()->setPaused(true);
}
Esempio n. 17
0
void Player::update(float deltaTime) {
    //take input
    if(!Debugger::isShown()) processKeys(deltaTime);

    //transform coordinates for camera and other children
    float p = getGame()->getTimeSinceFixed()/getGame()->getFixedUpdateTime();
    transform = glm::translate(mat4f(1.0), lastPos*(1-p) + pos*p);

    //trace view
    traceView();
}
int startNextWave()	{
    if(getTotalCurrentWaveEnemies() == getDeathCnt())	{
        if(getWave(getGame(NULL))  < getTotalWaveNo())	{
            resetEnemyCounts();
            setCurrWaveNum(getGame(NULL)->currWaveNo+1);
        } else {
            //printf("you have won the level\n");
        }
        return 1;
    }
    return 0;
}
Esempio n. 19
0
void SuspendedUserInterface::renderHeader() const
{
   S32 ypos = vertMargin + MENU_TITLE_SIZE;

   if(getGame()->isSuspended())
      RenderUtils::drawCenteredString_fixed(ypos, MENU_TITLE_SIZE, Colors::white, "-- GAME SUSPENDED -- ");
   
   else
      RenderUtils::drawCenteredString_fixed(ypos, MENU_TITLE_SIZE, Colors::red, "!! GAME RESTARTED !! ");

   string subtitle = getSubtitle(getGame());

   RenderUtils::drawCenteredString_fixed(ypos + MENU_SUBTITLE_SIZE + TITLE_SUBTITLE_GAP, MENU_SUBTITLE_SIZE, Colors::green, subtitle.c_str());
}
Esempio n. 20
0
Mesh* Base::CopyMesh(renderableType mT, const Color& c)
{
    if(mT > sse || mT == none)
        return NULL;

    Renderable* temp = getGame()->getRenderable(mT);
    if(temp == NULL)
        return NULL;

    if(typeid(*temp) == typeid(Mesh))
    {
        //copy temp to m
        Mesh* m = new Mesh( *((Mesh*)(temp)) );

        //mesh->polys[i].length denotes the number of vertices in the polygon
        for(unsigned int i = 0; i < m->polyNum; ++i)
        {
            for(unsigned int index = 0; index < m->polys[i].length; ++index)
                m->polys[i].vertices[index].COLOR = c.returnD3DCOLOR();	//set color
        }
        //load to video memory
        LoadToVRAM(m);

        if(m->mountNum > 0)
        {
            Game* g = getGame();
            m->actualMounts = new Base*[m->mountNum];
            for(unsigned int i = 0; i < m->mountNum; ++i)
            {
                if(m->mountNames[i] == "thruster")
                {
                    Base* t = new Thruster(getGame()->getNextIndex(), owner, none, m->mountLocs[i], dir, this, false, true);	//none is used because the default mesh should point to this for the Render function to be called
                    //this->texture is used instead to store the actual drawing
                    g->insertObject(t);
                    m->actualMounts[i] = t;
                }
                else
                    m->actualMounts[i] = NULL;
                //other mounts are handled in the ship class (why?)(so I can control ROF's)
            }
        }
        else
            m->actualMounts = NULL;

        //back to renderable pointer
        return m;
    }
    else
        return NULL;
}
void LevelMenuSelectUserInterface::onActivate()
{
   Parent::onActivate();

   // Replace with a getLevelCount() method on Game?
   ClientGame *game = getGame();
   GameConnection *gc = game->getConnectionToServer();

   if(gc == NULL || gc->mLevelInfos.size() == 0)
      return;

   mMenuTitle = "CHOOSE LEVEL [" + mCategory + "]";
   mMenuDisplayItems.clear();

   char c[2];
   c[1] = 0;   // null termination

   if(mCategory == UPLOAD_LEVELS)
   {
      // Get all the playable levels in levelDir
      mMenuDisplayItems = mGameSettings->getLevelList();

      for(S32 i = 0; i < mMenuDisplayItems.size(); i++)
      {
         c[0] = mMenuDisplayItems[i][0];
         addMenuItem(new MenuItem(i | UPLOAD_LEVELS_BIT, 
                                  mMenuDisplayItems[i], 
                                  processLevelSelectionCallback, 
                                  "", 
                                  InputCodeManager::stringToInputCode(c)));
      }
   }
 
   for(S32 i = 0; i < gc->mLevelInfos.size(); i++)
   {
      if(gc->mLevelInfos[i].mLevelName == "")   // Skip levels with blank names --> but all should have names now!
         continue;

      if(strcmp(gc->mLevelInfos[i].getLevelTypeName(), mCategory.c_str()) == 0 || mCategory == ALL_LEVELS)
      {
         const char *levelName = gc->mLevelInfos[i].mLevelName.getString();
         c[0] = levelName[0];
         addMenuItem(new MenuItem(i, levelName, processLevelSelectionCallback, "", InputCodeManager::stringToInputCode(c)));
      }
   }

   if(!getGame()->isUsingPlaylist())
      sortMenuItems();
}
Esempio n. 22
0
void NexusZone::render() const
{
#ifndef ZAP_DEDICATED
    GameType *gameType = getGame() ? getGame()->getGameType() : NULL;
    NexusGameType *nexusGameType = NULL;

    if(gameType && gameType->getGameTypeId() == NexusGame)
        nexusGameType = static_cast<NexusGameType *>(gameType);

    bool isOpen = nexusGameType && nexusGameType->isNexusOpen();
    F32 glowFraction = gameType ? gameType->mZoneGlowTimer.getFraction() : 0;

    GameObjectRender::renderNexus(getOutline(), getFill(), getCentroid(), getLabelAngle(), isOpen, glowFraction);
#endif
}
Esempio n. 23
0
void DlgMatchResult::fillControlsFromExistingMatchResult()
{
  if (ma.getState() != STAT_MA_FINISHED) return;
  auto result = ma.getScore();
  if (result == nullptr) return;

  ui->game1Widget->setScore(*(result->getGame(0)));
  ui->game2Widget->setScore(*(result->getGame(1)));
  if (result->getNumGames() > 2)
  {
    ui->game3Widget->setScore(*(result->getGame(2)));
  }

  updateControls();
}
Esempio n. 24
0
GlowingShapeComponent::GlowingShapeComponent(GameObject *object, std::string name, std::string shapeFile, sf::Vector2f scale, bool castShadow, bool lit) :
    ShapeComponent(object, name, shapeFile, castShadow, lit)
{
    // Our blur shader
    sf::Shader blurShader;

    // Load the shader
    if (!blurShader.loadFromFile("Content/Shaders/blur.frag", sf::Shader::Fragment))
    {
        // TODO: Some kind of error message
    }
    blurShader.setParameter("texture", sf::Shader::CurrentTexture);
    blurShader.setParameter("blur_radius", 5.0f/mShape->getLocalBounds().width);

    // Render the shape to a texture
    sf::RenderTexture render;
    render.create(mShape->getLocalBounds().width + 128, mShape->getLocalBounds().height + 128);

    mShape->setPosition(sf::Vector2f(mShape->getLocalBounds().width/2 + 64, mShape->getLocalBounds().height/2 + 64)+
                        (mCenter*getGame()->getRenderingManager()->getPTU()));
    mShape->setScale(scale);
    render.draw(*mShape); //draw the shape
    render.display();

    //render that texture to another texture using a shader
    sf::Texture texture(render.getTexture());
    //sf::Texture texture(*ResourceManager()->getTexture("lesserbeing.png"));
    sf::Sprite tmpSprite(texture);

    sf::RenderStates renderStates = sf::RenderStates::Default;
    renderStates.shader = &blurShader;
    render.clear(sf::Color(0.0,0.0,0.0,0.0));
    render.draw(tmpSprite, renderStates);
    render.display();

    // Create an emissive light
    mEmissiveLight = new ltbl::EmissiveLight();

    mTexture = new sf::Texture(render.getTexture());
    mEmissiveLight->SetTexture(mTexture);

    mEmissiveLight->m_intensity = 1.1f;

    getGame()->getRenderingManager()->getLightSystem()->AddEmissiveLight(mEmissiveLight);

    mAlpha = 1.1f;
    mAlphaDir = -1.f;
}
Esempio n. 25
0
void NexusFlagItem::dismount(DismountMode dismountMode)
{
    if(isGhost())      // Server only
        return;
    if(getDatabase() == NULL)  // must be in database, switching levels makes database NULL
        return;

    if(dismountMode == DISMOUNT_MOUNT_WAS_KILLED)
    {
        // Should getting shot up count as a flag drop event for statistics purposes?
        if(mMount && mMount->getClientInfo())
            mMount->getClientInfo()->getStatistics()->mFlagDrop += mFlagCount + 1;

        dropFlags(mFlagCount + 1);    // Drop at least one flag plus as many as the ship carries

        // Now delete the flag itself
        removeFromDatabase(false);
        deleteObject();
    }
    else
    {
        GameType *gameType = getGame()->getGameType();
        if(!gameType)        // Crashed here once, don't know why, so I added the check
            return;

        gameType->itemDropped(mMount, this, dismountMode); // Sends messages; no flags actually dropped here; server only method
        dropFlags(mFlagCount);                             // Only dropping the flags we're carrying, not the "extra" one that comes when we die
    }
}
Esempio n. 26
0
// Load the resources for the scene from a resource loader
void MainMenu::load(const ResourceLoader& resourceLoader)
{
	Color normalColor(100, 100, 0), selectedColor(255, 255, 0);
	Font menuFont = resourceLoader.loadFont("mainMenu.ttf", 42);
	
	Game* game = getGame();

	_mainMenu.addElement(
		menuFont,
		"Play",
		normalColor,
		selectedColor);

	_mainMenu.addElement(
		menuFont,
		"Settings",
		normalColor,
		selectedColor);

	_mainMenu.addElement(
		menuFont,
		"Quit",
		normalColor,
		selectedColor,
		[&game](){
			game->quit();
		});
}
Esempio n. 27
0
void EnemyGrunt::render(sf::RenderTarget &rt) {
	sf::Sprite shadowSprite;
	shadowSprite.setTexture(_assets->_gruntShadow);

	shadowSprite.setOrigin(_assets->_gruntShadow.getSize().x * 0.5f, _assets->_gruntShadow.getSize().y * 0.5f);

	shadowSprite.setPosition(_position);

	rt.draw(shadowSprite);

	sf::Sprite footSprite;
	footSprite.setTexture(_assets->_gruntFoot);

	footSprite.setOrigin(2.0f, 2.5f);

	sf::Vector2f perpendicular(std::cos(_rotation * ltbl::_pi / 180.0f), std::sin(_rotation * ltbl::_pi / 180.0f));
	sf::Vector2f forward(perpendicular.y, -perpendicular.x);

	const float feetSpread = 1.5f;
	const float feetStepDistance = 2.5f;

	float leftFootOffset = std::sin(2.0f * ltbl::_pi * _footCycle);

	footSprite.setRotation(_rotation);

	footSprite.setPosition(_position - perpendicular * feetSpread + forward * feetStepDistance * leftFootOffset - forward * 1.0f);

	rt.draw(footSprite);

	footSprite.setPosition(_position + perpendicular * feetSpread - forward * feetStepDistance * leftFootOffset - forward * 1.0f);

	rt.draw(footSprite);

	sf::Sprite bodySprite;

	if (_pTarget == nullptr) {
		bodySprite.setTexture(_assets->_gruntBodyWalk);

		bodySprite.setPosition(_position);
	}
	else {
		std::uniform_real_distribution<float> noiseDist(-0.5f, 0.5f);

		// Show flash for only a bit of the flash cycle time
		if (_firingCycle < 0.3f) {
			bodySprite.setPosition(_position + sf::Vector2f(noiseDist(getGame()->_generator), noiseDist(getGame()->_generator)));
			bodySprite.setTexture(_assets->_gruntBodyFlashes[_currentFlash]);
		}
		else {
			bodySprite.setPosition(_position);
			bodySprite.setTexture(_assets->_gruntBodyNoFire);
		}
	}

	bodySprite.setOrigin(sf::Vector2f(_assets->_gruntBodyWalk.getSize().x * 0.5f, _assets->_gruntBodyWalk.getSize().y * 0.5f));

	bodySprite.setRotation(_rotation + leftFootOffset * 8.0f); // Sway a bit

	rt.draw(bodySprite);
}
void mog::InputComponent::addSelfToGame(Game *g)
{
	auto networkGame = dynamic_cast<mog::network::ServerGame*> (g);

	//Not added to server
	if (networkGame != nullptr)
		return;

	auto ccNetGame = dynamic_cast<CCNetworkGame*> (g);
	assert(ccNetGame != nullptr);

	ccGame = ccNetGame->getGame();

	auto eventListener = cocos2d::EventListenerKeyboard::create();

	eventListener->onKeyPressed = [this](cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event)
	{
		auto actionPair = onPressActions.find(keyCode);
		if (actionPair != onPressActions.end())
			actionPair->second();
	};

	eventListener->onKeyReleased = [this](cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event* event)
	{
		auto actionPair = onReleaseActions.find(keyCode);
		if (actionPair != onReleaseActions.end())
			actionPair->second();
	};

	ccGame->addChild(this);
	ccGame->getEventDispatcher()->addEventListenerWithSceneGraphPriority(eventListener, this);
}
Esempio n. 29
0
PorpTextCtrl::PorpTextCtrl( int id , Vec2i const& pos , Vec2i const& size , GWidget* parent ) 
	:GTextCtrl( id , pos , size , parent )
{
	text->setCharSize( 20 );
	text->setFont( getGame()->getFont(0) );
	text->setColor( Color( 255 , 255 , 0 ) );
}
Esempio n. 30
0
void levelQueueReader()	{

	Keyword current;
	KeywordQueue kQueue = getKWQueue(NULL);
	current = kQueue->start;
	while(current != NULL)	{
		switch(current->lCommand)	{
			case wave:
					//! only expands waves into create enemies commands if it is at the start of the queue
					if(kQueue->start == current && getWave(getGame(NULL)) == returnPropertyValue(current,waveID))	{
						increaseEnemyNumbersThisWave(returnPropertyValue(current,numberOfEnemies));
						waveCreatorCommand(current);
						current = removeLink(current);
					} else { 
						current = current->prev;
					}
					break;
			case makeEnemy:
					if(createEnemyCommand(current))	{
						current = removeLink(current);
						return;
					} else {
						return;
					}
					break;
			case delay:
					setCreateEnemyGroupDelay(returnPropertyValue(current,dTime));
					current = removeLink(current);
					return;
					break;
			default:
					break;
		}
	}
}