Example #1
0
// Draws just the timer 
void ScoreBar::drawtimer(sf::RenderWindow &window, sf::Clock &clock)
{
	string str;

	str = "Clock: " + std::to_string(30 - int(clock.getElapsedTime().asSeconds()));
	timer.setString(str);

	window.draw(timer);
}
Example #2
0
void FPSCounter::Display(sf::RenderTarget * app, unsigned int frameCount, sf::Clock & clock)
{
    impl->fc++;
    if(impl->fc > 99)
    {
        SetText( impl->getNewText(clock.getElapsedTime().asMicroseconds()) );
    }
    TextObject::Display(app, frameCount, clock);
}
void Game_Manager::draw()
{
    static sf::Clock render_clock;
    if (render_clock.getElapsedTime().asMilliseconds() < 2) {
        return;
    }
    render_clock.restart();
    m_app->clear();

    if (is_tree)
    {
        tree_background.draw(0, 0);
        skill_button[0].draw();
        skill_button[3].draw();
        skill_button[4].draw();
        skill_button[5].draw();
        skill_button[6].draw();
        skill_button[7].draw();
        skill_button[8].draw();

        energy_text.refill(to_string(myPlayer.getEnergy()));
        energy_text.draw(0, 0, 55);
        if (skill_level < 3)
        {
            empty.draw(0, 500);
        }
        else if (skill_level >= 3)
        {
            empty.draw(0, 700);
        }
    }
    else if (is_menu_visible)
    {
        menu1.draw();
    }
    else
    {
        m_app->setView(m_view2);
        //Changes on the world
        world_sprite.draw(0, 0);
        afficherMapobjet();

        m_app->setView(m_view1);

        //Changes on the HUD, player
        myPlayer.draw();
        light_bar_background.draw(m_screen_x - light_bar_background.get_w(), 0);
        light_bar.draw(m_screen_x + 28 - light_bar_background.get_w(), 40);
        light_bar_grad.draw(m_screen_x - light_bar_background.get_w(), 0);
        energy_text.refill(to_string(myPlayer.getEnergy() ) );
        energy_text.draw(0, 0, 55);
        difficulter_text.refill(to_string(_difficulter-1));
        difficulter_text.draw(0, 100, 55);
    }
    m_app->display();
}
Example #4
0
void Boss::comportamiento(Personaje* s, Mapa *map){
    
   
    if(clock_comportamiento.getElapsedTime().asMilliseconds()>4000)      
    { srand(time(NULL));
        int num = rand()%2;
    actitud=num;
    clock_comportamiento.restart();         
    }
    if(actitud==0){
    if(detectada && !muriendo){
        if(!rapido){ this->set_speed(fast); rapido = true;}
        int distancia = this->pos->getX() - s->getPosicion()->getX();
        if(distancia > 0){ 
            if(distancia < 15){ this->attack(s); }
            else{ this->atacando = false; this->orientacion = 1;}
        }
        else{
            if(distancia > -15){ this->attack(s); }
            else{ this->atacando = false; this->orientacion = 0;}
        }
        
        int aux = this->colision_Boss(map);
        if(!(aux == 0 && this->orientacion == 0 || aux == 1 && this->orientacion == 1)){
            this->move();
        }
        else{
            this->pos->setInicial();
            clock_posicion.restart();
        }
    }}
    
    if(actitud==1){
       
     if(detectada){
         this->getPosition()->setInicial();
          clock_posicion.restart();
        //if(this->clock_quieto.getElapsedTime().asSeconds() > 0.5){ this->quieto = false; }
        if(!rapido){ this->set_speed(fast); rapido = true;}
        int distancia = this->pos->getX() - s->getPosicion()->getX();
        if(distancia > 0){
            this->orientacion = 1; 
            this->attack2(s);
            //if(this->clock_quieto.getElapsedTime().asSeconds() > 0.1){ this->orientacion = 0; }
        }
        else{
            this->orientacion = 0; 
            this->attack2(s);
            //if(this->clock_quieto.getElapsedTime().asSeconds() > 0.1){ this->orientacion = 1; }
        }
        //this->move();
     }
    }
    
}
Example #5
0
// ----------------------------------------------------------------------------
void do_motion (void)
{
	static GLint prev_time = 0;

	//int time = glutGet(GLUT_ELAPSED_TIME);
	int time=theClock.getElapsedTime().asMilliseconds();
	angle += (time-prev_time)*0.1;
	prev_time = time;

	//glutPostRedisplay ();
}
void Engine::playerControl(Player *player, float &delta_time, bool pressed)
{
    sf::Vector2f vectors;
    static sf::Vector2f wektor;
    static sf::Clock clockCrash;
    static sf::Time timerCrash;

    if(player->lifes < -1)
    {
        game_over.setString(stringGameOver+toString(player->score));
        game_over.setPosition((windowSize.x-game_over.getGlobalBounds().width)/2, windowSize.y/2);
        gameOver = true;
    }

    if(crash)
    {
        player->ship.setOutlineColor(red);
        timerCrash = clockCrash.getElapsedTime();

        if(player->lifes >= 0)
            info.setString(stringInfo+toString(player->lifes));

        if(timerCrash >= sf::seconds(5))
        {
            crash = false;
            player->ship.setOutlineColor(cyan);
            clockCrash.restart();
            player->lifes -= 1;
        }
    }

    if(player->ship.getPosition().y < - 3.f)
        player->ship.setPosition(player->ship.getPosition().x, windowSize.y + 3.f);

    else if(player->ship.getPosition().y > windowSize.y + 3.f)
        player->ship.setPosition(player->ship.getPosition().x, - 3.f);

    else if(player->ship.getPosition().x > windowSize.x + 3.f)
        player->ship.setPosition(-3.f, player->ship.getPosition().y);

    else if(player->ship.getPosition().x < - 3.f)
        player->ship.setPosition(windowSize.x + 3.f, player->ship.getPosition().y);

    if(pressed)
    {
        wektor.x = std::sin((player->ship.getRotation()*M_PI) / 180.0f);
        wektor.y = -std::cos((player->ship.getRotation()*M_PI) / 180.0f);
    }

    vectors.x = wektor.x * player->velocity * delta_time;
    vectors.y = wektor.y * player->velocity * delta_time;

    player->ship.move(vectors);
}
Example #7
0
int main(){
    sf::RenderWindow window(sf::VideoMode(800, 600), "New Metroid: Disparos");
    window.setFramerateLimit(60);
    
    std::vector<sf::Texture*> texturas;
    std::list<Bullet*> clip;
    std::list<Bullet*> toRemove;
    
    inicializar(texturas);
    float tempo;
    
    while(window.isOpen()){
        if(reloj.getElapsedTime().asMilliseconds() > UPDATE_TICK_TIME){
            tempo = reloj.getElapsedTime().asSeconds();
            reloj.restart();
            update(window, toRemove, clip, texturas);
        }
        render(window, toRemove, clip);
    }    
    return 0;
}
	void filterCollisions(std::vector<anax::Entity>& entities) {
		sf::Time currentTime = m_clock.getElapsedTime();
		for (auto entity : entities) {
			if (entity.isValid() &&  entity.hasComponent<IgnoreCollisionComponent>()) {
				auto& ignoreCollisionComp = entity.getComponent<IgnoreCollisionComponent>();
				if(ignoreCollisionComp.reason == IgnoreCollisionReason::NEW_SPLIT_BODY){
					if (currentTime - ignoreCollisionComp.timeIgnoreCollisionAdded >= m_maxIgnoreTime) {
						entity.removeComponent<IgnoreCollisionComponent>();
						//std::cout << "about to mark as deleted" << std::endl;
					}
				}
			}
		}
	}
Example #9
0
void Car::updateGhosts() {
    static sf::Clock clock = sf::Clock();
    
    sf::Time time = clock.getElapsedTime();
    
    sf::Vector2f lastLocation = this->mLastLocation;
    if (this->mCarGhostDrawables.size() > 0) {
        lastLocation = this->mCarGhostDrawables.back().ghost.getPosition();
    }
    
    // add new ghost
    float ghostDistance = length(this->mCurrentLocation - lastLocation);
    if (ghostDistance >= Car::MAX_GHOSTS_DISTANCE && this->mVelocity > 0.0f) {
        sf::RectangleShape ghost(sf::Vector2f(Car::CAR_WIDTH, Car::CAR_HEIGHT));
        ghost.setOrigin(Car::CAR_WIDTH / 2.0f, Car::CAR_HEIGHT / 2.0f);
        
        sf::Vector2f dir = normalize(this->mCurrentDirection);
        ghost.setPosition(this->mCurrentLocation); // - (dir * (Car::MAX_GHOSTS_DISTANCE + 20.0f)));
        ghost.setRotation(RAD_TO_DEG(heading(dir)));
        
        ghost.setFillColor(this->mCarDrawable.getFillColor());
        
        this->mCarGhostDrawables.push_back(Ghost(ghost, time.asMilliseconds()));
        
        if (this->mCarGhostDrawables.size() >= Car::MAX_GHOSTS) {
            this->mCarGhostDrawables.erase(this->mCarGhostDrawables.begin());
        }
    }
    
    // do we need to remove some ghosts?
    std::list<Ghost>::iterator it = this->mCarGhostDrawables.begin();
    while (it != this->mCarGhostDrawables.end()) {
        if ((time.asMilliseconds() - (*it).age) >= Car::MAX_GHOSTS_AGE) {
            it = this->mCarGhostDrawables.erase(it);
        } else {
            ++it;
        }
    }
       
    // adjust alphas
    int i = this->mCarGhostDrawables.size()+1;
    //float steps = (80.0f - (80.0f * (MAX_VELOCITY / this->mVelocity))) / static_cast<float>(i);
    float steps = 80.0f / static_cast<float>(i);
    sf::Color color = this->mCarDrawable.getFillColor();
    for (std::list<Ghost>::reverse_iterator it = this->mCarGhostDrawables.rbegin(); it != this->mCarGhostDrawables.rend(); ++it) {
        color.a = steps * i--;
        (*it).ghost.setFillColor(color);
    }

}
Example #10
0
std::string Comunicare :: interactTastatura(sf::RenderWindow &fereastra, sf::Event &ev)
{
    static sf::Clock timpActiune;
    float timpRamas = timpActiune.getElapsedTime().asSeconds();
    if(ev.type == sf::Event::TextEntered)
        text_dl_tastatura += (char)ev.text.unicode;
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::Return))
        if(timpRamas > 0.1)
        {
            timpActiune.restart();
            text_dl_tastatura += '\n';
        }
    if(sf::Keyboard::isKeyPressed(sf::Keyboard::BackSpace) && !text_dl_tastatura.empty())
        text_dl_tastatura.erase(text_dl_tastatura.size()-1,1);
}
Example #11
0
float framesPerSecond(sf::Clock & clock) {
    frames_count++;
    if (frames_count >= MAX_FRAME_SAMPLES) {
        fps = ((float)frames_count / (float)clock.getElapsedTime().asMilliseconds()) * 1000;
        clock.restart();
        frames_count = 0;
    }
    //if (clock.getElapsedTime().asMilliseconds() >= 1000) {
    //    clock.restart();
    //    fps = count;
    //    count = 0;
    //}
    fflush(stdout);
    return fps;
}
Example #12
0
    float step()
    {
        ++mySteps;

        float time(myClock.getElapsedTime().asSeconds());

        if (time >= 1.f)
        {
            std::ostringstream str; str.precision(4);
            str<<mySteps/time;
            setString(str.str());
            mySteps = 0;
            myClock.restart();
        }
        return time;
    }
Example #13
0
void PlayScene::LoadingBubbles(sf::Clock const& clock)
{
    const uint32 ms = clock.getElapsedTime().asMilliseconds();

    // Create obstacle bubbles (Todo factory)
    if (ms - m_bubbleLoadTimer >= 2000)
    {
        const uint16 bubbleRadius = ObstacleBubbleDefault::Size / 2;
        const uint16 obstacleCount
            = PlaySceneDefault::GoodBubbleCount + PlaySceneDefault::BadBubbleCount;

        sf::Vector2u const& winSize = sGame->GetWindow()->getSize();
        const uint16 maxBubbleCoordCount = winSize.x - (winSize.x - winSize.y);
        const float forBubbleSize = ObstacleBubbleDefault::Size;

        // Fill coords
        std::vector<sf::Vector2f> bubbleCoords;
        for (uint16 i = 0; i < maxBubbleCoordCount / forBubbleSize; ++i)
            bubbleCoords.push_back(sf::Vector2f(i * forBubbleSize, i * forBubbleSize));

        if (bubbleCoords.size() < obstacleCount)
            Assert(true, FS("PlayScene::LoadingBubbles: Need to generate more coordinates! "
            "Generated coords '%%%' < need count '%%%'.", bubbleCoords.size(), obstacleCount));

        // Shuffle
        std::random_shuffle(bubbleCoords.begin(), bubbleCoords.end());

        // Creating...
        for (uint16 i = 0; i < obstacleCount; ++i)
        {
            ObstacleBubble* obstacle = nullptr;
            eMoveDirs dir = RandI<uint16>(0, 1) ? eMoveDirs::Right : eMoveDirs::Left;

            // Create good bubbles
            if (i < PlaySceneDefault::GoodBubbleCount)
                obstacle = new GoodBubble(bubbleRadius, bubbleCoords.at(i), dir);
            // Create bad bubbles
            else
                obstacle = new BadBubble(bubbleRadius, bubbleCoords.at(i), dir);

            m_bubbles.push_back(obstacle);
        }

        m_bubbleLoaded = true;
    }
}
Example #14
0
void	AMovingObject::move(const sf::Clock &clock)
{
	float	dist;

	dist = clock.getElapsedTime().asMicroseconds() * speed;
	if (direction % 2 == 1)
		dist /= 1.4f;
	if (direction >= 7)
		posY -= dist;
	else if (direction <= 3)
		posY += dist;
	if (direction % 3 == 0)
		posX += dist;
	if (direction % 3 == 1)
		posX -= dist;
	posX = (posX < 0) ? 0 : (posX >= WIDTH) ? WIDTH - 1 : posX;
	posY = (posY < 0) ? 0 : (posY >= LENGTH) ? LENGTH - 1 : posY;
}
Example #15
0
void MenuBackground::DoLogic()
{
    //Now the background of menu will move always at the same pace
    static sf::Clock frameTime;
    m_view.move(1.2f*frameTime.getElapsedTime().asMilliseconds(),0);
    frameTime.restart();

    //When the view reaches the End of the current level, reset the view and Load a new level
    if(m_view.getCenter().x >= m_tileSize.x * m_levelLength)
    {
        m_view = m_window.getView();

        m_view.setCenter(400,225);

        m_renderTex.setView(m_view);
        Init();
    }

    m_renderTex.setView(m_view);
}
Example #16
0
void server_reliability_manager::tick(game_state* state)
{
    const float broadcast_time_ms = 4;

    static sf::Clock clk;

    if(clk.getElapsedTime().asMilliseconds() < broadcast_time_ms)
        return;

    clk.restart();

    for(auto& i : player_reliability_handler)
    {
        int32_t id = i.first;

        player play = state->get_player_from_player_id(id);

        i.second.tick(play.sock, play.store);
    }
}
Example #17
0
	virtual void update(){
		
		sf::Event event;
        while (window->pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
            
            {
                window->close();
                has_ended = true;
                }
             
             if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
             
             {
				 has_ended = true;
				 
			 }
             
             
                
			}
		
		
		dt = timer.getElapsedTime().asSeconds();
		
		if(dt<fadein_time)
		
		{
			darken.setFillColor(sf::Color(0,0,0, 255-(255/fadein_time)*dt));
			}
			if(dt>fadein_time+stable_time)
		
		{
			darken.setFillColor(sf::Color(0,0,0, (255/fadeout_time)*(dt-fadein_time-stable_time)));
			}
		
		if(dt>fadein_time+stable_time+fadeout_time)has_ended=true;
		
		};
void gestionTouches (sf::View &View, sf::Clock &timer)
{
    float Offset =  timer.getElapsedTime().asMilliseconds();

    // le deplacement de la map
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) )      View.move( 0,      -Offset);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) )    View.move( 0,       Offset);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) )    View.move(-Offset,  0);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) )   View.move(Offset,   0);

    // le zoom
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Add) )         View.zoom(1.005f);
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract) )    View.zoom(0.995f);

    // la gestion du "temps"
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) )    MonTimer::getSpeed() * 1.07;
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z) )    MonTimer::getSpeed() / 1.07;

    // clean
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::E) )     std::cout <<std::endl <<std::endl<<std::endl<<std::endl;

}
Example #19
0
void display(sf::RenderWindow *window)
{
	if (frames==0)
		sfclock.restart();
	
	// Draw using SFML
	window->pushGLStates();
	window->resetGLStates();
	//insert SFML drawing code here (any part you are using that does not involve opengl code)
	window->popGLStates();

	//set up the background color of the window. This does NOT clear the window. Right now it is (0,0,0) which is black
	glClearColor(0,0,0,0);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //this command actually clears the window.
	glEnable(GL_DEPTH_TEST);
	v.draw(); //simply delegate to our view class that has all the data and does all the rendering

	if (frames>500)
	{
		sf::Time t = sfclock.getElapsedTime();
		frame_rate = frames/t.asSeconds();
		frames = 0;
	}
	else
	{
		frames++;
	}
	stringstream str;

	str << "Frame rate " << frame_rate;
	// Draw some text on top of our OpenGL object
	drawText(window,str.str(),window->getSize().x,20);
    
	
	// Finally, display the rendered frame on screen
	window->display();
//	cout << "Rendering" << endl;
}
void step()
{
	// Clear to black
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	InputManager::Update();

	// Get delta time since the last frame
	float dt = timer.getElapsedTime().asSeconds();
	timer.restart();

	CameraManager::Update(dt);

	RenderManager::Update(dt);

	teapot->Update(dt);

	RenderManager::Draw(CameraManager::ViewProjMat());

	// Swap buffers
	window.display();
}
Example #21
0
//public
void IdleAnimation::update(float dt)
{
    m_lines.erase(std::remove_if(m_lines.begin(), m_lines.end(), 
        [](const std::unique_ptr<LineSection>& line)
    {
        return line->dead(); 
    }), m_lines.end());
    
    for (auto& l : m_lines)
    {
        l->update(dt);
    }

    updatePoint(m_start, dt);
    updatePoint(m_end, dt);

    static sf::Clock timer;
    if (timer.getElapsedTime().asSeconds() > spawnFrequency)
    {
        timer.restart();
        m_lines.emplace_back(std::make_unique<LineSection>(m_start.position, m_end.position));
    }
}
event MameUIsenWindow::getJoystickEvent()
{
	static sf::Clock clock;
	if(clock.getElapsedTime().asMilliseconds() >= configuration.getJoystick_delay())
	{
		clock.restart();
		if(sf::Joystick::getAxisPosition(joystickId, sf::Joystick::X) < 0)
		{
			return PREVIOUS_CATEGORY;
		}
		else if(sf::Joystick::getAxisPosition(joystickId, sf::Joystick::X) > 0)
		{
			return NEXT_CATEGORY;
		}
		else if(sf::Joystick::getAxisPosition(joystickId, sf::Joystick::Y) < 0)
		{
			return PREVIOUS_ROM;
		}
		else if(sf::Joystick::getAxisPosition(joystickId, sf::Joystick::Y) > 0)
		{
			return NEXT_ROM;
		}
		else if(sf::Joystick::isButtonPressed(joystickId, 0))
		{
			return LAUNCH_ROM;
		}
		else
		{
			return NO_EVENT;
		}
	}
	else
	{
		return NO_EVENT;
	}
}
Example #23
0
void App::run()
{
  int frame_counter = 0;
  static sf::Clock clock;

  // Populate the state machine using a template method.
  _populate_states();

  // Set running boolean.
  impl->is_running = true;

  clock.restart();

  // Start the loop
  while (impl->is_running)
  {
    // Process events
    sf::Event event;
    while (impl->app_window->pollEvent(event))
    {
      handle_event(event);
    }

    impl->state_machine->execute();

    // Limit frame rate to 62.5 fps.
    if (clock.getElapsedTime().asMilliseconds() > 16)
    {
      clock.restart();
      impl->app_window->clear();
      impl->state_machine->render(*(impl->app_window.get()), frame_counter);
      impl->app_window->display();
      ++frame_counter;
    }
  }
}
Example #24
0
void game_state::periodic_gamemode_stats_broadcast()
{
    static sf::Clock clk;

    ///once per second
    float broadcast_every_ms = 1000.f;

    if(clk.getElapsedTime().asMicroseconds() / 1000.f < broadcast_every_ms)
        return;

    clk.restart();

    byte_vector vec;
    vec.push_back(canary_start);
    vec.push_back(message::GAMEMODEUPDATE);
    vec.push_back(mode_handler.current_game_mode);

    vec.push_back(mode_handler.current_session_state);
    vec.push_back(mode_handler.current_session_boundaries);

    vec.push_back(canary_end);

    broadcast(vec.ptr, -1);
}
Example #25
0
	static int GetDelay()
	{
		return spawnDelay.getElapsedTime().asMilliseconds();
	}
Example #26
0
void stateUpdate()
{
	while(server.hasGameStarted())
	{
		float elapsedTime = deltaClock.getElapsedTime().asMilliseconds();
		float ballElapsedTime = ballClock.getElapsedTime().asMilliseconds();
		ballSendTimer += elapsedTime;
		ballClock.restart();
		if(elapsedTime >= 16.6)
		{
			deltaClock.restart();
			//Update the ball's position.
			ballRect = sf::FloatRect(ballRect.left + ballVelocity.x, ballRect.top + ballVelocity.y, ballRect.width, ballRect.height);
		}

		//Check for paddle collisions.
		if(ballRect.intersects(onePaddleRect) && ballVelocity.x < 0)
		{
			ballVelocity.x *= (-1.0f);
			std::cout << "Ball rebound off Paddle One." << std::endl;
			ballCollisionDetected = true;
		}
		else if(ballRect.intersects(twoPaddleRect) && ballVelocity.x > 0)
		{
			ballVelocity.x *= (-1.0f);
			std::cout << "Ball rebound off Paddle Two." << std::endl;
			ballCollisionDetected = true;
		}

		checkBounds();

		//Check and manage points for both players.
		if(ballRect.left <= LEFT_WALL + 3 && ballVelocity.x < 0)
		{
			server.sendAll("3 2");
			
			player2Points++;

			std::cout << "Player 2 Score update: " << player2Points << std::endl;

			//Send the end game message if player 2 wins.
			if(player2Points >= MAX_POINTS)
			{
				server.sendAll("4 2");
				
				server.stopGame();

				std::cout << "Player Two win with points." << std::endl;
			}

			ballRect = sf::FloatRect(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT);
			ballCollisionDetected = true;
		}
		if(ballRect.left + ballRect.width >= SCREEN_WIDTH - 3 && ballVelocity.x > 0)
		{
			server.sendAll("3 1");

			player1Points++;

			std::cout << "Player 1 Score update: " << player1Points << std::endl;

			//Send the end game message if player 1 wins.
			if(player1Points >= MAX_POINTS)
			{
				server.sendAll("4 1");

				server.stopGame();

				std::cout << "Player One win with points." << std::endl;
			}

			ballRect = sf::FloatRect(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, BALL_WIDTH, BALL_HEIGHT);
			ballCollisionDetected = true;

			std::cout << "Collided" << std::endl;
		}

		if(ballCollisionDetected || ballSendTimer >= (1/60))
		{
			ballSendTimer = 0;
			std::time_t rawtime;
			std::time(&rawtime);

			//Send the ball packet.
			std::stringstream ballPacketStringStream;
			
			ballPacketStringStream << "1 " << ballRect.left << " " << ballRect.top << " " << ballVelocity.x << " " << ballVelocity.y << " " << (rawtime - ((playerOneLag + playerTwoLag)/2));

			server.sendAll(ballPacketStringStream.str());

			ballCollisionDetected = false;
		}
	}
}
 bool within_release_hysteresis(float time_ms)
 {
     return hysteresis_time.getElapsedTime().asMicroseconds() / 1000.f < time_ms;
 }
Example #28
0
void Handle_One_Event() {
	static const long twentyTicks = time_in_ticks(20).asMilliseconds();
	static const long fortyTicks = time_in_ticks(40).asMilliseconds();
	
	through_sending();
	Handle_Update();
	
	//(cur_time - last_anim_time > 42)
	if((animTimer.getElapsedTime().asMilliseconds() >= fortyTicks) && (overall_mode != MODE_STARTUP) && (anim_onscreen) && get_bool_pref("DrawTerrainAnimation", true)
	   && (!gInBackground)) {
		animTimer.restart();
		draw_terrain();
	}
	if((animTimer.getElapsedTime().asMilliseconds() > twentyTicks) && (overall_mode == MODE_STARTUP)) {
		animTimer.restart();
		draw_startup_anim(true);
	}
	
	clear_sound_memory();
	
	if(map_visible && mini_map.pollEvent(event)){
		if(event.type == sf::Event::Closed) {
			mini_map.setVisible(false);
			map_visible = false;
		} else if(event.type == sf::Event::GainedFocus)
			makeFrontWindow(mainPtr);
	}
	if(!mainPtr.pollEvent(event)) {
		if(changed_display_mode) {
			changed_display_mode = false;
			adjust_window_mode();
		}
		flushingInput = false;
		redraw_screen(REFRESH_NONE);
		return;
	}
	switch(event.type) {
		case sf::Event::KeyPressed:
			if(flushingInput) return;
			if(!(event.key.*systemKey))
				handle_keystroke(event);
			
			break;
			
		case sf::Event::MouseButtonPressed:
			if(flushingInput) return;
			Mouse_Pressed();
			break;
			
		case sf::Event::MouseLeft:
			// Make sure we don't have an arrow cursor when it's outside the window
			make_cursor_sword();
			break;
			
		case sf::Event::GainedFocus:
			Handle_Update();
			makeFrontWindow(mainPtr);
		case sf::Event::MouseMoved:
			if(!gInBackground) {
				location where(event.mouseMove.x, event.mouseMove.y);
				change_cursor(where);
			}
			break;
			
		case sf::Event::MouseWheelMoved:
			if(flushingInput) return;
			handle_scroll(event);
			break;
			
		case sf::Event::Closed:
			if(overall_mode == MODE_STARTUP) {
				if(party_in_memory) {
					std::string choice = cChoiceDlog("quit-confirm-save", {"save","quit","cancel"}).show();
					if(choice == "cancel") break;
					if(choice == "save") {
						fs::path file = nav_put_party();
						if(!file.empty()) break;
						save_party(file, univ);
					}
				}
				All_Done = true;
				break;
			}
			if(overall_mode > MODE_TOWN){
				std::string choice = cChoiceDlog("quit-confirm-nosave", {"quit", "cancel"}).show();
				if(choice == "cancel")
					break;
			}
			else {
				std::string choice = cChoiceDlog("quit-confirm-save", {"save", "quit", "cancel"}).show();
				if(choice == "cancel")
					break;
				if(choice == "save")
					save_party(univ.file, univ);
			}
			All_Done = true;
		default:
			break; // There's several events we don't need to handle at all
	}
	flushingInput = false; // TODO: Could there be a case when the key and mouse input that needs to be flushed has other events interspersed?
}
Example #29
0
void update(sf::Clock& clock, Packman& packman)
{
    const float elapsedTime = clock.getElapsedTime().asSeconds();
    clock.restart();
    updatePackman(packman, elapsedTime);
}
Example #30
0
void Weapon::shoot(list<Ammo*>* air, Float2 angle)
{

    /* CADENCE DE TIR */
    double cadence;

    switch(type) // définir la cadence en millisecondes
    {
    case PISTOL       :
        cadence = 150;
        break;
    case SHOTGUN      :
        cadence = 500;
        break;
    case SMG          :
        cadence = 60;
        break;
    //case FLAMETHROWER : cadence = 100; break;
    case FLAMETHROWER :
        cadence = 1000;
        break;
    default           :
        cadence = 0;
        break;
    }

    bool cadence_ok = true;

    static int elapsed = -1;
    static sf::Clock clock;

    if(cadence > 0)
    {
        if(elapsed == -1)
        {
            elapsed = 0;
            clock.restart();
        }
        else
        {
            elapsed = clock.getElapsedTime().asMilliseconds();
            if(elapsed >= cadence)
                clock.restart();
            else
                cadence_ok = false;
        }
    }


    if(ammos.x>0 && cadence_ok)
    {
        /* POSITION DES BALLES */
        Int2 pos = owner->getPosition();
        Int2 siz = owner->getSize();

        // X
        if(angle.x > 0)
            pos.x += siz.x+30;
        else if(angle.x == 0)
            pos.x += siz.x*0.5;
        else
            pos.x -= 30;

        // Y
        if(angle.y > 0)
            pos.y += siz.y;
        else if(angle.y == 0)
            pos.y += siz.y*0.2;
        if(angle.x==0 && angle.y<0)
            pos.y -= 50;

        if(owner->getStatePosition() == Character::KNELT)
        {
            pos.y -= siz.y*0.2;
        }

        // FIX
        if(type_ammo == Ammo::FLAME)
        {
            if(angle.x != 0)
                pos.y -= siz.y*0.7;
            else
                pos.x -= siz.x*0.7;
        }


        /* CREATION DES BALLES */
        float disp;

        switch(type)
        {
        case PISTOL :
            air->push_back(new Ammo(pos,siz,0,type_ammo,angle,owner));
            ammos.x--;
            break;

        case SMG :
            disp = (rand()%2000-1000)/10000.0;
            if(angle.y==0)
                angle.y += disp;
            else
                angle.x += disp;
            air->push_back(new Ammo(pos,siz,0,type_ammo,angle,owner));
            ammos.x--;
            break;

        case SHOTGUN : //  balles
            disp = 0.2;
            for(float i=-disp; i<=disp && ammos.x>0; i+=disp/2)
            {
                Float2 tmp = angle;
                if(angle.x!=0)
                    tmp.y+=i;
                if(angle.y!=0)
                    tmp.x+=i;
                if((angle.x<0 && angle.y<0) || (angle.x>0 && angle.y>0))
                    tmp.x-=i*2;
                air->push_back(new Ammo(pos,siz,0,type_ammo,tmp,owner));
            }
            ammos.x--;
            break;

        case FLAMETHROWER :
            air->push_back(new Ammo(pos,siz,0,type_ammo,angle,owner));
            ammos.x--;
            break;
        }

        //cout << "Il reste " << ammos.x << " munitions" << endl;

    }
}