Esempio n. 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 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();
	}
}
Esempio n. 3
0
int main(int, char const**)
{
    // Create the main window
    RenderWindow window;
    window.create(VideoMode(800, 600), "Pong");

    
    
    //Create and initialize the actual game screen
    GameScreen gamescreen = GameScreen();
    gamescreen.initialize();
    
    
    // Start the game loop
    while (window.isOpen()) {
        
        // Process events
        Event p1;
        while (window.pollEvent(p1)) {
            // Close window: exit
            if (p1.type == Event::Closed) {
                window.close();
            }
            
        }
        

        // Clear screen
        window.clear();

        
        
        /*
         
         Here I am trying to use that standard game loop with initialize, update, and draw. If I ever try to make a real game in C++ I know that I will need to know how to use these methods and create objects outside of this class.
         
         */
        gamescreen.update();        
        
        //Draw each entity (sprite)
        for(Sprite ent : gamescreen.entities) {
            window.draw(ent);
        }
        
        
        
        // Update the window
        window.display();
    }

    return EXIT_SUCCESS;
}
Esempio n. 4
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);
	}
}
Esempio n. 5
0
int main()
{
	//Synchonisation coordonnée à l'écran!
	mainWin.setVerticalSyncEnabled(true);


	

	Menu mainMenu;
	mainMenu.draw(mainWin);
	
		

	while (mainWin.isOpen())
	{
		Event event;
	

		while (mainWin.pollEvent(event))
		{
			switch (event.type)
			{
				case sf::Event::Closed:
					mainWin.close();
					break;
				case sf::Event::KeyPressed:
					if (event.key.code == sf::Keyboard::Down)
					{
						mainMenu.MoveCursor("Down", mainWin);
					}
					else if (event.key.code == sf::Keyboard::Up)
					{
						mainMenu.MoveCursor("Up", mainWin);
					}
					else if (event.key.code == sf::Keyboard::Space)
					{
						mainMenu.SelectItem(mainWin);
					}
					break;


			}
		}

	}

	

	return EXIT_SUCCESS;
}
Esempio n. 6
0
// 1 = Play; 0 = Exit Game
bool mainMenu(RenderWindow& window) {

	Rectangle play(299, 505, 435, 501);
	Rectangle exit(299, 505, 539, 605);
	Rectangle info(684, 788, 746, 788);

	Sprite background;
	background.setTexture(menuNothingHighlighted);
	window.draw(background);
	window.display();

	Event event;
	while (true) {

		if (hovering(window, play, event)) {
			background.setTexture(menuPlayHighlighted);
			window.draw(background);
			window.display();
		}
		else if (hovering(window, exit, event)) {
			background.setTexture(menuExitHighlighted);
			window.draw(background);
			window.display();
		}
		else if (hovering(window, info, event)) {
			background.setTexture(menuInfoHighlighted);
			window.draw(background);
			window.display();
		}
		else {
			background.setTexture(menuNothingHighlighted);
			window.draw(background);
			window.display();
		}

		if (!window.pollEvent(event)) continue;

		if (event.type == Event::Closed) return false;
		if (wasClicked(window, play, event)) return true;
		if (wasClicked(window, exit, event)) return false;
		if (wasClicked(window, info, event)) {
			infoScreen(window);
			while (window.pollEvent(event));
			if (!window.isOpen()) return false;
		}
	}

	return false;
}
Esempio n. 7
0
int main()
{
	
	//{ -1,0 }left GlobalNormal
	//{1,0}right GlobalNormal
	//{0,1}down GlobalNormal
	//{0,-1}up GlobalNormal	
	
				//position x, position y, width, height, Color      ,faceNormal ,backNormal ,leftNormal , rightNormal
	platform[0] = { 512 - 40 ,  750 - 8 ,  150, 20,Color::White     ,{0,-1 }   ,{0 ,1 }   ,{-1,0 }   ,{ 1,0 }		}; //kinda tryhard ;p but it works, so its not stupid
	platform[1] = { 20, 380, 20, 150, Color::White					,{ 1,0 }   ,{-1,0 }   ,{ 0,-1}	 ,{ 0,1 }		};
	platform[2] = { 512 - 40, 42, 150, 20, Color::White				,{ 0,1 }   ,{ 0,1 }   ,{ 1,0 }   ,{-1,0	}		};
	platform[3] = { 984, 380, 20, 150, Color::White					,{-1,0 }   ,{ 1,0 }   ,{ 0,1 }   ,{ 0,-1}		};

	position.x = ball.position.x;
	position.y = ball.position.y;

	if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf")) 
	{
		MessageBox(NULL,"ERROR:Couldn't load font",NULL,NULL);
		window.close();
	}
	
	setText(scoreText, font, Color::Red, 24, "Score: 0", {0,0});
	setText(initialText, font, Color::White, 20, "Press space to start", { 420,320 });

	//game loop
	clock_t previous = clock();
	clock_t lag = 0;
	while (window.isOpen())
	{	
		clock_t current = clock();
		clock_t elapsed = current-previous;

		lag += elapsed;

		previous = current;
		handleEvent();
		
		while (lag > 16)
		{
			update();
			lag -=16;
		}
		render();
	}
	return 0;
}
Esempio n. 8
0
File: main.cpp Progetto: dlxgit/TP
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();
		}
	}
}
Esempio n. 9
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();
		}
	}
};
Esempio n. 10
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();
		}
	}
}
Esempio n. 11
0
int main()
{


 Sky sky;
 load_all_sound();

 bgm.play();
 Player  player;
 while (window.isOpen())
    {
        window.clear();
        sky.drawsky();

       Event event;
        while (window.pollEvent(event))
        {
            if (event.type == Event::Closed)
                window.close();
            if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Up)
                player.moveup();
            if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Down)
                player.movedown();
            if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Left)
                player.moveleft();
            if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Right)
                player.moveright();
            if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Space)
                player.gun();
        }
        player.bullet_refresh();
        window.display();
    }


    return 0;

}
Esempio n. 12
0
int main(int argc, char* argv[]) {

    Config config;
    Game game;
    game.configure(config);
    game.start();

    RenderWindow* window = GameWindow::instance().getWindow();

    while (window->isOpen()) {
        Event Event;
        while (window->pollEvent(Event)) {
            if (Event.type == Event::Closed)
                window->close();
        }
        window->clear(Color::Black);

        game.tick();
        game.render();

        window->display();
    }
}
Esempio n. 13
0
int main()
{
	Button			start_button(MediaBucket.getTexture("Start1"), sf::Vector2f(WINDOW_RESOLUTION.x/2, WINDOW_RESOLUTION.y/2));
					start_button.addSprite(MediaBucket.getTexture("Start2"));
					start_button.addSprite(MediaBucket.getTexture("Start3"));
					start_button.setPosition(sf::Vector2f(WINDOW_RESOLUTION.x/2, WINDOW_RESOLUTION.y/2), -1);
	
	Sprite			firecan_icon;
					firecan_icon.setTexture(MediaBucket.getTexture("firecan_icon"));
					FloatRect firecan_icon_size = firecan_icon.getLocalBounds();
					firecan_icon.setOrigin(firecan_icon_size.width/2, firecan_icon_size.height/2);
					firecan_icon.setPosition(Vector2f(firecan_icon_size.width/2, WINDOW_RESOLUTION.y-firecan_icon_size.height/2));
	intro();
	
	while(app.isOpen())
	{
		while(app.pollEvent(event))
		{
			if(event.type == Event::KeyPressed) {
				if(event.key.code == Keyboard::Escape) {
					app.close();
				}
			}
			if(event.type == Event::Closed) {
				app.close();
			}
			if(event.type == Event::MouseButtonPressed && start_button.isClicked()) {

			}
		}
	
		app.clear(Color::White);
		app.draw(start_button);
		app.draw(firecan_icon);
		app.display();
	}
}
Esempio n. 14
0
void GameProcess(RenderWindow & window, Font & font, bool &isWin, bool &isLose)
{
	Clock clock;
	Board board;
	Ball ball;
	list<Brick*> bricks;
	iniGameObj(board, ball, bricks, WINDOW_SIZE);
	Event event;
	bool isPause = false;
    
	while (window.isOpen() && (!isWin) && (!isLose))
	{   
		float time = float(clock.restart().asMicroseconds());
		time = time / COEF_SPEED_GAME;
		if (isPause)
		{
			time = 0;
			isPause = false;
		}

		while (window.pollEvent(event))
		{
			if (event.type == Event::Closed)
				window.close();
			if (Keyboard::isKeyPressed(Keyboard::Left))
			{
				board.dir = LEFT;
			}
			else if (Keyboard::isKeyPressed(Keyboard::Right))
			{
				board.dir = RIGHT;
			}
			else
			{
				board.dir = NONE;
			}
			if (Keyboard::isKeyPressed(Keyboard::Space))
			{
				ball.inBoard = false;
			}
			if (Keyboard::isKeyPressed(Keyboard::Escape))
			{
				window.close();
			}
			if (Keyboard::isKeyPressed(Keyboard::P))
			{
				isPause = true;
			}

		}
		if (window.isOpen())
		{
			if (isPause)
			{
				PauseMenu(window, font);
			}
			else
			{
				update(board, time, WINDOW_SIZE);
				if (ball.inBoard)
				{
					MoveBallInBoard(ball, board, time);
				}
				else
				{
					CollisionAndMove(ball, bricks, board, time, WINDOW_SIZE);
				};
				UpdateList(bricks);

				window.clear();
				window.draw(*(board.sprite));
				window.draw(*(ball.sprite));
				RenderList(bricks, window);
				window.display();

				if (bricks.size() == 0)
				{
					isWin = true;
				}
				if (ball.sprite->getPosition().y + ball.sprite->getRadius() >= WINDOW_SIZE.y)
				{
					isLose = true;
				}
			}
		}
	}
	DispolseGameObj(&board, &ball, bricks);
}
Esempio n. 15
0
int menu_proc(RenderWindow & win){
    int status[3] = {CHOSE_PERSON, LOAD_SAVE_GAME, EXIT};
    Texture t_fon;
    t_fon.loadFromFile("Labelmenu1.png");
    Sprite s_fon;
    s_fon.setTexture(t_fon);
    Font font;
    font.loadFromFile("GoodDog.otf");
    //Text text("text", font);
    char text[3][15] = {"New Game", "Load Game", "Exit"};
    Text t[3];
    Color pink(254, 137, 245);
    Color yellow(255, 214, 136);
    for(int i = 0; i < 3; i++){
        t[i].setString(text[i]);
        t[i].setFont(font);
        t[i].setCharacterSize(100);
        t[i].setPosition(190, i*90+160);
        t[i].setColor(pink);
    }

    int cur = 0;
    t[cur].setColor(yellow);
    bool IsKeyPressedOneTime = false;


    while (win.isOpen()){
        Event event;
        while (win.pollEvent(event)){
            if (event.type == sf::Event::Closed || Keyboard::isKeyPressed(Keyboard::Escape)){
                win.close();
            }
        }
        if(Keyboard::isKeyPressed(Keyboard::Down) && !IsKeyPressedOneTime){
            IsKeyPressedOneTime = true;
            t[cur].setColor(pink);
            if(cur < 2)
                cur++;
            t[cur].setColor(yellow);

        }
        else if(Keyboard::isKeyPressed(Keyboard::Up) && !IsKeyPressedOneTime){
            IsKeyPressedOneTime = true;
            t[cur].setColor(pink);
            if(cur > 0)
                cur--;
            t[cur].setColor(yellow);
        }
        else if(Keyboard::isKeyPressed(Keyboard::Return)){
            break;
        }
        win.clear();
        win.draw(s_fon);

        for(int i = 0; i < 3; i++)
            win.draw(t[i]);
        win.display();
        Sleep(100);
        IsKeyPressedOneTime = false;
    }
    return status[cur];
}
Esempio n. 16
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();
    }
}
Esempio n. 17
0
int lavelMap_proc(Game * game, RenderWindow & win){
    const int num = 4;
    int pos[num][2] = {{250, 567}, {305, 535}, {358, 505}, {408, 474}};

    Image i_pod;
    i_pod.loadFromFile("podsvet.png");
    i_pod.createMaskFromColor(Color::White);
    Texture t_fon, t_pod, t_p;
    t_p.loadFromFile(game_getNameSprite(game));
    t_pod.loadFromImage(i_pod);
    t_fon.loadFromFile("lavel_map.png");
    Sprite s_fon, s_pod, s_p;
    s_p.setTexture(t_p);
    s_p.setTextureRect(IntRect(40, 0, 40, 55));
    s_pod.setTexture(t_pod);
    s_fon.setTexture(t_fon);
    Font font;
    font.loadFromFile("GoodDog.otf");
    Color pink(255, 0, 128);
    Color blue(63, 200, 210);
    Text text("Lavel map", font);
    text.setCharacterSize(90);
    text.setPosition(200, 0);
    text.setColor(pink);
    bool IsKeyPressedOneTime = false;
    int cur = 0;
    while (win.isOpen()){
        Event event;
        while (win.pollEvent(event)){
            if (event.type == sf::Event::Closed || Keyboard::isKeyPressed(Keyboard::Escape)){
                win.close();
            }
        }
        if(Keyboard::isKeyPressed(Keyboard::Right) && !IsKeyPressedOneTime){
            IsKeyPressedOneTime = true;
            if(cur < num-1)
                cur++;
        }
        else if(Keyboard::isKeyPressed(Keyboard::Left) && !IsKeyPressedOneTime){
            IsKeyPressedOneTime = true;
            if(cur > 0)
                cur--;
        }
        else if(Keyboard::isKeyPressed(Keyboard::Return)){
            game_setCurLavel(game, cur);
            break;
        }
        else if(Keyboard::isKeyPressed(Keyboard::BackSpace)){
            return MAIN_MENU;
        }
        s_p.setPosition(pos[cur][0]+7, pos[cur][1]-38);
        s_pod.setPosition(pos[cur][0], pos[cur][1]);
        win.clear();
        win.draw(s_fon);
        win.draw(s_pod);
        win.draw(text);
        win.draw(s_p);
        win.display();
        Sleep(100);
        IsKeyPressedOneTime = false;
    }
    return LAVEL;

}
Esempio n. 18
0
int main()
{
    // Creates the window to show your game
    RenderWindow *window;
    window = new RenderWindow(VideoMode(800, 600),"Ping Pong");
    window->setFramerateLimit (25);

    Sprite *background = new Sprite(); // a pointer for sprite
    Texture bg; // bgtex to store the texture

	if(!bg.loadFromFile("assets/background.png")) // Loads image as texture. Image must at least be 610 x 600
		std::cout<<"\nError loading image";
	else
		background->setTexture (bg);   // you set the texture to the sprite

	// Use setTextureRect() function to set the texture to some of the window
	background->setTextureRect (IntRect (0, 0, 610, 600));

    //Initialize the game objects
    onCreate ();

    // The Game Loop

    while (window->isOpen ())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        Event event;
        while (window->pollEvent (event))
        {
            //Window is closed or 'Esc' key is pressed
            if (event.type == Event::Closed || (event.type == Event::KeyPressed && event.key.code == Keyboard::Escape))
                window->close ();
        }

		//checks User input
        InputHandler (window);

		//update positions,scores etc.
        GameUpdate ();

		//perform AI operations
       	AIOperation ();

        //Clears the window every frame to render updated positions. MUST DO
        window->clear (sf::Color::White);

	    //Draw the background image
		window->draw (*background);

        //Draw everything else here
        Display (window);

		//Check score
		ScoreManager (window);

		if (ResultManager (window) ) onEnd ();

		//Display everything on the Window
        window->display();
    }

	//free memory
	delete background;
	delete window;

    return 0;
}
Esempio n. 19
0
bool playing(RenderWindow &window,Clock &clock, PLAYER &Player, std::list<Entity*>::iterator &it, std::list<Entity*> &entities,  Level &lvl, int &levelNumber)
{
	init_sounds sound;
	init_texture texture;

	PlayerScores plScores;

	if (levelNumber == 1 || levelNumber == 2)
	{
		sound.musicInGame.play();
		sound.musicInGame.setLoop(true);
	}
	else {
		sound.musicInGame.stop();
		sound.levelThird.play();
		sound.levelThird.setLoop(true);
	}

	float attack_timer = 0;
	int dead_enemy = 0;
	int bossHp = 200;
	bool playDeadSound = true;

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

		time = time / 500;
		if (time > 40) time = 40;

		Event event;
		while (window.pollEvent(event))
		{
			if (event.type == Event::Closed)
				window.close();
		}
		
		if (!Player.life || Player.isWin) 
		{
			
			if (Keyboard::isKeyPressed(Keyboard::Tab)) { levelNumber = 0; return true;  }
		
			if (Keyboard::isKeyPressed(Keyboard::Escape)) { return false; }
			
		}
		if ((dead_enemy == 8 || dead_enemy >= 8) && levelNumber == 1) { return true; }
		
		if (Player.levelNumber == 1) { return true; }
		

		checking_key(Player, sound.saber, time, attack_timer);
		
		plScores.update(Player.Health, Player.mana, bossHp);

		Player.update(time);

		is_enemy_alive(it, entities, time, lvl, texture.anim_mana, dead_enemy, sound.deathClon, sound.deathDroid);

		if (Player.life == true)	

		for (it = entities.begin();it != entities.end();it++)
		{
			player_sup_attack(it, Player, texture.anim_light, entities, lvl, time);

			definition_of_the_enemy(it, Player, texture.anim_bullet, entities, lvl, time, sound.shoot);

			definition_of_the_platform(it, Player, entities, lvl, time);

			take_bonus(it, Player, lvl, levelNumber);
		
			if (((*it)->Name == "enemy_obiwan"))
			{
				if ((*it)->Health <= 0 && playDeadSound)
				{
					playDeadSound = false;
					sound.levelThird.stop();
					sound.deadObi.play();
				}
				else bossHp = (*it)->Health;
			}
			if ((*it)->Health <= 0) continue;			
		}
		else { if (Player.isPlaySound) { sound.musicInGame.stop(); sound.levelThird.stop(); sound.deadEnakin.play(); Player.isPlaySound = false; } }

		getPlayerCoordinateForView(Player.x, Player.y, window, levelNumber);

		draw_game(window, lvl, it, entities, Player, plScores, levelNumber);

	}
	return 0;
}
Esempio n. 20
0
File: mines.cpp Progetto: jokoon/eio
//map<color, Color> colors = {
//    { Black, Color::Black },
//    { White, Color::White },
//    { Red, Color::Red },
//    { Green, Color::Green },
//    { Blue, Color::Blue },
//    { Yellow, Color::Yellow },
//    { Magenta, Color::Magenta },
//    { Cyan, Color::Cyan },
//    { Transparent, Color::Transparent },
//    { Orange, Color(255, 128, 0) }
//};
////////////////////////// this returns a lambda //////////////////////////
function<void()>
////////////////////////// TYPE APP NAME ON LINE BELOW //////////////////////////
mine_solver

(RenderWindow&window, ui &UI) {
    return [&window, &UI]() {
#ifndef COMMON_INITS
        //void smoothmouse(RenderWindow&window, ui &UI){

        // tidy code organization, here we predeclare methods just like a header would, it's redundant but necessary
        function<void()> draw, loop, init, update;
        function<void(Vec2 pos)> mousemoved;
        function<void(sf::Mouse::Button button)> mouseclick, mouserelease;
        function<void(Event&e)> treatotherevent;
        function<void(Keyboard::Key k)> treatkeyevent;

        // we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway.
        Texture cursor_tx;
        Sprite cursor;
        configfile cfg;
        cfg.init("bedlab.cfg");
        Color background = cfg.getvar<Color>("background");
        if (!cursor_tx.loadFromFile(cfg.getstr("cursor")))
            cout << "did not load cursor" << endl;
        cursor.setTexture(cursor_tx);
        cursor.setOrigin(3, 3);
        window.setMouseCursorVisible(false);
        Vec2 mpos;
        bool leftclicked = false, rightclicked = false;

        // view and zoom
        View view, ui_view;
        ui_view = view = window.getDefaultView();
        float zoomlevel = 1;
        Vec2 mpos_abs;
#endif // COMMON_INITS
        // ************************ CODE BEGIN ************************

        barstack bst(FONT, FONTSIZE);
        slider_finder sl;


        randgenfloat cell_rnd(0, 16);
        //grd.
        vector<string> mines_str =
        {
            "               ",
            "   21114X411   ",
            "   3X22XX212   ",
            "   X3--4433X   ",
            "   23--4XX3X   ",
            "   1X4---433   ",
            "   12X4--4X2   ",
            "   123X3XX3X   ",
            "   2X2122221   ",
            "               "

        };

        int w = mines_str[0].length();
        int h = mines_str.size();
        vector<int> mine_states(h*w);
        grid grd;
        grd.screen_init(Vec2u(window.getSize()), Vec2u( w,h ), true);


        /*
        1-8: surrounding mines
        0 no mine, "clear"
        -1: unknown
        -2 mine
        
        */
        map<char, int> lookup =
        {
            { '-',-1 },
            { 'X',-2 },
            { ' ',0 }
        };


        int i = 0;
        logfile lg("minelog.txt");
        lg.logw(to_str("i", "j", "index", "value"));

        for (auto&a : mines_str)
        {
            int j = 0;
            for (auto&b : a)
            {
                int value = -10;

                //value =
                //    lookup.count(b) ?
                //    lookup[b]
                //    : (b > '0' || b <= '9') ?
                //        int(b - '0')
                //        : value;
                //msg(value);
                if (lookup.count(b)) value = lookup[b];
                else if (b > '0' || b <= '9')value = int(b - '0');

                int index = getat(j, i, w);
                mine_states[index] = value;

                //msgm(i,j,index, value);
                lg.logw(to_str(i,j,index, value));
                ++j;
            }
            ++i;
        }

        map<int, Color> mine_colors =
        {
            { -2,Color::Red },
            { -1,Color::Cyan },
            { 0,Color::Black }

        };
        msg(mine_states);
        i = 0;
        for (auto&a : mine_states)
        {
            if(a > 0)
                grd.texts[i].setString(to_str(a));
            else
                grd.cells[i].setFillColor(mine_colors[a]);
            //grd.texts2[i].setString(to_str(i));
            //grd.texts3[i].setString(to_str(getat(i,w)));
            ++i;
        }

        auto analyse = [&mine_states, w, h, &grd]()
        {
            vector<Vec2i> offsets = {
                { -1,-1 },
                { 1,-1 },
                { -1,1 },
                { 1,1 },
                { 0,-1 },
                { -1,0 },
                { 0,1 },
                { 1,0 }
            };

            int i = 0;
            for (auto&a : mine_states)
            {
                auto pos = getat(i, w);
                int unknown = 0, is_mine = 0;
                for (auto&off : offsets)
                {
                    auto cell = pos + off;
                    int cell_index = getat(cell,w);
                    if (cell_index < 0
                        || cell_index >= mine_states.size()
                        || cell.x < 0
                        || cell.x > w) continue;
                    switch (mine_states[cell_index])
                    {
                        case -1: ++is_mine; break; //unknown
                        case -2: ++unknown; break; //mine
                    }
                }
                int mine_left = a - is_mine;
                float prob = mine_left / unknown;
                ++i;
            }
        };
        
        auto nearest_pt = mkcircle({ 0, 0 }, Color::Transparent, 10);
        nearest_pt.setOutlineThickness(2);
        // ************************ INITS END **********************
        //then we actually define the functions, note how all function captures the local context by reference
#ifndef LOOP_LAMBDAS
        draw = [&]() {
            window.setView(view);
            // object draw, AFTER normal view

            //////////////// obj draw START ////////////////
            for (auto&a : glob_pts)window.draw(a);
            for (auto&a : glob_rects)window.draw(a);
            for (auto&a : glob_vert)window.draw(a);
            for (auto&a : glob_texts)window.draw(a);
            window.draw(nearest_pt);
            grd.draw(window);


            //////////////// obj draw END ////////////////
            // UI draw, AFTER ui view and BEFORE other draw
            window.setView(ui_view);
            bst.draw(window);
            // nothing after here please
            UI.draw(window);
            window.draw(cursor);
        };
        update = [&]() {

        };
        treatkeyevent = [&](Keyboard::Key k) {
            switch (k)
            {
            case Keyboard::BackSpace:
                glob_pts.clear();
                glob_texts.clear();
                glob_rects.clear();
                glob_vert.clear();
                break;
            case Keyboard::Space:

                break;
            case Keyboard::Q: break;
            }
        };
        mousemoved = [&](Vec2 pos) {
            cursor.setPosition(pos);
            if (leftclicked) sl.mouse_callback(pos);
        };
        mouseclick = [&](sf::Mouse::Button button) {
            if (button == Mouse::Button::Left) leftclicked = true;
            if (button == Mouse::Button::Right) rightclicked = true;
        };
        mouserelease = [&](sf::Mouse::Button button) {
            if (button == Mouse::Button::Left) leftclicked = false;
            if (button == Mouse::Button::Right) rightclicked = false;
            sl.release();
        };
        loop = [&]() {
            while (window.isOpen())
            {
                sf::Event event;
                while (window.pollEvent(event))
                {
                    switch (event.type)
                    {
                    case sf::Event::KeyPressed:
                        if (event.key.code == sf::Keyboard::Escape)
                            window.close();
                        treatkeyevent(event.key.code);
                        break;
                    case sf::Event::Closed:
                        window.close();
                        break;
                    case sf::Event::MouseButtonPressed:
                        mouseclick(event.mouseButton.button);
                        break;
                    case sf::Event::MouseButtonReleased:
                        mouserelease(event.mouseButton.button);
                        break;
                    case sf::Event::MouseMoved:
                        mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
                        mousemoved(mpos);
                        break;
                    default:
                        treatotherevent(event);
                        break;
                    }
                }

                window.clear(background);
                update();
                draw();
                window.display();
            }
        };
        treatotherevent = [&](Event&e) {
            if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta)
            {
                mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);

                //view = window.getView();
                if (e.mouseWheel.delta < 0)
                {
                    zoomlevel *= 2.f;
                    view.setSize(view.getSize()*2.f);
                    view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
                    //view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
                }
                if (e.mouseWheel.delta > 0)
                {
                    zoomlevel *= 0.5;
                    view.setSize(view.getSize()*.5f);
                    view.setCenter(.5f*(view.getCenter() + mpos_abs));
                    //view.setCenter(.5f*(view.getCenter() + mpos_abs));
                }
                window.setView(view);
            }
        };
        loop();
#endif // LOOP_LAMBDAS
    };
}
Esempio n. 21
0
void mainLevel(RenderWindow &window)
{
	//>>>>>>>>>>>>>>>---Level---<<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Level lvl;
	 lvl.LoadFromFile("map.tmx");

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

	Texture texture2; 
	texture2.loadFromFile("images/levelShad.png");
	Sprite level2(texture2);

	Texture texture3;
	texture3.loadFromFile("images/level12.png");
	Sprite level3(texture3);
	//>>>>>>>>>>>>>>>>---Music---<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Music mainSong;
	 Music skyrim, muse, bathMus;
	 bathMus.openFromFile("music/bath.ogg");
	 Object mus = lvl.GetObject("muse");
	 muse.openFromFile("music/synd.ogg"); muse.setVolume(100);
	 skyrim.openFromFile("music/skyrim.ogg"); skyrim.setVolume(100);
	 mainSong.openFromFile("music/level1.ogg");
	 mainSong.play();
	 mainSong.setLoop(true);
	 mainSong.setVolume(75);

	 //>>>>>>>>>>>>>>>>---Create a cat---<<<<<<<<<<<<<<<<<<<
	 Object player = lvl.GetObject("cat");
	 Object fish = lvl.GetObject("fish");
	 Object mo = lvl.GetObject("mouse");
	 Object ob = lvl.GetObject("catPlace");


	 Player cat("cat.png", lvl, 68, 429, 60, 120, player.rect.left,  player.rect.top, ELSE);
	 
	 Clock clock;
	 Clock gameTimeClock;
	 int sinkCnt = 0;

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

	SoundBuffer buf, buf3;
	buf.loadFromFile("music/steklo.ogg");
	buf3.loadFromFile("music/mouse.ogg");
	Sound glass; Sound mouseS;
	glass.setBuffer(buf); glass.setVolume(100);
	mouseS.setBuffer(buf3);
	
	 //Objects
	 Furniture posters("tayles1.png",  160, 660, 210, 250, 280, 215, POSTERS);
	 Furniture bed("tayles1.png", 420, 80, 280, 310, 250, 440, ELSE); 
	 Furniture toys("tayles1.png", 120, 470, 180, 150, 220, 545, TOYS);
	 Furniture upShelf("tayles1.png", 700, 652.5, 120, 97.5, 350, 83, SHELF);
	 Furniture cabinet("tayles1.png", 75, 40, 250, 350, 605, 305, CABINET); 
	 Furniture mop("tayles1.png", 515, 785, 165, 241, 587, 385, MOP); 
	 Furniture flower("tayles1.png",780, 65, 170, 330, 147, 285, ELSE);
	 Furniture ball("tayles1.png", 905, 615, 40, 55, 357, 190, BALL); 
	 Furniture books("tayles1.png", 860, 735, 125, 80, 290, 187, BOOKS); 
	 Furniture brokenBall("tayles1.png",920, 540, 90, 42, 430, 430, ELSE); 
	 Furniture key("tayles1.png", 1, 1, 25, 25, 430, 425, KEY);
	 Furniture cabinetEnd("cabinet.png", 20, 50, 270, 350, 590, 290, ELSE); 
	 Furniture girl("girlHair.png", 1,1, 96, 45, 1075, 350, ELSE);
	 
	 Furniture door("tayles2.png", 0, 560, 80, 340, 870, 350, ELSE);
	 Furniture puddle("tayles1.png",789, 1000, 204, 75, 1057, 559, ELSE);
	 Furniture brokenLight("tayles2.png", 10, 110, 50, 70, 795, 430, ELSE);
	 Furniture light("tayles2.png", 20, 20, 35, 70, 220, 565, ELSE);
	 Furniture bath("tayles2.png", 80, 50, 320, 380, 1010, 330, BATH);
	 Furniture openBath("bathr.png", 264, 79, 339, 369, 1015, 315, ELSE);
	 Furniture carpet("tayles2.png", 100, 500, 100, 140, 870, 530, ELSE);
	 Furniture mirror("tayles2.png", 90, 700, 110, 290, 1200, 300, ELSE);
	 Furniture sink("tayles2.png", 290, 440, 150, 240, 1190, 450, SINK);
	 Furniture sinkWater("bathr.png", 22, 180, 197, 427, 1200, 540, ELSE);
	 Furniture mou("mouse.png",  2, 21, 32, 25, mo.rect.left, mo.rect.top, ELSE);
	 
	 
	 std::list<Furniture> fList;
	 std::list<Furniture>::iterator it;
	 fList.push_back(posters);
	 fList.push_back(toys);
	 fList.push_back(upShelf);
	 fList.push_back(cabinet);
	 fList.push_back(mop);
	 fList.push_back(ball);
	 fList.push_back(books);
	 fList.push_back(key);
	 fList.push_back(puddle);
	 fList.push_back(brokenLight);
	 fList.push_back(bath);
	 fList.push_back(sink);
	 for(it = fList.begin(); it != fList.end(); it++){
		 it->setSub((void *)&it, writeMess);
	 }

	 int cntMeow = 1, cntGame = 0, click = 0, clickBath = 1, clickSink = 1;
	 bath.isPlayed = true;
	 sink.isPlayed = true;


	  while (window.isOpen())
    {
		
		float time = clock.getElapsedTime().asMicroseconds();
		float sinkTime = gameTimeClock.getElapsedTime().asSeconds();
		if(clickSink < 2)
			gameTimeClock.restart();
		clock.restart();
		time = time/500;
		Vector2i pos = Mouse::getPosition(window);
		
		Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();

			if (event.type == Event::MouseButtonPressed)
				if (event.key.code == Mouse::Left){

					if (fish.rect.contains(pos.x, pos.y) && key.isPlayed == true){
						mainSong.stop();
						finish();
						window.close();
					}
					if (cat.sprite.getGlobalBounds().contains(pos.x, pos.y))
					{
						cntMeow++;
						if(cntMeow == 5)
						{
							meow2.play();
							cntMeow = 0;
						}
						else
							meow1.play();
					}
					 
					toys.trueMove(pos);
					if(light.isPlayed == false) light.trueMove(pos);
					if(ball.isPlayed == true && books.isPlayed == true) key.trueMove(pos);
					if(puddle.isPlayed == true) mop.trueMove(pos);
					click = light.clickedThings(pos);
					clickBath = bath.clickedThings(pos);
					clickSink = sink.clickedThings(pos);


					if (upShelf.sprite.getGlobalBounds().contains(pos.x, pos.y)){
						skyrim.play();
					}
					if (mus.rect.contains(pos.x, pos.y)){
						muse.play();
					}
					if (girl.sprite.getGlobalBounds().contains(pos.x, pos.y) && cat.room == 2){
						mainSong.pause();
						gameOver();
						mainSong.play();
					}
					if(mou.isPlayed == false)
						{
							if (mou.sprite.getGlobalBounds().contains(pos.x, pos.y))
							{
								mainSong.pause();
								mouseS.play();
								//gameRunning();
								mou.isPlayed = true;
								mainSong.play();
							}
						}

						if(books.isPlayed == false)
						{
							if (books.sprite.getGlobalBounds().contains(pos.x, pos.y))
							{
								mainSong.pause();
								MiniGame_Books();
								books.isPlayed = true;
								mainSong.play();
							}
						}
				}
					
			if (event.type == Event::MouseButtonReleased)
				if (event.key.code == Mouse::Left){
					toys.isMove = false;
					key.isMove = false;
					if(light.isPlayed == false) light.isMove = false;
					 mop.isMove = false;
				}
		}
		if(sinkTime > 5 && clickSink == 2) puddle.isPlayed = true;

		if(clickBath == 2 && cat.room == 2)
			bathMus.play();

		if(click == -1){}
		else if(click == 1 || click == 2)
			cat.room = click;
		toys.intersect("toys",lvl); toys.move(pos); 
		if(mop.isPlayed == false)
		{
			mop.intersect("mop", lvl);
			mop.move(pos);
		}
		if(light.isPlayed == false) 
		{
			light.intersect("light", lvl);
			light.move(pos);
		}
		if(ball.isPlayed == true && books.isPlayed == true){
			if(mop.isPlayed == true)
				key.intersect("key", lvl);
			if(key.isPlayed == false)
				key.move(pos);
		}
		if(ball.isPlayed == false && books.isPlayed == true){
			if(cat.sprite.getGlobalBounds().intersects(ob.rect))
			{
				if(cntMeow == 0)
				{
					ball.falling(event, window, pos, lvl, time);
					glass.play();
					ball.isPlayed = true;
					ball.intersect("ball", lvl);
				}
			}
		}
        
      
		cat.Update(time);

		window.clear(Color::Black);
		lvl.Draw(window);
		if(cat.room == 0)
			window.draw(level);
		if(cat.room == 1)
			window.draw(level2); 
		if(cat.room == 2)
			window.draw(level3);
			
		window.draw(posters.sprite);
		window.draw(bed.sprite);
		if(key.isPlayed == true)
			window.draw(cabinetEnd.sprite);
		else
			window.draw(cabinet.sprite);
		window.draw(upShelf.sprite);
		window.draw(flower.sprite);
		if(ball.isPlayed == false)
			window.draw(ball.sprite);
		else
		{
			window.draw(brokenBall.sprite);
			window.draw(key.sprite);
		}
		window.draw(books.sprite);

		
		if(mou.isPlayed == false){
			window.draw(mou.sprite);
		}
		else
			window.draw(light.sprite);
		window.draw(toys.sprite);


		if(cat.room == 2){
				
			 if(clickBath == 2){
				window.draw(girl.sprite);
				window.draw(openBath.sprite);
			 }
			 else
				 window.draw(bath.sprite);
			window.draw(mirror.sprite);

			 if(clickSink == 2)
				window.draw(sinkWater.sprite);
			 else
				 window.draw(sink.sprite);

			 if(puddle.isPlayed == true && mop.isPlayed == false)
				window.draw(puddle.sprite);
		}

		if(cat.room == 1 || cat.room == 2){
			if(light.isPlayed == false)
			window.draw(brokenLight.sprite);
			window.draw(carpet.sprite);
			window.draw(door.sprite);
		}
		if(mop.isPlayed == false)
			window.draw(mop.sprite);
		window.draw(cat.sprite);

		for(it = fList.begin(); it != fList.end(); it++)
			{
				if(it->sprite.getGlobalBounds().contains(pos.x, pos.y))
				{
					if(it->f.cb_fn != NULL)
					{
						cb_fn fn;
						fn = (cb_fn)it->f.cb_fn;
						fn(&window, it->type, &pos);
					}
				}
			}
		
		window.display();
    }

}
bool StartGame(RenderWindow & window, Game & game)
{
	Level lvl;
	lvl.LoadFromFile(GetLevelNumb(game));
	Image image;
	Texture texture;
	if (!image.loadFromFile("images/lvl1.png"))
		cout << "Error loading image from file " << endl;
	image.createMaskFromColor(Color(0, 128, 0));
	if (!texture.loadFromImage(image))
		cout << "Error loading texture from image " << endl;

	Sprite heartSprite;
	heartSprite.setTexture(texture);
	heartSprite.setTextureRect(IntRect(395, 151, 54, 46));
	heartSprite.setScale(0.3f, 0.3f);

	Sprite lifeSprite;
	lifeSprite.setTexture(texture);
	lifeSprite.setTextureRect(IntRect(457, 149, 29, 29));
	lifeSprite.setScale(0.8f, 0.8f);

	Font font;
	font.loadFromFile("fonts/pixel.ttf");
	Text text("", font, 25);

	game.graphic.statistic.heart = heartSprite;
	game.graphic.statistic.life = lifeSprite;
	game.graphic.text = text;
	game.isPause = true;
	game.restart = false;

	vector <Enemy*>  enemies;
	std::vector<Object> e = lvl.GetObjects("easyEnemy");
	for (Object i : e)
		enemies.push_back(new Enemy(texture, "easyEnemy", i.rect.left, i.rect.top, 53, 28));

	e = lvl.GetObjects("flyEnemy");
	for (Object i : e)
		enemies.push_back(new Enemy(texture, "flyEnemy", i.rect.left, i.rect.top, 38, 36));
	
	
	if (lvl.IsExist("trap"))
	{
		e = lvl.GetObjects("trap");
		for (Object i : e)
			enemies.push_back(new Enemy(texture, "trap", i.rect.left, i.rect.top, 32, 18));
	}


	vector <Portal*> portals;
	vector <Bullet*> bullets;
	vector <Object> objects = lvl.GetAllObjects();
	Clock clock;

	SoundBuffer shootBuffer;
	shootBuffer.loadFromFile("sound/shoot.wav");
	Sound shoot(shootBuffer);

	SoundBuffer portalBuffer;
	portalBuffer.loadFromFile("sound/portal.wav");
	Sound portal(portalBuffer);

	SoundBuffer teleportBuffer;
	teleportBuffer.loadFromFile("sound/teleport.wav");
	Sound teleport(teleportBuffer);

	SoundBuffer damageBuffer;
	damageBuffer.loadFromFile("sound/damage.wav");
	Sound damage(damageBuffer);

	SoundBuffer deathBuffer;
	deathBuffer.loadFromFile("sound/damage.wav");
	Sound gameOver(deathBuffer);

	Music music;
	music.openFromFile("sound/musicGame.ogg");
	music.play();

	Object playerObject = lvl.GetObject("player");
	Player player(texture, "Player1", playerObject.rect.left, playerObject.rect.top, 32, 32);
	player.health = game.health;
	player.heart = game.hearts;

	while (window.isOpen() && (!game.restart))
	{
		float time = float(clock.getElapsedTime().asMicroseconds());
		clock.restart();
		time = time / 800;
		Event event;
		Vector2i pixelPos = Mouse::getPosition(window);
		Vector2f pos = window.mapPixelToCoords(pixelPos);
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed || (Keyboard::isKeyPressed(Keyboard::Escape) && game.isPause))
			{
				window.close();
				game.restart = false;
			}
			if (event.type == Event::MouseButtonPressed)
			{
				pos.y = float(player.teleportY);
				if ((event.key.code == Mouse::Left) && (player.doesOpenPortal))
				{
					CreatePortal(portals, game, "blue", pos, texture);
					portal.play();
				}
				else if (event.key.code == Mouse::Right && (player.doesOpenPortal))
				{
					CreatePortal(portals, game, "yellow", pos, texture);
					portal.play();
				}
			}
			if (player.isTeleporting)
			{
				TeleportPlayer(player, portals);
				teleport.play();
			}
			if (Keyboard::isKeyPressed(Keyboard::Return))
			{
				game.isPause = false;
			}
			if (Keyboard::isKeyPressed(Keyboard::P))
			{
				game.isPause = true;
			}
			if (Keyboard::isKeyPressed(Keyboard::Tab) && game.isPause) 
			{ 
				game.restart = true; 
			}
		}
		if (player.isExit)
		{
			if (game.isEndLevel)
			{
				game.isPause = true;
			}
			else
			{
				game.level++;
				game.restart = true;
				game.health = player.health;
				game.hearts = player.heart;
			}
		}
		for (auto *e : enemies)
		{
			if ((*e).name == "flyEnemy" && (*e).isShoot)
			{
				CreateBullet(bullets, (*e).GetRect(), player, texture);
				shoot.play();
			}
		}
		EntitiesIntersection(player, enemies, portals, bullets, damage);
		if (player.alive)
		{
			setPlayerCoordinateForView(game.camera, player.GetPos().x, player.GetPos().y);
		}
		if (!game.isPause)
		{
			UpdateEnemies(objects, enemies, time, player);
			UpdatePortals(portals, time);
			UpdateBullets(objects, bullets, time);
			player.Update(objects, time, pos, game.portalH);
		}
		window.setView(game.camera);
		window.clear();
		lvl.Draw(window);
		DrawEnemies(window, enemies);
		DrawPortals(window, portals);
		DrawBullets(window, bullets);
		DrawStatistic(window, &game, player, game.camera);
		window.draw(player.sprite);
		DrawAllMessages(player, game, window);
		music.setLoop(true);
		window.display();
	}
	return game.restart;
}
Esempio n. 23
0
void Game::DoGameLoop(RenderWindow& window, GameMode & gameMode)
{
	parts = snake.ReturnParts();
	apple.SpawnNewApple(parts);
	Text text("", font, 30);
	text.setColor(Color::Green);
	while (window.isOpen())
	{
		window.clear();
		Event event;
		while (window.pollEvent(event))
			if (event.type == Event::Closed)
				window.close();

		switch (gameMode)
		{
		case GameMode::MENU:
			text.setString("Press Enter to play");
			text.setPosition(180, 220);
			window.draw(text);
			if (Keyboard::isKeyPressed(Keyboard::Return))
			{
				snake.ResetSnake();
				gameMode = GameMode::PLAY;
			}
			break;
		case GameMode::END:
			text.setString("GAME OVER");
			text.setPosition(230, 180);
			window.draw(text);
			current = snake.ReturnSize();
			if (score)
			{
				playerScoreString.str("");
				playerScoreString << (current - 1) * 10;
				score = false;
			}
			text.setString("SCORE: " + playerScoreString.str());
			text.setPosition(240, 250);
			window.draw(text);
			text.setString("Press Enter to restart");
			text.setPosition(160, 350);
			window.draw(text);
			if (Keyboard::isKeyPressed(Keyboard::Return))
			{
				snake.ResetSnake();
				gameMode = GameMode::PLAY;
			}

			break;
		case GameMode::PLAY:
			time = 0;
			while (time < TIME_STEP)
			{
				snake.ProcessEvents(window);
				time = clock.getElapsedTime().asMilliseconds();
			}

			if (time >= TIME_STEP)
			{
				clock.restart(); 

				snake.ProcessEvents(window);       
				snake.Tick();	
				snake.Update();                    

				parts = snake.ReturnParts();

				if (apple.CheckEventApple(parts))
				{
					snake.AddNewSnakePart();
				}
				if (snake.CheckGameOver())
				{
					gameMode = GameMode::END;
					score = true;
				}
				DrawMap(window, fieldSprite, blockSprite);
				snake.DrawSnake(window);
				apple.DrawApple(window);
			}
			break;
		}
		window.display();
	}
}
Esempio n. 24
0
function<void()>
////////////////////////// TYPE APP NAME ON LINE BELOW //////////////////////////
delaun_distr

(RenderWindow&window, ui &UI) {
	return [&window, &UI]() {
#ifndef COMMON_INITS
		//void smoothmouse(RenderWindow&window, ui &UI){

		// tidy code organization, here we predeclare methods just like a header would, it's redundant but necessary
		function<void()> draw, loop, init, update;
		function<void(Vec2 pos)> mousemoved;
		function<void(sf::Mouse::Button button)> mouseclick, mouserelease;
		function<void(Event&e)> treatotherevent;
		function<void(Keyboard::Key k)> treatkeyevent;

		// we don't have a class/interface/struct with data, everything is local to this function, like a classic stack that all programs are anyway.
		Texture cursor_tx;
		Sprite cursor;
		configfile cfg;
		cfg.init("bedlab.cfg");
		Color background = cfg.getvar<Color>("background");
		if (!cursor_tx.loadFromFile(cfg.getstr("cursor")))
			cout << "did not load cursor" << endl;
		cursor.setTexture(cursor_tx);
		cursor.setOrigin(3, 3);
		window.setMouseCursorVisible(false);
		Vec2 mpos;
		bool leftclicked = false, rightclicked = false;

		// view and zoom
		View view, ui_view;
		ui_view = view = window.getDefaultView();
		float zoomlevel = 1;
		Vec2 mpos_abs;
#endif // COMMON_INITS
		// ************************ CODE BEGIN ************************
		
		auto random_graph = [](int pick_count, float distrib_radius)
		{
			vector<pair<int,Vec2>> points;
			vector<pair<int, int>> graph;
			

			//float distrib_radius;// = cfg.getvar<float>("distrib_radius");

			paused_distr paus_distr(distrib_radius, 5, 321);
			//int winheight = cfg.getvar<Vec2i>("windowsize").y;
			//scaler scl(winheight*0.9f, { 0,0 });

			DelaunayTriangulation dela(1, 1);

			//int pick_count = cfg.getvar<int>("pick_count");
			for (int i = 0; i < pick_count; ++i)
			{
				Vec2 cand;
				int retcode = -1;
				do
				{
					retcode = paus_distr.pick5(cand);
				} while (retcode == 2);
				if (retcode != -1 && retcode != 0)
				{
					dela.AddPoint(Point(cand.x, cand.y));
					//glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
					//glob_pts.push_back(mkcircle(scl(cand), Color::White, 3.f));
					points.push_back({ points.size(),cand });
				}

			}
			//msg(glob_pts.size());
			for (auto&triangle : dela.triangles)
			{
				int
					a = triangle.get()->v[0],
					b = triangle.get()->v[1],
					c = triangle.get()->v[2];
				Point
					A = dela.points[a],
					B = dela.points[b],
					C = dela.points[c];
				if (
					A.x == 0 || A.x == 1
					|| A.y == 0 || A.y == 1
					|| B.x == 0 || B.x == 1
					|| B.y == 0 || B.y == 1
					|| C.x == 0 || C.x == 1
					|| C.y == 0 || C.y == 1
					)
				{
					continue;
				}

				graph.push_back({a,b});
				graph.push_back({b,c});
				graph.push_back({a,c});

				// those are the ones!
				//segment(scl(Vec2(A.x, A.y)), scl(Vec2(B.x, B.y)));
				//segment(scl(Vec2(C.x, C.y)), scl(Vec2(B.x, B.y)));
				//segment(scl(Vec2(A.x, A.y)), scl(Vec2(C.x, C.y)));

				//segment(Vec2(A.x, A.y), Vec2(B.x, B.y));
				//segment(Vec2(C.x, C.y), Vec2(B.x, B.y));
				//segment(Vec2(A.x, A.y), Vec2(C.x, C.y));
				//segment(pts[a], pts[b]);
				//segment(pts[a], pts[c]);
				//segment(pts[c], pts[b]);
			}
			return make_pair(points, graph);
		};


		float distrib_radius = cfg.getvar<float>("distrib_radius");

		paused_distr paus_distr(distrib_radius, 5, 321);
		int winheight = cfg.getvar<Vec2i>("windowsize").y;
		scaler scl(winheight*0.9f, { 0,0 });

		DelaunayTriangulation dela(1, 1);

		int pick_count = cfg.getvar<int>("pick_count");
		for(int i = 0; i < pick_count; ++i)
		{ 
			Vec2 cand;
			int retcode = -1;
			do
			{
				retcode = paus_distr.pick5(cand);
			} while (retcode == 2);
			if (retcode != -1 && retcode != 0)
			{
				dela.AddPoint(Point(cand.x, cand.y));

				//glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
				glob_pts.push_back(mkcircle(scl(cand), Color::White, 3.f));
			}

		}
        msg(glob_pts.size());
		for (auto&triangle : dela.triangles)
		{
			int
				a = triangle.get()->v[0],
				b = triangle.get()->v[1],
				c = triangle.get()->v[2];
			Point
				A = dela.points[a],
				B = dela.points[b],
				C = dela.points[c];
			if (
				A.x == 0 || A.x == 1
				|| A.y == 0 || A.y == 1
				|| B.x == 0 || B.x == 1
				|| B.y == 0 || B.y == 1
				|| C.x == 0 || C.x == 1
				|| C.y == 0 || C.y == 1
				) 
			{
				continue;
			}
			
			segment(scl(Vec2(A.x, A.y)), scl(Vec2(B.x, B.y)));
			segment(scl(Vec2(C.x, C.y)), scl(Vec2(B.x, B.y)));
			segment(scl(Vec2(A.x, A.y)), scl(Vec2(C.x, C.y)));
			//segment(Vec2(A.x, A.y), Vec2(B.x, B.y));
			//segment(Vec2(C.x, C.y), Vec2(B.x, B.y));
			//segment(Vec2(A.x, A.y), Vec2(C.x, C.y));
			//segment(pts[a], pts[b]);
			//segment(pts[a], pts[c]);
			//segment(pts[c], pts[b]);
		}

		barstack bst(FONT, FONTSIZE);
		slider_finder sl;
		size_t edit_mode = 1;

		// ************************ INITS END ************************
		//then we actually define the functions, note how all function captures the local context by reference
#ifndef LOOP_LAMBDAS
		draw = [&]() {
			window.setView(view);
			// object draw, AFTER normal view

			//Vec2 cand;
			//int retcode = -1;
			//do
			//{
			//	retcode = paus_distr.pick4(cand);
			//} while (retcode == 2);
			//if (retcode != -1 && retcode != 0)
			//{
			//	//glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
			//	glob_pts.push_back(mkcircle(scl(cand), Color::White, .5f));
			//}


			//////////////// obj draw START ////////////////
			for (auto&a : glob_pts)window.draw(a);
			for (auto&a : glob_rects)window.draw(a);
			for (auto&a : glob_vert)window.draw(a);
			for (auto&a : glob_texts)window.draw(a);
			//window.draw(nearest_pt);

			//////////////// obj draw END ////////////////
			// UI draw, AFTER ui view and BEFORE other draw
			window.setView(ui_view);
			bst.draw(window);
			// nothing after here please
			UI.draw(window);
			window.draw(cursor);
		};
		update = [&]() {

		};
		treatkeyevent = [&](Keyboard::Key k) {
			switch (k)
			{
			case Keyboard::BackSpace:
				glob_pts.clear();
				glob_texts.clear();
				glob_rects.clear();
				glob_vert.clear();
				break;
			case Keyboard::Space:

				break;
			case Keyboard::Q: break;
			}
		};
		mousemoved = [&](Vec2 pos) {
			cursor.setPosition(pos);
			if (leftclicked) sl.mouse_callback(pos);
		};
		mouseclick = [&](sf::Mouse::Button button) {
			if (button == Mouse::Button::Left) leftclicked = true;
			if (button == Mouse::Button::Right) rightclicked = true;
		};
		mouserelease = [&](sf::Mouse::Button button) {
			if (button == Mouse::Button::Left) leftclicked = false;
			if (button == Mouse::Button::Right) rightclicked = false;
			sl.release();
		};
		loop = [&]() {
			while (window.isOpen())
			{
				sf::Event event;
				while (window.pollEvent(event))
				{
					switch (event.type)
					{
					case sf::Event::KeyPressed:
						if (event.key.code == sf::Keyboard::Escape)
							window.close();
						treatkeyevent(event.key.code);
						break;
					case sf::Event::Closed:
						window.close();
						break;
					case sf::Event::MouseButtonPressed:
						mouseclick(event.mouseButton.button);
						break;
					case sf::Event::MouseButtonReleased:
						mouserelease(event.mouseButton.button);
						break;
					case sf::Event::MouseMoved:
						mpos = Vec2(event.mouseMove.x, event.mouseMove.y);
						mousemoved(mpos);
						break;
					default:
						treatotherevent(event);
						break;
					}
				}

				window.clear(background);
				update();
				draw();
				window.display();
			}
		};
		treatotherevent = [&](Event&e) {
			if (e.type == Event::MouseWheelMoved && e.mouseWheel.delta)
			{
				mpos_abs = window.mapPixelToCoords(Vec2i(mpos), view);

				//view = window.getView();
				if (e.mouseWheel.delta < 0)
				{
					zoomlevel *= 2.f;
					view.setSize(view.getSize()*2.f);
					view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
					//view.setCenter(interp(mpos_abs, view.getCenter(), 2.f));
				}
				if (e.mouseWheel.delta > 0)
				{
					zoomlevel *= 0.5;
					view.setSize(view.getSize()*.5f);
					view.setCenter(.5f*(view.getCenter() + mpos_abs));
					//view.setCenter(.5f*(view.getCenter() + mpos_abs));
				}
				window.setView(view);
			}
		};
		loop();
#endif // LOOP_LAMBDAS
	};
}
bool startGame (int & startLevel, RenderWindow & window, int & lives) {

    view.reset(FloatRect(0, 0, 700, 600));


    Level lvl;

    switch (startLevel) {
    case 1:
        lvl.LoadFromFile("level1.tmx");
        break;
    case 2:
        lvl.LoadFromFile("level2.tmx");
        break;
    case 3:
        lvl.LoadFromFile("level3.tmx");
        break;
    }
    //lvl.LoadFromFile("level1.tmx");

    SoundBuffer coinBuffer;
    coinBuffer.loadFromFile("sounds/coin.wav");
    Sound coinSound;
    coinSound.setBuffer(coinBuffer);
    SoundBuffer deathBuffer;
    deathBuffer.loadFromFile("sounds/mariodie.wav");
    Sound deathSound;
    deathSound.setBuffer(deathBuffer);
    SoundBuffer stageBuffer;
    stageBuffer.loadFromFile("sounds/stage.wav");
    Sound stageSound;
    stageSound.setBuffer(stageBuffer);

    Image heroImage;
    heroImage.loadFromFile("images/mario.png");
    heroImage.createMaskFromColor(Color(255, 255, 255));
    Image easyEnemyImage;
    easyEnemyImage.loadFromFile("images/EasyEnemy.png");
    easyEnemyImage.createMaskFromColor(Color(255, 255, 255));
    Image coinImage;
    coinImage.loadFromFile("images/coin.png");
    coinImage.createMaskFromColor(Color(255, 255, 255));
    Image mediumEnemyImage;
    mediumEnemyImage.loadFromFile("images/MediumEnemy.png");
    mediumEnemyImage.createMaskFromColor(Color(255, 255, 255));
    Image movePlatformImage;
    movePlatformImage.loadFromFile("images/MovingPlatform.png");

    std::list<Entity*> entities;
    std::list<Entity*>::iterator it;
    std::list<Entity*>::iterator it2;

    std::vector<Object> e = lvl.GetObjects("EasyEnemy");
    for (int i = 0; i < e.size(); i++) {
        entities.push_back(new Enemy(easyEnemyImage, "EasyEnemy", lvl, e[i].rect.left, e[i].rect.top, 15, 25));
    }
    e = lvl.GetObjects("coin");
    for (int i = 0; i < e.size(); i++) {
        entities.push_back(new Coin(coinImage, "coin", lvl, e[i].rect.left, e[i].rect.top, 15, 15));
    }
    e = lvl.GetObjects("MediumEnemy");
    for (int i = 0; i < e.size(); i++) {
        entities.push_back(new Enemy(mediumEnemyImage, "MediumEnemy", lvl, e[i].rect.left, e[i].rect.top, 16, 24));
    }
    e = lvl.GetObjects("exit");
    for (int i = 0; i < e.size(); i++) {
        entities.push_back(new Exit(mediumEnemyImage, "exit", lvl, e[i].rect.left, e[i].rect.top, 16, 24));
    }
    e = lvl.GetObjects("fire");
    for (int i = 0; i < e.size(); i++) {
        entities.push_back(new Fire(mediumEnemyImage, "fire", lvl, e[i].rect.left, e[i].rect.top, 16, 24));
    }
    e = lvl.GetObjects("MovingPlatform");
    for (int i = 0; i < e.size(); i++)
        entities.push_back(new MovingPlatform(movePlatformImage, "MovingPlatform", lvl, e[i].rect.left, e[i].rect.top, 95, 22));

    Object player = lvl.GetObject("player");
    Player p(heroImage, "Player", lvl, player.rect.left, player.rect.top, 22, 38);

    Clock clock;

    while (window.isOpen())
    {

        float time = clock.getElapsedTime().asMicroseconds();

        clock.restart();
        time = time / 800;

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

        for (it = entities.begin(); it != entities.end();) {
            Entity *b = *it;
            b->update(time);
            if (b->life == false) {
                it = entities.erase(it);
                delete b;
            }
            else it++;
        }

        for (it = entities.begin(); it != entities.end(); it++) {
            if (((*it)->name == "MovingPlatform") && ((*it)->getRect().intersects(p.getRect())))
            {
                Entity *movPlat = *it;
                if (p.dy>0)
                    if (p.y + p.height < movPlat->y + movPlat->height)
                    {
                        p.y = movPlat->y - p.height + 3;
                        p.x += movPlat->dx*time;
                        p.dy = 0;
                        p.onGround = true;
                    }
            }
            if ((*it)->getRect().intersects(p.getRect())) {
                if ((*it)->name == "EasyEnemy" || (*it)->name == "MediumEnemy") {
                    if ((p.dy>0) && (p.onGround == false) && (p.y + p.height < (*it)->y + (*it)->height)) {
                        p.dy = -0.3;
                        (*it)->lives--;
                        if ((*it)->name == "EasyEnemy")
                            (*it)->sprite.setTextureRect(IntRect(60, 8, 16, 8));
                        p.Score++;
                    }
                    else {
                        if (((*it)->lives != 0)) {
                            deathSound.play();
                            p.lives--;
                            lives--;
                            return false;
                        }
                    }
                }
                if ((*it)->name == "fire") {
                    deathSound.play();
                    p.lives--;
                    lives--;
                    return false;
                }
                if ((*it)->name == "coin") {
                    p.Score++;
                    coinSound.play();
                    (*it)->life = false;
                }
                if ((*it)->name == "exit") {
                    stageSound.play();
                    startLevel++;
                    return false;
                }
            }
            for (it2 = entities.begin(); it2 != entities.end(); it2++) {
                if ((*it)->getRect() != (*it2)->getRect())
                    if (((*it)->getRect().intersects((*it2)->getRect())) && ((*it)->name == "EasyEnemy")) {
                        (*it)->dx *= -1;
                        (*it)->sprite.scale(-1.5, 1.5);
                    }
            }
        }
        p.update(time);



        if (Keyboard::isKeyPressed(Keyboard::Escape)) {
            lives = 0;
            return false;
        }

        window.setView(view);
        window.clear(Color(167, 207, 218));
        lvl.Draw(window);


        for (it = entities.begin(); it != entities.end(); it++) {
            window.draw((*it)->sprite);
        }

        window.draw(p.sprite);
        window.display();
    }

    return 0;

}
Esempio n. 26
0
int main(int argc, char* argv[])
{
	setlocale(LC_ALL, "polish");
	string title = "Deltix v.";
	title += VERSION;
	///////////////////
	RenderWindow okno; //OKNO
	try
	{
		okno.create(VideoMode(RESOLUTION_WIDTH, RESOLUTION_HEIGHT, COLOR_DEPTH),
			title,
#if __MODE__ != 0
			Style::Fullscreen
#elif __MODE__ == 0
			Style::Default
#endif
			); //TWORZENIE OKNA
		okno.setFramerateLimit(200); //limit do 200fps
		okno.setMouseCursorVisible(false);
	}
	catch (...)
	{
		string temp = "BŁĄD - " + title;
		MessageBox(NULL, "Nie udało się utworzyć okna!", temp.c_str(), MB_OK | MB_ICONERROR);
		return 1;
	}
	
	/////////////////////
	
	States states = Splash;
	// PĘTLA
	while(okno.isOpen())
	{

		switch (states)
		{
		case Splash:
			
			if (SplashUpdate(&okno) < 0)

				states = Menu;
			break;
		case Menu:
			MenuUpdate(&okno);
			break;
		}


		Event eventMain;
		while (okno.pollEvent(eventMain))
		{
			if (eventMain.type == Event::Closed)
				okno.close(); // zamykanie
			/*if (eventMain.type == Event::KeyReleased && eventMain.key.code == Keyboard::C)
			{
				STARTUPINFO si;
				PROCESS_INFORMATION pi;

				ZeroMemory(&si, sizeof(si));
				si.cb = sizeof(si);
				ZeroMemory(&pi, sizeof(pi));
				CreateProcess(TEXT("C:\\WINDOWS\\System32\\calc.exe"), NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);
			}*/ // SYSTEMOWY KALKULATOR pod "C"
			switch (states)
			{
			case Menu:
				MenuEvents(&okno, eventMain); //Eventy Menu
				break;
			}
				
		}//TABELA EVENTÓW
		
		if (states != Splash) drawPointer(&okno);
		okno.display();
	}

#if __DEBUG__ == 1
	system("pause");
#endif
	return 0;
}
Esempio n. 27
0
int main()
{
#ifdef __GNUC__
	XInitThreads();
#endif

	xb::Joystick::isAnyXBox360ControllerConnected();

	bool isSmall;
	sf::View v(sf::FloatRect(0,0,sf::VideoMode::getDesktopMode().width,sf::VideoMode::getDesktopMode().height));

	RenderWindow *window;

	HEIGHT = 800;
	WIDTH = 1280;

	if (sf::VideoMode::getDesktopMode().height > 800)
	{
		window = new RenderWindow(VideoMode(WIDTH, HEIGHT), "Grief Trigger Turbo HD", sf::Style::Titlebar | sf::Style::Close);
		isSmall = false;
	}
	else
	{
		//HEIGHT = sf::VideoMode::getDesktopMode().width;
		//WIDTH = sf::VideoMode::getDesktopMode().height;

		window = new RenderWindow(VideoMode(sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height), "Grief Trigger Turbo HD", sf::Style::Titlebar | sf::Style::Close);
		isSmall = true;

		window->setSize(sf::Vector2u(sf::VideoMode::getDesktopMode().width/2, 800/2));
		v = window->getView();
		//v.zoom(2.f);
		window->setView(v);

		
	}
	//window->setFramerateLimit(60);
	window->setVerticalSyncEnabled(true);
//	window.setKeyRepeatEnabled(false);

	sf::Clock frameClock;
	sf::Clock updateClock;
	sf::Int32 nextUpdate = updateClock.getElapsedTime().asMilliseconds();
	float updateRate(1.0f / 15.f);
	float maxUpdates = 1;

	Level::instance().setDay(0);  // Menu
	Level::instance().setScene(0);//

	GameData::instance().getPlayer().getWeapon().init(L"Клеймор x");
	GameData::instance().getEmber().getWeapon().init(L"Посох x");
	GameData::instance().getThunder().getWeapon().init(L"Катана x");

	running = true;
	
	isMenu = true;

	

	while (running && window->isOpen())
	{
		sf::Int32 updateTime = updateClock.getElapsedTime().asMilliseconds();
		Uint32 updates = 0;

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

			if (!isMenu) SceneManager::instance().input(event);
			else mm.input(event);
		}	

		while((updateTime - nextUpdate) >= updateRate && updates++ < maxUpdates)
		{
			if (!isMenu)SceneManager::instance().update(sf::seconds(updateRate));
			else mm.update(sf::seconds(updateRate));		
			nextUpdate += updateRate;
		} 		

		//float lt, rt;
		//xb::Joystick::getTriggers(0, lt, rt);

		//// Triggers controls the vibration
		//xb::Joystick::setVibration(0, lt, rt);

		if (Level::instance().getDay()==0 && Level::instance().getScene()==0)
		{
			isMenu = true;
		}
		if (Level::instance().getDay()==0 && Level::instance().getScene()==0)
		{
			isMenu = true;
		}

		window->clear();
		if (isSmall)
		{		
			if (!isMenu) SceneManager::instance().draw(*window);
			else mm.draw(*window);
		}
		else
		{
			if (!isMenu) SceneManager::instance().draw(*window);
			else mm.draw(*window);
		}	
		window->display();
	}

	//xb::Joystick::setVibration(0);

	return 0;
}
Esempio n. 28
0
void mainLevel(RenderWindow &window)
{
	//>>>>>>>>>>>>>>>---Level---<<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Level lvl;
	 lvl.LoadFromFile("map.tmx");

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

	Texture texture2; 
	texture2.loadFromFile("images/levelShad.png");
	Sprite level2(texture2);

	Texture texture3;
	texture3.loadFromFile("images/level12.png");
	Sprite level3(texture3);
	//>>>>>>>>>>>>>>>>---Music---<<<<<<<<<<<<<<<<<<<<<<<<<<
	 Music mainSong;
	 mainSong.openFromFile("music/level1.ogg");
	 mainSong.play();
	 mainSong.setLoop(true);
	 mainSong.setVolume(75);

	 //>>>>>>>>>>>>>>>>---Create a cat---<<<<<<<<<<<<<<<<<<<
	 Object player = lvl.GetObject("cat");
	 Player cat("cat.png", lvl, player.rect.left, player.rect.top, 60, 120, 55, 25);
	 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);

	SoundBuffer buf;
	buf.loadFromFile("music/steklo.ogg");
	Sound glass;
	glass.setBuffer(buf); glass.setVolume(100);

	 //Objects
	 Furniture posters("tayles1.png",  160, 660, 210, 250, 280, 215);
	 Furniture bed("tayles1.png", 420, 80, 280, 310, 250, 440);
	 Furniture toys("tayles1.png", 120, 470, 180, 150, 220, 545);
	 Furniture upShelf("tayles1.png", 700, 652.5, 120, 97.5, 350, 83);
	 Furniture cabinet("tayles1.png", 75, 40, 250, 350, 605, 305);
	 Furniture mop("tayles1.png", 515, 785, 165, 241, 587, 385);
	 Furniture flower("tayles1.png",780, 65, 170, 330, 147, 285);
	 Furniture ball("tayles1.png", 905, 615, 40, 55, 357, 190);
	 Furniture books("tayles1.png", 860, 735, 125, 80, 290, 187);
	 Furniture brokenBall("tayles1.png",920, 540, 90, 42, 430, 430);
	 
	 Furniture door("tayles2.png", 0, 560, 80, 340, 870, 350);
	 Furniture brokenLight("tayles2.png", 10, 110, 50, 70, 795, 430);
	 Furniture light("tayles2.png", 20, 20, 35, 70, 220, 565);
	 Furniture bath("tayles2.png", 80, 50, 320, 380, 1010, 330);
	 Furniture carpet("tayles2.png", 100, 500, 100, 140, 870, 530);
	 Furniture mirror("tayles2.png", 90, 700, 110, 290, 1200, 300);
	 Furniture sink("tayles2.png", 290, 440, 150, 240, 1190, 450);
	 int cntMeow = 0;
	 Object ob = lvl.GetObject("catPlace");
	  while (window.isOpen())
    {
		
		float time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time = time/500;
		Vector2i pos = Mouse::getPosition(window);

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

			if (event.type == Event::MouseButtonPressed){
					if (event.key.code == Mouse::Left)
					{
						int cntMeow = meow(meow1, meow2, cat, pos);
						//>>>>>>BALL<<<<<<<<<<<<<<
						if(cat.sprite.getGlobalBounds().intersects(ob.rect))
						{
							if(cntMeow == -1)
							{
								ball.falling(event, window, pos, lvl, time);
								glass.play();
								ball.moving(event, window, pos, "ball", lvl);
							}
						}
						cat.clickedThings(window, light);
						//BOOKS>>>>----<<<<<<
						if(books.isPlayed == false)
						{
							if (books.sprite.getGlobalBounds().contains(pos.x, pos.y))
							{
								mainSong.pause();
								MiniGame_Books();
								books.isPlayed = true;
								mainSong.play();
							}
						}

					}
			}		
					
					toys.moving(event, window, pos, "toys", lvl);
					if(light.isPlayed == false)
						light.moving(event, window, pos, "light", lvl);
					

	
        }
		
		

		cat.Update(time);

		window.clear(Color::Black);
		lvl.Draw(window);
		if(cat.room == 0)
			window.draw(level);
		if(cat.room == 1)
			window.draw(level2); 
		if(cat.room == 2)
			window.draw(level3);
			
		window.draw(posters.sprite);
		window.draw(bed.sprite);
		window.draw(light.sprite);
		window.draw(toys.sprite);
		window.draw(upShelf.sprite);
		window.draw(cabinet.sprite);
		window.draw(mop.sprite);
		window.draw(flower.sprite);
		if(ball.isPlayed == false)
			window.draw(ball.sprite);
		else
			window.draw(brokenBall.sprite);
		window.draw(books.sprite);



		if(cat.room == 2){
			window.draw(bath.sprite);
			window.draw(mirror.sprite);
			window.draw(sink.sprite);
		}

		if(cat.room == 1 || cat.room == 2){
			if(light.isPlayed == false)
			window.draw(brokenLight.sprite);
			window.draw(carpet.sprite);
			window.draw(door.sprite);
		}
		

		window.draw(cat.sprite);
		
		window.display();
    }

}
Esempio n. 29
0
int main(int, char const**){
    // Create the main window
    RenderWindow window(VideoMode(800, 600), "SFML window");
    window.setFramerateLimit(60);

    
    Font font;
    if (!font.loadFromFile("Resources/sansation.ttf")) {
        return EXIT_FAILURE;
    }
    Text text(std::to_string(fps), font, 50);
    text.setColor(Color::White);
    text.setPosition(0,600-text.getGlobalBounds().height*2);
    
    tileTexture.loadFromFile("Resources/mapTileSpritesheet.png");

    guyTexture.loadFromFile("Resources/sprite1.png");
    // guyTexture.loadFromFile("Resources/guy.png");

    wallTexture.loadFromFile("Resources/64x64/b0.png");

    chestTexture.loadFromFile("Resources/chest.png");

    // std::cout << sizeof(tileTexture) << std::endl;

    dirtRect.left = 0;
    dirtRect.top = 0;
    dirtRect.width = 32;
    dirtRect.height = 32;
    
    Sprite dirt(tileTexture, dirtRect);
    
    grassRect.left = 32;
    grassRect.top = 0;
    grassRect.width = 32;
    grassRect.height = 32;
    
    Sprite grass(tileTexture, grassRect);

    wallRect.left = 0;
    wallRect.top = 0;
    wallRect.width = 32;
    wallRect.height = 32;

    Sprite wall(wallTexture,wallRect);

    Sprite closedChest(chestTexture,IntRect(0,0,16,16));
    closedChest.setScale(2,2);
    Sprite openChest(chestTexture,IntRect(17,0,16,16));
    openChest.setScale(2,2);

    // guyRect.left = 0;
    // guyRect.top = 128;
    // guyRect.width = 64; 
    // guyRect.height = 64;

    guyRect.left = 0;
    guyRect.top = 32;
    guyRect.width = 24; 
    guyRect.height = 24;

    Sprite guy(guyTexture, guyRect);
    // guy.setOrigin(guy.getLocalBounds().width/2, guy.getLocalBounds().height/2);
    // guy.setScale(32/24.0,32/24.0);
    guy.setPosition(windowWidth/2,windowHeight/2);

    RectangleShape guyHitBox(Vector2f(guy.getLocalBounds().width, guy.getLocalBounds().height));
    // guyHitBox.setOrigin(guyHitBox.getLocalBounds().width/2, guyHitBox.getLocalBounds().height/2);
    // guyHitBox.setScale(32/24.0,32/24.0);
    guyHitBox.setPosition(guy.getPosition());

    RectangleShape centerScreen(Vector2f(10,10));
    centerScreen.setPosition(windowWidth/2-5,windowHeight/2-5);
    centerScreen.setFillColor(Color(255,0,0));

    // std::cout << sizeof(dirt) << std::endl;
    // std::cout << sizeof(grass) << std::endl;
    
    tiles = new Tile[numTiles];
    for (int i = 0; i < numTiles; i++){
        if(i/columns == 0 || i / columns == rows-1 || i%columns == 0 || i%columns == columns-1){
            tiles[i].setVal(i/columns,i%columns,WALL,false);
        }
        else{
            tiles[i].setVal(i/columns,i%columns,GRASS,true);
        }
    }

    tiles[getTileIndex(5,5)].type = WALL;
    tiles[getTileIndex(5,5)].walkable = false;
    tiles[getTileIndex(6,5)].type = WALL;
    tiles[getTileIndex(6,5)].walkable = false;
    tiles[getTileIndex(7,5)].type = WALL;
    tiles[getTileIndex(7,5)].walkable = false;
    tiles[getTileIndex(8,5)].type = WALL;
    tiles[getTileIndex(8,5)].walkable = false;

    tiles[getTileIndex(5,18)].type = GRASS;
    tiles[getTileIndex(5,18)].walkable = false;
    tiles[getTileIndex(5,18)].chest = true;
    // tiles[getTileIndex(5,18)].chestOpen = true;

    // std::cout << sizeof(tiles[1]) << std::endl;
    
//    tiles[getTileIndex(2, 1)].setColor(Color::White);

    while (window.isOpen()){
        Event event;
        while (window.pollEvent(event)){
            // Close window: exit
            if (event.type == Event::Closed) {
                window.close();
            }
            // Escape pressed: exit
            if (event.type == Event::KeyPressed) {
                if(event.key.code == Keyboard::Escape){
                    window.close();
                }
                if(event.key.code == Keyboard::E){
                    tileAction(guy);
                }
            }
            if (event.type == Event::MouseButtonPressed)
            {
                if (event.mouseButton.button == Mouse::Left)
                {
                    int index = mouseToTile(event.mouseButton.x,event.mouseButton.y);
                    if (index >= 0) {
                        if(tiles[index].chest){
                            tiles[index].toggleState();
                        }
                    }
                }
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
            facing = UP;
            guy.move(0,-movementSpeed);
            guyPos = guy.getPosition();
            FloatRect guyBox = guy.getLocalBounds();
            tempIndex = mouseToTile(guyPos.x+guyBox.width/2,guyPos.y);
            Tile tempTile = tiles[tempIndex];
            int tempRow = tempTile.row;
            int tempCol = tempTile.col;
            for(int i = tempCol-2; i < tempCol+2; i++){
                // tiles[getTileIndex(tempRow,i)].type = DIRT;
                tempTile = tiles[getTileIndex(tempRow,i)];
                if(!tempTile.walkable){
                    int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2);
                    int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2);
                    int z3 = tempTile.width/2 + guyBox.width/2;
                    int z4 = tempTile.height/2 + guyBox.height/2;
                    if(std::abs(z1) < z3 && std::abs(z2) < z4){
                        // printf("top\n");
                        guyPos = Vector2f(guyPos.x, tempTile.y + tempTile.height+spacing);
                        guy.setPosition(guyPos);
                    }
                }
            }
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
            facing = DOWN;
            guy.move(0,movementSpeed);
            guyPos = guy.getPosition();
            FloatRect guyBox = guy.getLocalBounds();
            tempIndex = mouseToTile(guyPos.x+guyBox.width/2,guyPos.y+guyBox.height);
            Tile tempTile = tiles[tempIndex];
            int tempRow = tempTile.row;
            int tempCol = tempTile.col;
            for(int i = tempCol-2; i < tempCol+2; i++){
                // tiles[getTileIndex(tempRow,i)].type = DIRT;
                tempTile = tiles[getTileIndex(tempRow,i)];
                if(!tempTile.walkable){
                    int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2);
                    int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2);
                    int z3 = tempTile.width/2 + guyBox.width/2;
                    int z4 = tempTile.height/2 + guyBox.height/2;
                    if(std::abs(z1) < z3 && std::abs(z2) < z4){
                        // printf("bottom\n");
                        guyPos = Vector2f(guyPos.x, tempTile.y - guyBox.height - spacing);
                        guy.setPosition(guyPos);
                    }
                }
            }
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
            facing = LEFT;
            guy.move(-movementSpeed,0);
            guyPos = guy.getPosition();
            FloatRect guyBox = guy.getLocalBounds();
            tempIndex = mouseToTile(guyPos.x,guyPos.y+guyBox.height/2);
            Tile tempTile = tiles[tempIndex];
            int tempRow = tempTile.row;
            int tempCol = tempTile.col;
            for(int i = tempRow-2; i < tempRow+2; i++){
                tempTile = tiles[getTileIndex(i,tempCol)];
                // tiles[getTileIndex(i,tempCol)].type = DIRT;
                if(!tempTile.walkable){
                    int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2);
                    int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2);
                    int z3 = tempTile.width/2 + guyBox.width/2;
                    int z4 = tempTile.height/2 + guyBox.height/2;
                    if(std::abs(z1) < z3 && std::abs(z2) < z4){
                        // printf("left\n");
                        guyPos = Vector2f(tempTile.x + tempTile.width+spacing,guyPos.y);
                        guy.setPosition(guyPos);
                    }
                }
            }
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
            facing = RIGHT;
            guy.move(movementSpeed,0);
            guyPos = guy.getPosition();
            FloatRect guyBox = guy.getLocalBounds();
            tempIndex = mouseToTile(guyPos.x+guyBox.width,guyPos.y+guyBox.height/2);
            Tile tempTile = tiles[tempIndex];
            int tempRow = tempTile.row;
            int tempCol = tempTile.col;
            for(int i = tempRow-2; i < tempRow+2; i++){
                // tiles[getTileIndex(i,tempCol)].type = DIRT;
                tempTile = tiles[getTileIndex(i,tempCol)];
                if(!tempTile.walkable){
                    int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2);
                    int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2);
                    int z3 = tempTile.width/2 + guyBox.width/2;
                    int z4 = tempTile.height/2 + guyBox.height/2;
                    if(std::abs(z1) < z3 && std::abs(z2) < z4){
                        // printf("right\n");
                        guyPos = Vector2f(tempTile.x - guyBox.width - spacing,guyPos.y);
                        guy.setPosition(guyPos);
                    }
                }
            }
        }

        guyHitBox.setPosition(guy.getPosition());
        
        calculateFPS();
        
        text.setString(std::to_string(fps));
        closedChest.setPosition(-100,-100);
        openChest.setPosition(-100,-100);

        window.clear(Color(0,0,0));

        for (int i = 0; i < numTiles; i++){
            switch (tiles[i].type){
                case DIRT:
                    dirt.setPosition(tiles[i].x,tiles[i].y);
                    window.draw(dirt);
                    break;
                case GRASS:
                    grass.setPosition(tiles[i].x,tiles[i].y);
                    window.draw(grass);
                    break;
                case WALL:
                    wall.setPosition(tiles[i].x,tiles[i].y);
                    window.draw(wall);
                    break;
            }
            if(tiles[i].chest){
                if(tiles[i].chestOpen){
                    openChest.setPosition(tiles[i].x,tiles[i].y);
                    window.draw(openChest);
                }
                else{
                    closedChest.setPosition(tiles[i].x,tiles[i].y);
                    window.draw(closedChest);
                }
            }
        }
        window.draw(guyHitBox);
        window.draw(guy);
        // window.draw(openChest);
        window.draw(text); //FPS 
        // window.draw(centerScreen);
        
//        window.draw(dirt);

        window.display();
    }

    return EXIT_SUCCESS;
}
Esempio n. 30
0
void choice (RenderWindow &window, int volume)
{
     Texture choiceBackground;
	 choiceBackground.loadFromFile("images/choiceBG.png");
	 Sprite choiceBg(choiceBackground);
	 int choiceNum = 0;
	 bool isMenu = 1;
	 int menuNum = 0;
	 choiceBg.setPosition(0,0);
	 Font font;
	 font.loadFromFile("COLONNA.ttf");
	 Text text1("", font, 50);
	 Text text2("", font, 50);
	 Text text3("", font, 50);
	 Text text4("", font, 45);
	 Text text5("", font, 45);
	 Text text6("", font, 45);
	 Text text7("", font, 45);
	 Text text8("", font, 45);
	 Text text9("", font, 45);
	 Text text10("", font, 45);
	 Text text11("", font, 45);
	 text1.setString("HERE");
	 text2.setString("Let's go and save the village!");
	 text3.setString("MENU");
	 text4.setString("Far far away a long time ago");
     text5.setString("there was the best village in the world.");
     text6.setString("There lived the Red Dragon, who");
     text7.setString("helped people to survive from disasters.");
     text8.setString("Now this Dragon is sleeping,");
     text9.setString("but people need him to save their");
     text10.setString("lives! The bravest guy has");
     text11.setString("to wake him up!");
	 text1.setPosition(680,130);
	 text2.setPosition(920,750);
	 text3.setPosition(100,750);
	 text4.setPosition(820, 250);
	 text5.setPosition(740, 300);
	 text6.setPosition(760, 350);
	 text7.setPosition(730, 400);
	 text8.setPosition(820, 450);
	 text9.setPosition(770, 500);
	 text10.setPosition(850, 550);
	 text11.setPosition(930, 600);
	 int heroNum = 1;
	 int heroNumst = 1;
	 int exit = 0;
	 object_t * object = object_t_new ("book", false);
	 object_t * object1 = object_t_new ("book", false);
	 SoundBuffer buf1, buf2;
	 buf1.loadFromFile("sounds/step.ogg");
	 buf2.loadFromFile("sounds/step2.ogg");
	 Sound step1, step2;
	 step1.setBuffer(buf1);
     step2.setBuffer(buf2);
     sf::Music music;
     music.openFromFile("sounds/time.ogg");
     int musiccheck = 0;
	 while(window.isOpen())
	 {
		text1.setColor(Color(0,0,0));
		text2.setColor(Color(0,0,0));
		text3.setColor(Color(0,0,0));
		text4.setColor(Color(0,0,0));
		text5.setColor(Color(0,0,0));
		text6.setColor(Color(0,0,0));
		text7.setColor(Color(0,0,0));
		text8.setColor(Color(0,0,0));
		text9.setColor(Color(0,0,0));
		text10.setColor(Color(0,0,0));
		text11.setColor(Color(0,0,0));
		menuNum = 0;
        if (musiccheck == 0)
            {
                musiccheck = 1;
                music.setVolume(volume);
                music.play();
            }
		 window.clear(Color(129,181,221));
		 if(IntRect(680,130,150,50).contains(Mouse::getPosition(window)))
		 {
			 text1.setString("|");
			 menuNum = 1;
		 }
		 if(IntRect(920,750,550,50).contains(Mouse::getPosition(window)))
		 {
			 text2.setColor(Color(232,30,19));
			 menuNum = 2;
		 }
		 if(IntRect(100,750,250,50).contains(Mouse::getPosition(window)))
		 {
			 text3.setColor(Color(232,30,19));
			 menuNum = 3;
		 }
		if(Mouse::isButtonPressed(Mouse::Left))
		{
			if (menuNum == 1)
            {
                step1.play();
                puts ("choice num 1");
            }
			if(menuNum == 2)
			{
				step1.play();
				music.stop();
				puts ("choice num 2");
				object_t_write_plan (object, 0);
				object_t * object1 = startgame(window, object, volume);
				object_t_copy (object, object1);
				musiccheck = 0;
			}
			if(menuNum == 3)
			{
			    step1.play();
			    music.stop();
			    puts ("choice num 3");
				exit = 1;
			}
		}
		if (exit == 1)
            return;
		 window.draw(choiceBg);
		 window.draw(text1);
		 window.draw(text2);
		 window.draw(text3);
		 window.draw(text4);
		 window.draw(text5);
		 window.draw(text6);
		 window.draw(text7);
		 window.draw(text8);
		 window.draw(text9);
		 window.draw(text10);
		 window.draw(text11);
		 window.display();
	 }
	 puts ("end of choice");
}