Exemple #1
0
	int exec() {
		Clock renderClock, updateClock;
		while (window.isOpen()) {
			time = renderClock.getElapsedTime();
			float fFps = 1000000/time.asMicroseconds();
			stringstream s;
			s<<"fps: "<<fFps;
			fps.setString(s.str());
			renderClock.restart();

			const Int64 frameTime = 1000000/FRAMES_PER_SECOND;
			Clock c;
			Time t = c.getElapsedTime();
			Int64 nextFrameTime = t.asMicroseconds() + frameTime;

			int loops = 0;
			while (t.asMicroseconds() < nextFrameTime && loops < MAX_FRAMESKIP) {
				processEvents();
				updateTime = updateClock.restart().asMilliseconds();
				update();
				t = c.getElapsedTime();
				loops++;
			}

			display();
		}

		return EXIT_SUCCESS;
	}
void Game::LoadScreen()
{
	Texture loading[4];

	loading[0].loadFromFile("Art\\Loading4.png");
	loading[1].loadFromFile("Art\\Loading3.png");
	loading[2].loadFromFile("Art\\Loading2.png");
	loading[3].loadFromFile("Art\\Loading1.png");
	Clock TimeElapsed;

	Sprite Screen;
	Screen.scale(_rWindow.getSize().x/(float)loading[0].getSize().x,_rWindow.getSize().y/(float)loading[0].getSize().y);
	TimeElapsed.restart();
	

	while(TimeElapsed.getElapsedTime().asSeconds()<2.0f)
	{
		
		Clock interval;
		for(int i=0;i<4;i++)
		{
			interval.restart();
			_rWindow.clear();
			Screen.setTexture(loading[i]);
			_rWindow.draw(Screen);
			_rWindow.display();
			while(interval.getElapsedTime().asMilliseconds()<800);
			

		}
	}

}
int main()
{
    Clock clk;
    int size = 100;
    vector<int> v1,v2;
    srand(time(NULL));
    int i,k;
    for(k=0;k<4;k++)
    {
        size*=10;
        v1.clear();         v2.clear();
        v1.resize(size);    v2.resize(size);
        cout<<k+1<<"."<<endl;
        cout<<"size="<<size<<endl;
        for(i=0; i<size; ++i)
            v1.at(i) = (rand()/(RAND_MAX+1.0))*INT_MAX;
        v2 = v1;
        clk.start();
        sort(v1.begin(), v1.end());
        cout << "sort(): " << clk.getElapsedTime() << " seconds\n";
        cout << "v1/v2 are "<<((v1==v2)?"the same.\n":"different.\n");
        clk.start();
        insertion_sort(v2);
        cout << "insertion_sort(): " <<clk.getElapsedTime() << " seconds\n";
        cout << "v1/v2 are "<<((v1==v2)?"the same.\n":"different.\n")<<endl;
    }
    return 0;
}
Exemple #4
0
int main(){
	Clock clk;
	Cows c;
        int size;
        srand(time(NULL));
        cout << "enter the sorting size(ex. 1000, 10000, 100000): ";
        cin >> size;
	vector<int> weight(size), weight_2;

	int j, random;
	for(j=0; j<size; j++){
		random=rand()%size+1;
		weight[j]=random;
	}

	weight_2=weight;
	clk.start();
	sort(weight.begin(), weight.end());
	cout << "sort(): " << fixed << clk.getElapsedTime() << " seconds."<< endl;
	cout << "weight/wieght_2 are " << ((weight==weight_2)?"the same.\n":"different.\n");
        clk.start();
        c.insertion_sort(weight_2);
        cout << "insertion_sort(): " << fixed << clk.getElapsedTime() << " seconds."<< endl;
        cout << "weight/wieght_2 are " << ((weight==weight_2)?"the same.\n":"different.\n");

	

	return 0;
}
Exemple #5
0
int showWelcome(RenderWindow *window){
	Texture texBack,
		texWelcome,
		texSprite1,
		texSprite2,
		texSprite3,
		texSprite4,
		texSprite5,
		texSprite6;


	if (!texBack.loadFromFile("../data/background.png")
		|| !texWelcome.loadFromFile("../data/welcome.png")
		|| !texSprite1.loadFromFile("../data/sprite1.png")
		|| !texSprite2.loadFromFile("../data/sprite2.png")
		|| !texSprite3.loadFromFile("../data/sprite3.png")
		|| !texSprite4.loadFromFile("../data/sprite4.png")
		|| !texSprite5.loadFromFile("../data/sprite5.png")
		|| !texSprite6.loadFromFile("../data/sprite6.png"))
	{
		return EXIT_FAILURE;
	}

	Sprite spriteWelcome(texWelcome),
		sprite1(texSprite1),
		sprite2(texSprite2),
		sprite3(texSprite3),
		sprite4(texSprite4),
		sprite5(texSprite5),
		sprite6(texSprite6),
		spriteBack(texBack);

	float y = 0;

	Clock clk;
	clk.restart();
	Time tme = clk.getElapsedTime();
	while (tme.asSeconds() < 5)
	{
		window->clear();
		window->draw(spriteBack);
		sprite1.setPosition(100.0, 1.5*y + 50.0);
		sprite2.setPosition(300.0, 0.5*y + 400.0);
		sprite3.setPosition(500.0, y + 200.0);
		sprite4.setPosition(700.0, 2 * y + 700.0);
		sprite5.setPosition(900.0, y + 100.0);
		sprite6.setPosition(1100.0, 1.75*y + 750);
		window->draw(sprite1);
		window->draw(sprite2);
		window->draw(sprite3);
		window->draw(sprite4);
		window->draw(sprite5);
		window->draw(sprite6);
		window->draw(spriteWelcome);
		window->display();
		tme = clk.getElapsedTime();
		y -= 1;
	}
}
bool Game::Run()
{
	
	SplashScreen();

	LoadScreen();
	

	Initialize();
	_currentState=_pMenu;
	//_currentState = new Level1(_rWindow,_rSfmlDebugDraw,_pWorld,score);
	
	LoadContent();

	Clock timeElapsed;

	while ( _rWindow.isOpen() )
	{
		
		_rWindow.pollEvent(e);

		if ( e.type == Event::Closed )
		{
			_rWindow.close();
			UnloadContent();
			break;
		}

		if(e.type==Event::KeyPressed)
		{
			if(Keyboard::isKeyPressed(Keyboard::LAlt) && Keyboard::isKeyPressed(Keyboard::F4))
			{
				_rWindow.close();
				UnloadContent();
				break;
			}

			
		}
		
		HandleInput( e );

		//Time lastUpdateCall = timeElapsed.restart();

		if ( timeElapsed.getElapsedTime().asMilliseconds() >= timeStep)
		{
			Update( e, oldEvent, timeElapsed.restart() );
		}
	
		Time lastDrawCall = /*lastUpdateCall +*/ timeElapsed.getElapsedTime(); //.restart();

		Draw( _rWindow, lastDrawCall );

		oldEvent = e;
	}
	
	return true;
}
Exemple #7
0
int main()
{
	RenderWindow window(VideoMode(1280, 720), "Platformer");
	View view(Vector2f(0, 0), Vector2f(1280, 720)); //These numbers can be scaled to zoom it out
	window.setFramerateLimit(60);
	GUI* CurrentGUI = new GUI("menugui.txt", &window);
	CurrentGUI->SetCurrentGUI(CurrentGUI); //this line is so weird
	GUI* TestGUI = CurrentGUI;
	Clock clock;
	while (window.isOpen())
	{
		if (CurrentGUI != TestGUI)
		{
			cout << "New GUI in the main loop.\n";
			TestGUI = CurrentGUI;
		}
		if (clock.getElapsedTime().asSeconds() > 2)
		{
			cout << "CurrentGUI Address = " << CurrentGUI << endl;
			cout << "CurrentGUI name = " << CurrentGUI->GUIFileName << endl;

			clock.restart();
		}
		window.clear(Color::White);
		Event event;
		/*while (window.pollEvent(event)) //If theres any event that is supposed to close the window, do that and deallocate everything.
		{ 
			if (event.type == Event::Closed)
			{
				cout << "Closing...\n";
				window.close();
				cout << "Successfully closed window.\n";
				return 0;
			}
			else if (event.type == sf::Event::MouseWheelMoved)
			{
				if (event.mouseWheel.delta > 0)
				{
					view.zoom(0.7f);
					cout << "Zooming in... \n";
				}
				else if (event.mouseWheel.delta < 0)
				{
					view.zoom(1.3f);
					cout << "Zooming out... \n";
				}
			}
		} */
		if (Keyboard::isKeyPressed(Keyboard::Escape))
		{
			window.close();
		}
		window.setView(view);
		CurrentGUI->Update();
		view.setCenter(window.getSize().x / 2, window.getSize().y / 2);
		window.display();
	}

	return 0;
} 
Exemple #8
0
void main()
{
    RenderWindow window(VideoMode(900, 720), "Limitus: Imaginatus");
	RenderWindow* win = &window;
//	window.setFramerateLimit(60);
	

	SceneSystem::openScene(new Mainmenu);
	Clock clock;
	
	while (window.isOpen())
    {
		Event event;
        while (window.pollEvent(event))
        {
            if (event.type == Event::Closed)
                window.close();
        }

		Time elapsed = clock.getElapsedTime();
		float dt = 0.00001f*elapsed.asMicroseconds();
		clock.restart();
		
		SceneSystem::update(dt);

        window.clear();
		SceneSystem::draw(win);
		window.display();
		//cout << elapsed.asSeconds() << endl;
		 
		//system("cls");
	}
}
Exemple #9
0
void main()
{
	Clocks clocks;
	Hands hands;
	InitializeHands(hands);
	InitializeClocks(clocks);

	sf::ContextSettings settings;  //initialization of window
	settings.antialiasingLevel = 8;
	sf::RenderWindow window(sf::VideoMode(400, 400), "Clock", sf::Style::Default, settings);

	Clock frameClock;   //time for screen-update
	float timeSinceLastFrame;

	while (window.isOpen())
	{
		timeSinceLastFrame = frameClock.getElapsedTime().asSeconds();
		CheckWindowClose(window);
		if (timeSinceLastFrame >= 1)		//screen update every second
		{
			window.clear(Color::White);
			frameClock.restart();

			UpdateClockTime(hands);
			ComputeHandsPosition(hands); 
			Draw(window, clocks, hands);

			window.display();
		}
	}
}
Exemple #10
0
    void TcpClient::connect(const IpAddress& address, NetPort port, const Duration& timeout, const Duration& pause)
    {
        Expect(address.isValid(), Throw(InvalidParameter, "Invalid IpAddress"));
        Expect(port != NetPort_Any, Throw(InvalidParameter, "Invalid NetPort"));

        int ret;
        Clock clock;

        Socket::create(address.getProtocol());

        prv::SockAddrBuffer buffer(address, port);

        clock.start();

        do
        {
            ret = ::connect(getHandler(), buffer.getSockAddr(), buffer.getLength());

            if(ret != 0)
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<long long>(pause.asMilliseconds())));
            }
        }while(ret != 0 && clock.getElapsedTime() < timeout);

        Expect(ret == 0, Throw(InternalError, "Failed to connect to the remote host"));
    }
Exemple #11
0
int		SelectPolicy::waitForEvent(int timeout)
{
	struct timeval time;
	int ret;
	fd_set *set[3];
	Clock	clock;

	while (_wait)
	{
		int t = this->handleTimers(timeout);
		if (t >= 0)
		{
			time.tv_sec = t / 1000;
			time.tv_usec = (t % 1000) * 1000;
		}
		fd_set rs = _read_set, ws = _write_set, es = _except_set;
		set[0] = (_rsize == 0) ? nullptr : &rs;
		set[1] = (_wsize == 0) ? nullptr : &ws;
		set[2] = (_esize == 0) ? nullptr : &es;
#if defined (_WIN32)
		if (!set[0] && !set[1] && !set[2])
		{
			Net::Clock::sleep(t);
			continue ;
		}
		else
#endif
			ret = ::select(_maxfd + 1, set[0], set[1], set[2], (t < 0) ? nullptr : &time);
		if ((ret == -1 && errno == EINTR) || (ret == 0 && timeout != 0))
			continue ;
		if (ret == -1)
			std::cerr << Net::getLastError() << std::endl;
		if (ret == -1  || (ret == 0 && timeout == 0))
			return ret;
		if (timeout > 0)
		{
			timeout -= clock.getElapsedTime();
			clock.update();
			if (timeout < 0)
				timeout = 0;
		}
		for (auto it = _sockets.begin(); it != _sockets.end();)
		{
			auto socket = it->first;
			auto handler = socket->getEventHandler();
			auto handle = socket->getHandle();
			++it;
			if (FD_ISSET(handle, &es))
				handler->handleClose(*socket);
			else
			{
				if (FD_ISSET(handle, &rs) && handler->handleInput(*socket) <= 0)
						handler->handleClose(*socket);
				else if (FD_ISSET(handle, &ws) && handler->handleOutput(*socket) <= 0)
						handler->handleClose(*socket);
			}
		}
	}
	return 0;
}
Exemple #12
0
void ModuleCamera::Update()
{
	uint64_t camera = *Global->Get<uint64_t>("camera");
	auto cam = Entity->Get<Camera>(camera);
	auto wnd = Global->Get<RenderWindow>("window");

	// rotate camera head
	Vector2i center(wnd->getSize().x / 2, wnd->getSize().y / 2);
	Vector2i position = Mouse::getPosition(*wnd);
	if(cam->Active && position != center)
	{
		Mouse::setPosition(center, *wnd);
		Vector2i offset = position - center;
		Rotate(vec3(offset.y, -offset.x, 0));
	}

	// synchronize camera head and capsule body
	if(cam->Person)
	{
		auto frmcam = Entity->Get<Form>(camera);
		auto frmpsn = Entity->Get<Form>(cam->Person);
		frmcam->Position(frmpsn->Position() + vec3(0, Entity->Get<Person>(cam->Person)->Eyes, 0));
		frmpsn->Rotation(vec3(0, Yaw(), 0));
	}

	// store cameras every some milliseconds
	static Clock clock;
	if(clock.getElapsedTime().asMilliseconds() > 500)
	{
		Save();
		clock.restart();
	}

	Calculate();
}
void run_animation(RenderWindow &window)
{
	Clock clock;
	std::vector<initialization_blocks*>  object;
	float x = RECTANGLES_SIZE.x / 2, y = 0;
	int number_block;
	for (int i = 0; i < NUMBER_BLOCKS; i++) {
		y += 10 + RECTANGLES_SIZE.y;
		object.push_back(new initialization_blocks(x, y, i));
	}
	while (window.isOpen())
	{
		Event event;
		while (window.pollEvent(event))
			if (event.type == Event::Closed)
				window.close();

		float time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time = time / 800;
		
		window.clear(Color::White);
		number_block = 0;
		for (auto i : object) {
			i->update(time, number_block);
			window.draw(i->rectangle);
			number_block++;
		}
		window.display();
	}
}
Exemple #14
0
int main(){
	Clock clk;
	const int size = 1000;
	vector <int> v1 (size), v2;
	srand(time(NULL));
	for(int i = 0; i < size; ++i) v1.at(i) = random();
	v2 = v1;
	clk.start();
	sort(v1.begin(), v1.end());
	cout << "sort(): " << clk.getElapsedTime() << " seconds\n";
	cout << "v1/v2 are " << ((v1==v2) ? "the same.\n" : "different.\n");
	clk.start();
	insertion_sort(v2);
	cout << "insertion_sort(): " << clk.getElapsedTime() << " seconds\n";
	cout << "v1/v2 are " << ((v1==v2) ? "the same.\n" : "different.\n");
	return 0;
}
Exemple #15
0
int main()
{
    RenderWindow window(VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "OO2");
	window.setVerticalSyncEnabled(true);

	Font calibri;
	if(!calibri.loadFromFile("res/calibri.ttf")){
		printf("Error: font not found!\n");
	}
	Text debugText;
	debugText.setFont(calibri);
	debugText.setString("0");
	debugText.setCharacterSize(24);
	debugText.setColor(Color::White);

	Clock clock;
	Time elapsedTime = clock.restart(); 
	int fps = 0;

	Player player();

    while (window.isOpen())
    {	
		elapsedTime = clock.getElapsedTime();
        Event event;
        while (window.pollEvent(event))
        {
            if (event.type == Event::Closed)
                window.close();
        }
		if (Controls::get()->iskeydown(Keyboard::Escape)){
			window.close();
		}

		//Logic here		
		Controls::get()->update();

		//FPS
		if(elapsedTime.asMilliseconds() >= 1000){
			clock.restart();
			debugText.setString(std::to_string(fps));
			fps = 0;
		}
		else{
			fps++;
		}


		//Draw here
		window.clear(Color::Black);
		window.draw(debugText);
        window.display();
    }

    return 0;
}
bool MusicManager::initialize(sf::RenderWindow* window){
	Clock cl;
	// Loading sounds
	if (archiveMusic()){
		logger::timing("Music loaded in " + to_string(cl.getElapsedTime().asSeconds()) + " seconds");
		return true;
	}
	else{
		logger::fatal("MusicManager failed to initialize");
		return false;
	}
}
Exemple #17
0
void RunProgram(RenderWindow& window)
{
	RectangleStruct rect[QUANTITY] = {};
	SecreteStruct secret;
	StageStruct stage;
	InitializationSqure(rect);
	Clock clock;
	Clock change_clock;
	srand(time(NULL));

	InitializationStage(stage);
	int secret_stage = 1;
	int i_color = 0;
	int num_turns = 0;
	float i_size = 1;

	Vector2f speed_move;
	speed_move.x = SPEED;
	speed_move.y = SPEED;

	InitializationSecret(secret);

	change_clock.restart();
	while (window.isOpen())
	{
		float time = clock.getElapsedTime().asMicroseconds();
		float time_for_change = change_clock.getElapsedTime().asSeconds();
		clock.restart();
		time = time / 1000;
		sf::Event event;
		if (time_for_change >= TIME)
		{
			change_clock.restart();
			SecretChange(secret);
		}
		while (window.pollEvent(event))
		{

			if (event.type == sf::Event::Closed)
				window.close();
		}
		StageSelect(stage, i_color, i_size, rect);
		SceneChange(stage, i_color, i_size, speed_move, time);

		if (secret.rotation == 1) Rotation(rect, time);
		if (secret.color == 1) ChangeColor(rect, i_color, time);
		if (secret.size == 1) ChangeSize(rect, i_size, time);
		if (secret.move == 1) Move(rect, speed_move);

		Draw(window, rect);
	}
}
void AnimationTester::run(){
	Clock fg;
	c::initialize();
	logger::timing("Constants initialized in " + std::to_string(fg.getElapsedTime().asSeconds()) + " seconds.");
	fg.restart();
	gi::initalize(window);
	logger::timing("Graphics interface initialized in " + std::to_string(fg.getElapsedTime().asSeconds()) + " seconds.");
	manager = new Manager();
	manager->initialize(window);
	logger::timing("Manager initialized in " + std::to_string(fg.getElapsedTime().asSeconds()) + " seconds.");

	manager->inputManager->registerListener(keyboardListenerW);
	manager->inputManager->registerListener(mouseWheelListenerW);

	world = new World();

	load();

	window->setFramerateLimit(60);
	while (gi::startOfFrame()){
		world->tick();
		manager->tick(window, world->time(), world->dt());

		window->clear();

		world->render();
		manager->menuManager->draw(world->time());

		gi::endOfFrame();
	}

	save();

	manager->finalize(window);
	delete manager;
	gi::finalize();
	delete world;
}
bool NetworkEngine::waitUntilConnected( unsigned int timeout )
{
	Clock clock;
	while(clock.getElapsedTime() < timeout)
	{
		if(isConnected())
		{
			return true;
		}
	}
	//Ha pasado el timeout, puede ser que la contraseña fuese incorrecta
	std::cout << "Error: Timeout al conectarse al servidor\n";
	return false;
}
Exemple #20
0
void startGame()
{
	RenderWindow window(VideoMode((sizeRectangleWeb * 2 - 1) * 32, (sizeRectangleWeb + 3) * 32), "Sea war");

	///////////////////////////////////////////////////////
	// «агрузка текстур
	sf::Sprite mapSprite, buttons[2];
	sf::Texture textureTile;
	sf::Texture textureButtons;

	textureButtons.loadFromFile("recourses\\images\\Buttons.png");
	textureTile.loadFromFile("recourses\\images\\map.png");
	mapSprite.setTexture(textureTile);

	buttons[0].setTexture(textureButtons);
	buttons[1].setTexture(textureButtons);
	///////////////////////////////////////////////////////
	//labelStartGame:


	generateMaps(amountShips,
		amountEveryType, myPlace, enemyPlace,
		coordinatesMyShips, coordinatesEnemyShips);

	// „тобы не было рывков создаЄм часы
	Clock clock;

	while (window.isOpen())
	{
		float time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time = time / 800;

		processEvents(window, buttons, myQueue, gameNotFinish);

		if (gameNotFinish)
		{
			if (myQueue == false)
			{
				enemyQueue(myPlace, direction,
					countMyDestroyShips, victoryNumber, lastTile,
					coordinatesMyShips, memberDirection,
					findDirection, findShip, myQueue, gameNotFinish,
					x, y);
			}
		}
		render(window, mapSprite, buttons, myPlace, enemyPlace);
	}
}
void startMenu::runMenu() {
	Clock clock;
	while (_window.isOpen()) {
		float time = clock.getElapsedTime().asMicroseconds() / 800;
		clock.restart();
		if (menuControl()) return;
		if (_ButtFocus == start) { _start.setFocus(true); _options.setFocus(false); _autors.setFocus(false); _quit.setFocus(false); }
		if (_ButtFocus == option) { _start.setFocus(false); _options.setFocus(true); _autors.setFocus(false); _quit.setFocus(false); }
		if (_ButtFocus == autors) { _start.setFocus(false); _options.setFocus(false); _autors.setFocus(true); _quit.setFocus(false); }
		if (_ButtFocus == quit) { _start.setFocus(false); _options.setFocus(false); _autors.setFocus(false); _quit.setFocus(true); }
		_window.clear();
		update(time);
		_window.display();
	}
}
Exemple #22
0
void SFMLWorld::RunWorld(void)
{
	window = new sf::RenderWindow(sf::VideoMode(windowWidth, windowHeight), "World window");
	Clock cl = Clock();

	totalElapsedSeconds = 0.0f;
	worldOver = false;
	float elapsed;
	sf::Event windowEvent;

	InitializeWorld();

	cl.restart();

	while (window->isOpen() && !worldOver)
	{
		//Handle window events first.
		while (window->pollEvent(windowEvent))
		{
			if (windowEvent.type == sf::Event::Closed)
			{
				OnCloseWindow();
			}
			else if (windowEvent.type == sf::Event::Resized)
			{
				OnWindowResized(windowEvent.size.width, windowEvent.size.height);
			}
			else
			{
				OnOtherWindowEvent(windowEvent);
			}
		}

		//Get elapsed time.
		elapsed = cl.getElapsedTime().asSeconds();
		totalElapsedSeconds += elapsed;
		cl.restart();

		//Call functions.
		if (elapsed > 0.0f)
		{
			UpdateWorld(elapsed);
			RenderWorld(elapsed);
		}
	}

	OnWorldEnd();
}
Exemple #23
0
 void render(bool ending) {
     if(!thisRunning) return;
     switch(round) {
         case 0:
             if(ending) {
                 movementMessage.setFade(0);
             } else if(changing) {
                 if(clock.getElapsedTime()>DISAPPEAR_DELAY && clock.getElapsedTime()<(DISAPPEAR_DELAY+REAPPEAR_DELAY)) {
                     movementMessage.active=false;
                 } else if (clock.getElapsedTime()>(DISAPPEAR_DELAY+REAPPEAR_DELAY)) {
                     changing=false;
                     spaceBarMessage.active=true;
                     round++;
                 }
             } else {
                 if(Keyboard::isKeyPressed(INFO::leftstrafeKey)) {
                     changing=true;
                     clock.restart();
                 }
             }
             break;
         case 1:
             if(ending) {
                 spaceBarMessage.setFade(0);
             } else if(changing) {
                 if(clock.getElapsedTime()>DISAPPEAR_DELAY && clock.getElapsedTime()<(DISAPPEAR_DELAY+REAPPEAR_DELAY)) {
                     spaceBarMessage.active=false;
                 } else if (clock.getElapsedTime()>(DISAPPEAR_DELAY+REAPPEAR_DELAY)) {
                     changing=false;
                     escapeMessage.active=true;
                     round++;
                 }
             } else {
                 if(Keyboard::isKeyPressed(INFO::actionKey)) {
                     changing=true;
                     clock.restart();
                 }
             }
             break;
         case 2:
             if(ending) {
                 escapeMessage.setFade(0);
                 escapeMessage.active=false;
                 round++;
             }
             break;
         case 3:
             thisRunning=false;
             break;
     }
 }
Exemple #24
0
void StartProgram(RenderWindow & window, vector<Block> & blocks, int & stateIndex)
{
	Clock frameClock;   //time for screen-update
	float timeSinceLastFrame;

	while (window.isOpen())
	{
		timeSinceLastFrame = frameClock.getElapsedTime().asMilliseconds();
		ProcessEvents(window);
		if (timeSinceLastFrame >= TIME_PER_FRAME)		//screen update every second
		{
			window.clear(Color::White);
			frameClock.restart();

			Update(blocks, stateIndex);
			Draw(window, blocks);

			window.display();
		}
	}
}
Exemple #25
0
int main(int argc, char* argv[])
{
  Window okno(VideoMode::getDesktopMode(),"Rattle",Style::Fullscreen,ContextSettings(24,8,4));
  okno.setFramerateLimit(150);
  //const Input& wejscie=okno.GetInput();
  Event event;
  Event zdarzenie;
  bool GlownaPetla=true;
  Clock zegar;

  if (glewInit() != GLEW_OK) //koniecznie po stworzeniu okna!!!
  {
    cerr<<"GLEW error"<<endl;
    return 1;
  }

  okno.display();
  while(GlownaPetla)
    {
      if(okno.pollEvent(zdarzenie))
        {
          switch(zdarzenie.type)
            {
            case Event::KeyPressed:
              if(zdarzenie.key.code==Keyboard::Q)
                GlownaPetla=false;
              break;

            case Event::MouseButtonPressed:
              break;
            }
        }
      
      OpenGL_test(zegar.getElapsedTime().asMilliseconds());
      zegar.restart();
      okno.display();
    }

  return 0;
}
Exemple #26
0
void StartProgram(RenderWindow & window, Pendulum & pendulum)
{
	Clock frameClock;
	int timeSinceLastFrame;

	while (window.isOpen())
	{
		timeSinceLastFrame = frameClock.getElapsedTime().asMilliseconds();
		ProcessEvents(window);
		if (timeSinceLastFrame >= TIME_PER_FRAME)
		{
			frameClock.restart();

			ComputePhysics(pendulum);
			UpdatePendulum(pendulum);

			window.clear(Color::White);
			Draw(window, pendulum);
			window.display();
		}
	}
};
Exemple #27
0
void StartProgram(RenderWindow & window, Car & car, Physics & physics, const RectangleShape & ground)
{
	Clock frameClock;
	int timeSinceLastFrame;

	while (window.isOpen())
	{
		timeSinceLastFrame = frameClock.getElapsedTime().asMilliseconds();
		ProcessEvents(window);
		if (timeSinceLastFrame >= TIME_PER_FRAME)
		{
			frameClock.restart();

			ComputePhysics(physics);
			UpdateCar(car, physics);

			window.clear(Color::White);
			Draw(window, car, ground);
			window.display();
		}
	}
}
Exemple #28
0
int main(int argc, char ** argv)
{
	Uint64 lastUpdateTime = 0;
	Clock time;
	GameEngine engine(WORLD_VIEW_WIDTH, WORLD_VIEW_HEIGHT);

	engine.pushState(new PlayingState());
	
	while (!engine.expended())
    {
		Uint64 currentTime = time.getElapsedTime().asMilliseconds();
		Uint64 elapsedTime = currentTime - lastUpdateTime;
		
		elapsedTime = (elapsedTime > GAME_MAXIMUM_UPDATE_INTERVAL) ? GAME_MAXIMUM_UPDATE_INTERVAL : elapsedTime;

		engine.handleEvents();
		engine.update(elapsedTime);
		engine.draw();

		lastUpdateTime = currentTime;
    }
    return 0;
}
Exemple #29
0
 int main()
 {
	 RenderWindow window(VideoMode(1300,702),"Find the fish", Style::Default);
	 window.setPosition(Vector2i(10,10));
	 menu(window);
	 int cntMeow = 0;


	//>>>>>>>>>>>>>>>>---Load basic image for level1----<<<<<<<<<<<<<<<<<
	Texture texture;
	texture.loadFromFile("images/level1empty.jpg");
	Sprite level(texture);

	//>>>>>>>>>>>>>>>>---Music---<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Music mainSong;
	 mainSong.openFromFile("music/level1.ogg");
	 mainSong.play();
	 mainSong.setLoop(true);
	 mainSong.setVolume(75);

	 //>>>>>>>>>>>>>>>>---Create a cat---<<<<<<<<<<<<<<<<<<<
	 Player p("cat.png", 55, 25, 200, 120, 45, 445);
	 Clock clock;

	 //>>>>>>>>>>>>>>>>---Sounds----<<<<<<<<<<<<<<<<<<<
	SoundBuffer buf1, buf2;
	buf1.loadFromFile("music/meow1.ogg");
	buf2.loadFromFile("music/meow2.ogg");
	Sound meow1, meow2;
	meow1.setBuffer(buf1);
	meow2.setBuffer(buf2);

	 //Objects
	 Object posters("tayles1.png", 160, 660, 210, 250, 280, 215);
	 Object bed("tayles1.png", 420, 80, 280, 310, 250, 440);
	 Object toys("tayles1.png", 120, 470, 180, 150, 220, 545);
	 Object upShelf("tayles1.png", 700, 652.5, 120, 97.5, 350, 83);
	 Object cabinet("tayles1.png", 75, 40, 250, 350, 605, 305);
	 Object mop("tayles1.png", 515, 785, 165, 241, 587, 385);
	 Object flower("tayles1.png", 780, 65, 170, 330, 147, 285);
	 Object ball("tayles1.png", 905, 615, 40, 55, 357, 190);
	 Object books("tayles1.png", 860, 735, 125, 80, 290, 187);
	  while (window.isOpen())
    {

		float time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time = time/500;
		Vector2i pos = Mouse::getPosition(window);

        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
			//>>>>>----Meow----<<<<<<
			if (event.type == Event::MouseButtonPressed)
					if (event.key.code == Mouse::Left)
						if (p.sprite.getGlobalBounds().contains(pos.x, pos.y))
						{
							if(cntMeow == 5)
							{
								meow2.play();
								cntMeow = 0;
							}
							meow1.play();
							cntMeow++;
						}
			//------------------------------------------------------------------------------
        }
		p.update(time);

		window.clear();
		window.draw(level);
		window.draw(posters.sprite);
		window.draw(bed.sprite);
		window.draw(toys.sprite);
		window.draw(upShelf.sprite);
		window.draw(cabinet.sprite);
		window.draw(mop.sprite);
		window.draw(flower.sprite);
		window.draw(ball.sprite);
		window.draw(books.sprite);
		window.draw(p.sprite);
		window.display();
    }
 }
Exemple #30
0
int ride( RenderWindow &window)
{


    //RenderWindow window(sf::VideoMode(640, 480), "Lesson 7. kychka-pc.ru");
    Image image;
    image.loadFromFile("machine.png");

    image.createMaskFromColor(Color (255, 255, 255));

    image.createMaskFromColor(Color (253, 253, 253));

    image.createMaskFromColor(Color (254, 254, 254));
    Texture herotexture;
    herotexture.loadFromImage(image);
    Sprite herosprite, tmpherosprite;
    herosprite.setTexture(herotexture);
    herosprite.setTextureRect(IntRect(0, 0, 135, 72));
    herosprite.setPosition(250, 250);
    tmpherosprite = herosprite;
    float CurrentFrame = 0;//хранит текущий кадр
    Clock clock;
    float angle = 0;
    Vector2f vert;
    Vector2f pos;

    vert.x = 1;
    vert.y = 0;
    while (window.isOpen())
    {

        float time = clock.getElapsedTime().asMicroseconds();
        clock.restart();
        time = time / 800;


        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        if ((Keyboard::isKeyPressed(Keyboard::Up) || (Keyboard::isKeyPressed(Keyboard::W)))) {
            CurrentFrame += 0.005*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
            //if (CurrentFrame > 3) CurrentFrame -= 3; //проходимся по кадрам с первого по третий включительно. если пришли к третьему кадру - откидываемся назад.
           // herosprite.setTextureRect(IntRect(96 * int(CurrentFrame), 0, 96, 96)); //проходимся по координатам Х. получается 96,96*2,96*3 и опять 96
            herosprite.move(0.1 * time * vert.x, 0.1 * time * vert.y);//происходит само движение персонажа вниз
        }
        if ((Keyboard::isKeyPressed(Keyboard::Down) || (Keyboard::isKeyPressed(Keyboard::S)))) {
            CurrentFrame += 0.005*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации
            //if (CurrentFrame > 3) CurrentFrame -= 3; //проходимся по кадрам с первого по третий включительно. если пришли к третьему кадру - откидываемся назад.
           // herosprite.setTextureRect(IntRect(96 * int(CurrentFrame), 0, 96, 96)); //проходимся по координатам Х. получается 96,96*2,96*3 и опять 96
            herosprite.move(-0.1 * time * vert.x, -0.1 * time * vert.y);//происходит само движение персонажа вниз
        }
        if ((Keyboard::isKeyPressed(Keyboard::Right) || (Keyboard::isKeyPressed(Keyboard::D)))) {

            angle += float(time)/1000;
            vert.x = cos(angle);
            vert.y = sin(angle);

        }
        if ((Keyboard::isKeyPressed(Keyboard::Left) || (Keyboard::isKeyPressed(Keyboard::A)))) {

        angle -= float(time)/1000;
            vert.x = cos(angle);
            vert.y = sin(angle);
        }

        if(Keyboard::isKeyPressed(Keyboard::Escape))
            break;

        pos = herosprite.getPosition();
        tmpherosprite.setPosition(int(-vert.x * 67.5 + 36 * vert.y + pos.x), int(-vert.y * 67.5 - 36 * vert.x + pos.y));
        tmpherosprite.setRotation(angle * 180 / 3.14);
        window.clear(Color(255, 255, 255));
        window.draw(tmpherosprite);
        window.display();
    }
}