Beispiel #1
0
int main()
{
    // Create main window
    WindowSettings Settings;
    //Settings.AntialiasingLevel = 4;
    RenderWindow application(VideoMode(800, 600), "Game", (Style::Close | Style::Resize), Settings);
    application.PreserveOpenGLStates(true);
    application.UseVerticalSync(true);

    // Setup rendering
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0.f, 0.f, 0.f, 0.f);

    // Setup an ortho projection
    glViewport(0, 0, 800, 600);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.f, 800.f, 600.f, 0.f, 0.f, 100.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // Gather a pointer to the input system
    const Input& input = application.GetInput();

    // Create a clock for measuring the time elapsed
    Clock clock;

    // Create the game object
    Game game(input);
    game.init();

    // Start game loop
    while (application.IsOpened())
    {
        // Give the game mouse screen related's position
        game.setMousePosition(input.GetMouseX(), input.GetMouseY());

        // Process events
        Event event;
        while (application.GetEvent(event))
        {
            // Close window : exit
            if (event.Type == Event::KeyPressed && event.Key.Code == Key::Escape)
            {
                application.Close();
            }

            switch (event.Type)
            {
                case Event::Closed:
                    application.Close();
                    break;

                case Event::Resized:
                    game.onEvent(&event);
                    onWindowResized(event.Size.Width, event.Size.Height);
                    break;

                case Event::MouseButtonPressed:
                    game.onEvent(&event);
                    break;

                case Event::LostFocus:
                case Event::GainedFocus:
                case Event::TextEntered:
                case Event::KeyPressed:
                case Event::KeyReleased:
                case Event::MouseWheelMoved:
                case Event::MouseButtonReleased:
                case Event::MouseMoved:
                case Event::MouseEntered:
                case Event::MouseLeft:
                case Event::JoyButtonPressed:
                case Event::JoyButtonReleased:
                case Event::JoyMoved:
                case Event::Count:
                    break;
            }
        }

        // Clear depth buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //Update
        game.update(clock.GetElapsedTime());
        clock.Reset();

        // Draw...
        game.draw();

        // Finally, display the rendered frame on screen
        application.Display();
    }

    return EXIT_SUCCESS;
}
Beispiel #2
0
int main(int , char**)
{
	int width = 1280, height = 760;
	Display mainWindow(width, height, "DEngine");
	//mainWindow.ShowCursor(false);
	mainWindow.WrapMouse(false);

	glm::vec3 lightPosition(-4.0f, 8.0f, -6.0f);
	Light sun(lightPosition, glm::vec3(1.0f, 1.0f, 1.0f), DIRECTIONAL_LIGHT);

	Camera camera(glm::vec3(0.0f, 2.0f, 1.0f));
	camera.SetCameraMode(FLY);
	

	Shader simpleProgram;
	simpleProgram.LoadShaders("./SHADERS/SOURCE/NoNormal_vs.glsl",
		"./SHADERS/SOURCE/NoNormal_fs.glsl");

	Shader skyBoxShaders;
	skyBoxShaders.LoadShaders("./SHADERS/SOURCE/skyBox_vs.glsl",
		"./SHADERS/SOURCE/skyBox_fs.glsl");
	Shader shadowShaders;
	shadowShaders.LoadShaders("./SHADERS/SOURCE/ShadowDepth_vs.glsl",
		"./SHADERS/SOURCE/ShadowDepth_fs.glsl");

	EventListener eventListener(&mainWindow, &camera, &simpleProgram);

	SkyBox sky;
	sky.LoadCubeMap("./Models/skybox");
	
	Model box;
	box.LoadModelFromFile(".\\Models\\Box.obj");
	box.TranslateModel(glm::vec3(0.0f, 2.0f, 0.0f));
	box.meshes[0].AddTexture("./Models/textures/154.png", textureType::DIFFUSE_MAP);
	box.meshes[0].AddTexture("./Models/textures/154_norm.png", textureType::NORMAL_MAP);
	box.meshes[0].AddTexture("./Models/textures/154s.png", textureType::SPECULAR_MAP);
	box.TranslateModel(glm::vec3(0.0f, -0.5f, -2.0f));

	Model floor;
	floor.LoadModelFromFile("./Models/Plane/plane.obj");
	floor.meshes[0].AddTexture("./Models/textures/196.png", textureType::DIFFUSE_MAP);
	floor.meshes[0].AddTexture("./Models/textures/196_norm.png", textureType::NORMAL_MAP);
	floor.meshes[0].AddTexture("./Models/textures/196s.png", textureType::SPECULAR_MAP);
	floor.TranslateModel(glm::vec3(0.0f, -2.0f, 0.0f));
	Clock clock;
	
	while (!mainWindow.isClosed)
	{
		eventListener.Listen();
		clock.NewFrame();

//DRAWING SCENE TO SHADOWMAP		
		//sun.StartDrawingShadows(shadowShaders.programID);
		//
		//glCullFace(GL_FRONT);
		////nanosuit.Draw(&mainWindow, camera, &sun, shadowShaders);
		//box.Draw(&mainWindow, camera, &sun, shadowShaders);
		//floor.Draw(&mainWindow, camera, &sun, shadowShaders);
		//
		//sun.StopDrawingShadows();
		//
		//glCullFace(GL_BACK);
		//glViewport(0, 0, width, height);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//NORMAL DRAWING SCENE		
		simpleProgram.UseProgram();
		glUniformMatrix4fv(glGetUniformLocation(simpleProgram.programID, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(sun.shadowMatrix));
		glUniform1f(glGetUniformLocation(simpleProgram.programID, "time"), clock.time);
		
		//glActiveTexture(GL_TEXTURE15);
		//glBindTexture(GL_TEXTURE_2D, sun.shadowTexture.textureID);
		//glUniform1i(glGetUniformLocation(simpleProgram.programID, "depth_map"), 15);
		
		
		floor.Draw(&mainWindow, camera, &sun, simpleProgram);
		box.Draw(&mainWindow, camera, &sun, simpleProgram);
		//sky.Draw(&mainWindow, camera, skyBoxShaders);

		camera.Update(clock.deltaTime);
		mainWindow.Update();
	}

	return 0;
}
Beispiel #3
0
int main()
{
	srand( time(NULL) );

	// Create the main window
	RenderWindow window(sf::VideoMode(800, 600, 32), "Stupid model 3");
		 
	std::vector<std::vector<HabitatCell> > grid;
	std::vector<Bug> bugs;

	//fill the vectors with cells
	for( int x = 0; x < GridSize; x++ ) {

		grid.push_back( std::vector<HabitatCell>() );

		for( int y = 0; y < GridSize; y++ ) {

			grid.at( x ).push_back( HabitatCell() );

		}
	}

	//place bugs randomly in the grid
	for (int i = 0; i < BugCount; i++) {
		int x = rand() % GridSize,
			y = rand() % GridSize;

		grid[x][y].hasBug = true;
		bugs.push_back( Bug(Vector2i(x,y), 1, &grid) );
	}

	Clock clock = Clock();

	while (window.isOpen())
	{
		// Process events
		sf::Event Event;
		while (window.pollEvent(Event))
		{
		// Close window : exit
		if (Event.type == sf::Event::Closed)
		window.close();
		// Escape key : exit
		if ((Event.type == sf::Event::KeyPressed) && (Event.key.code == sf::Keyboard::Escape))
		window.close();
		}


		//once a second
		if ( clock.getElapsedTime().asSeconds() >= 0.25f ) {

			//tell all the HabitatCells to produce food
			for(std::vector<std::vector<HabitatCell>>::iterator itr = grid.begin();
				itr != grid.end();
				itr++)
			{
				for(std::vector<HabitatCell>::iterator itr2 = itr->begin();
				itr2 != itr->end();
				itr2++)
				{
					itr2->ProduceFood();
				}
			}

			//tell all the bugs to move and grow
			for(std::vector<Bug>::iterator itr = bugs.begin(); itr != bugs.end(); itr++)
			{
				itr->Move();
				itr->Grow();
			}

			//restart the clock
			clock.restart();
		}

		//prepare frame
		window.clear();
		
		for(std::vector<Bug>::iterator itr = bugs.begin(); itr != bugs.end(); itr++)
		{
			itr->Draw(window);
		}

		window.display();

	} //loop back for next frame

	return EXIT_SUCCESS;
}
bool GUIPlayback::run(void)
{

    uint32_t movieTime;
    uint32_t systemTime;
    uint32_t fn;
    int refreshCounter=0;
    ticktock.reset();
    vuMeterPts=0;
    ADMImage *previewBuffer=admPreview::getBuffer();
    ADM_HW_IMAGE hwImageFormat=admPreview::getPreferedHwImageFormat();

    do
    {

        admPreview::displayNow();;
        GUI_setCurrentFrameAndTime(firstPts);
        if(false==videoFilter->getNextFrameAs(hwImageFormat,&fn,previewBuffer))
        {
            printf("[Play] Cancelling playback, nextPicture failed\n");
            break;
        }
        audioPump(false);
        lastPts=admPreview::getCurrentPts();
        systemTime = ticktock.getElapsedMS();
        movieTime=(uint32_t)((lastPts-firstPts*0)/1000);
        movieTime+=audioLatency;
       // printf("[Playback] systemTime: %lu movieTime : %lu  \r",systemTime,movieTime);
        if(systemTime>movieTime) // We are late, the current PTS is after current closk
        {
            if(systemTime >movieTime+20)
            {
                refreshCounter++;
            }
            if(refreshCounter>15)
            {
                UI_purge();
                UI_purge();
                refreshCounter=0;
            }
        }
	    else
	    {
            int32_t delta;
                delta=movieTime-systemTime;
                // a call to whatever sleep function will last at leat 10 ms
                // give some time to GTK
                while(delta > 10)
                {
                    if(delta>10)
                    {
                        audioPump(true);
                    }else
                        audioPump(false);

                    UI_purge();
                    refreshCounter=0;
                    systemTime = ticktock.getElapsedMS();
                    delta=movieTime-systemTime;
                }
        }
      }
    while (!stop_req);

abort_play:
        return true;
};
Beispiel #5
0
void runCollisionDetection ()
{
static Clock ck ;
ck.update () ;
double tall=ck.getDeltaTime () ;
  static int firsttime = true ;
  static unsigned int query = 0 ;

  FrameBufferObject *tmp ;
  FrameBufferObject *SCM = old ;
  FrameBufferObject *DCM = collisions ;
  unsigned int numHits ;

  if ( firsttime )
  {
    glGenQueriesARB ( 1, (GLuint*) & query ) ;
    firsttime = false ;
  }

  /* Fill SCM with big numbers */

  glClearColor ( 1.0f, 1.0f, 1.0f, 1.0f ) ;
  SCM -> prepare ( true ) ;

  glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f ) ;
  force -> prepare ( true ) ;  /* Zero out all of the forces. */

  int numPasses = 0 ;

  glPushClientAttrib   ( GL_CLIENT_VERTEX_ARRAY_BIT ) ;

  glClientActiveTexture( GL_TEXTURE1 ) ;
  glEnableClientState  ( GL_TEXTURE_COORD_ARRAY ) ;
  glBindBufferARB      ( GL_ARRAY_BUFFER_ARB, vbo_collt1 ) ;
  glTexCoordPointer    ( 2, GL_FLOAT, 0, vbo_collt1 ? NULL : colltexcoords1 ) ;

  glClientActiveTexture( GL_TEXTURE0 ) ;
  glEnableClientState  ( GL_TEXTURE_COORD_ARRAY ) ;
  glBindBufferARB      ( GL_ARRAY_BUFFER_ARB, vbo_collt0 ) ;
  glTexCoordPointer    ( 2, GL_FLOAT, 0, vbo_collt0 ? NULL : colltexcoords0 ) ;

  glEnableClientState  ( GL_VERTEX_ARRAY ) ;
  glBindBufferARB      ( GL_ARRAY_BUFFER_ARB, vbo_collvx ) ;
  glVertexPointer      ( 3, GL_FLOAT, 0, vbo_collvx ? NULL : collvertices ) ;

  while ( true )
  {
    collisionGenerator -> use () ;
    collisionGenerator -> applyTexture ( "position"  , position, 0 ) ;
    collisionGenerator -> applyTexture ( "old_collisions", SCM , 1 ) ;

    /* Fill DCM with zeroes */
    DCM -> prepare ( true ) ;

    glBeginQueryARB ( GL_SAMPLES_PASSED_ARB, query ) ;

    glMultiDrawArraysEXT ( GL_QUADS, (GLint*)& collstart, (GLint*)& colllength,
                           1 ) ;
numPasses++ ;

    glEndQueryARB   ( GL_SAMPLES_PASSED_ARB ) ;

    forceGenerator -> use () ;
    forceGenerator -> applyTexture ( "position"  , position , 0 ) ;
    forceGenerator -> applyTexture ( "force"     , force    , 1 ) ;
    forceGenerator -> applyTexture ( "collisions", DCM      , 2 ) ;

    GLuint sampleCount ;

    glGetQueryObjectuivARB ( query, GL_QUERY_RESULT_ARB, &sampleCount ) ;

//fprintf ( stderr, "%d ", sampleCount ) ;

    if ( sampleCount == 0 )
      break ;

    new_force -> paint () ;

    tmp = new_force ;
    new_force = force ;
    force = tmp ;

    tmp = DCM ;
    DCM = SCM ;
    SCM = tmp ;
  }

  glBindBufferARB      ( GL_ARRAY_BUFFER_ARB, 0 ) ;
  glPopClientAttrib () ;

ck.update () ;
double tdone=ck.getDeltaTime () ;
static int ii = 0 ;
ii++;
if (ii%100==0)
fprintf ( stderr, "Performance: %d passes %d cubes: other=%fms collisions=%fms\n", numPasses, NUM_CUBES, tall*1000.0, tdone*1000.0 ) ;
}
Beispiel #6
0
int main(int argc, char* argv[]) {

	// initialize Launchpad MIDI
	Launchpad launchpad;
	launchpad.initMidi();
	// test
	/*for (int x = 0; x < 4; x++) {
		for (int y = 0; y < 4; y++) {
			launchpad.plot(x * 2,     y * 2,     x, y);
			launchpad.plot(x * 2 + 1, y * 2 + 1, x, y);
		}
	}*/

	NanoKontrol nanoKontrol;
	/*nanoKontrol.initMidi();
	nanoKontrol.bindControl(16, &fltrRawCutoff);
	nanoKontrol.bindControl(17, &(fltr.reso));
	nanoKontrol.bindControl(18, &changeRoom);
	nanoKontrol.bindControl(19, &changeDamp);
	nanoKontrol.bindControl(20, &changeDecay);
	nanoKontrol.bindControl(21, &changeCurve);*/

	kontrolF1.bindControl(30, &fltrRawCutoff);
	kontrolF1.bindControl(31, &(fltr.reso));
	kontrolF1.bindControl(32, &changeRoom);
	kontrolF1.bindControl(33, &changeDamp);
	kontrolF1.bindControl(37, &changeDecay);
	// kontrolF1.bindControl(21, &changeCurve);


	for (int x = 0; x < 8; x++) {
		for (int y = 0; y < 3; y++) {
			nanoKontrol.plot(x, y, false);
		}
	}


	kontrolF1.initMidi();
	kontrolF1.bindControl(34, &f1ChangeH);
	kontrolF1.bindControl(35, &f1ChangeS);
	kontrolF1.bindControl(36, &f1ChangeB);

	kontrolF1.bindPads(&selectPad);


	// initialize SDL video and audio
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) return 1;

	// make sure SDL cleans up before exit
	atexit(SDL_Quit);

	// init synth
	osc3.freq  = 0.03;
	osc3.width = 0.9;
	glide.freq = 0.004;
	fltrSmoothCutoff.freq = 0.001;
	env.setReleaseTime(0.3);
	env.setCurvature(0.8);
	clk.setTempo(tempo);
	seq.setTempo(tempo);
	reverb.setRoomSize(0.3);
	reverb.setDamp(0.3);
	mix = 0.0;
	fltr.connect(&mix);
	glide.connect(&(seq.out));
	fltrSmoothCutoff.connect(&fltrRawCutoff);
	env.connect(&(clk.out));
	reverb.connect(&dry);

	// init SDL audio
	{
		SDL_AudioSpec audioSpec;
		audioSpec.freq     = SAMPLE_RATE;   // 44.1 kHz
		audioSpec.format   = AUDIO_S16;     // signed 16 bit
		audioSpec.channels = 2;             // stereo
		audioSpec.samples  = 512;           // buffer size: 512
		audioSpec.callback = audioCallback;
		SDL_OpenAudio(&audioSpec, NULL);
	}

	SDL_PauseAudio(0); // start audio

	SDL_Surface* screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
	SDL_WM_SetCaption("oodio", NULL);
	RenderingContext ctx(screen);
	ctx.backgroundColor(0, 0, 127);

	// load images
	AmsFont font("img/amstradFont.bmp");
	Button  btn(5, 23, "start/stop");
	Button  btnf(5, 25, "filter");
	Slider  sld(5, 27, 10, 0.1, 2);
	Slider  cut(12, 25, 30, 0.0, 1.0);
	Slider  res(16, 23, 26, 0.0, 0.7);
	btn.onClic(&playStop);
	btnf.onClic(&activateFilter);
	sld.onChange(&(osc3.freq));
	cut.onChange(&fltrRawCutoff);
	res.onChange(&(fltr.reso));

	displayMidiPorts(&font);
	// displayHidDevices(&font);

	btn.draw(&font);
	btnf.draw(&font);
	font.paper(1);
	font.pen(24);


	int nkx = 0;

	// program main loop
	bool run = true;
	while (run) {

		//-------------------------
		// message processing loop
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			// check for messages
			switch (event.type) {
			case SDL_QUIT:
				// exit if the window is closed
				run = false;
				break;

			// check for keypresses
			case SDL_KEYDOWN:
				// exit if ESCAPE is pressed
				if (event.key.keysym.sym == SDLK_ESCAPE) run = false;
				// start / stop sound with F1 key
				else if (event.key.keysym.sym == SDLK_F1) playStop();
				else if (event.key.keysym.sym == SDLK_F2) osc1.freq = 110;
				else if (event.key.keysym.sym == SDLK_F3) osc1.freq = 440;
				// keyboard
				else if (event.key.keysym.sym <= 256 && event.key.keysym.sym >= 0 ) {
					font.print(event.key.keysym.sym);
				}
				break;

			case SDL_MOUSEMOTION:
				// font.locate(event.motion.x / (8 * PIXEL), event.motion.y / (8 * PIXEL));
				// font.paper(-1);
				// font.print('*');
				sld.move(event.motion.x, event.motion.y);
				cut.move(event.motion.x, event.motion.y);
				res.move(event.motion.x, event.motion.y);
				break;
			case SDL_MOUSEBUTTONDOWN:
				btn.clic(event.button.x, event.button.y);
				btnf.clic(event.button.x, event.button.y);
				sld.clic(event.button.x, event.button.y);
				cut.clic(event.button.x, event.button.y);
				res.clic(event.button.x, event.button.y);
				break;
			case SDL_MOUSEBUTTONUP:
				sld.unclic(event.button.x, event.button.y);
				cut.unclic(event.button.x, event.button.y);
				res.unclic(event.button.x, event.button.y);
				break;
			}
		}

		ctx.clear();
		sld.draw(&font);
		cut.draw(&font);
		res.draw(&font);
		ctx.drawImage(font.getImage(), 0, 0);
		ctx.update();


		//----------------------------------
		// nanoKontrol light show
		/*nkx--;
		if (nkx < 0) nkx = 15;
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 3; y++) {
				bool value = ((nkx + x + y) % 16) < 2;
				nanoKontrol.plot(x, y, value);
			}
		}*/
		//----------------------------------

		SDL_Delay(40); // 25 FPS
	}

	// close audio
	SDL_CloseAudio();

	// close midi
	// midiOutReset(device);
	// midiOutClose(device);

	return 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;
}
Beispiel #8
0
bool Time::isValid() {
    Clock *clk = getClock();
    if (clk) return clk->isValid();
    return true;
}
Beispiel #9
0
double Time::now() {
    Clock *clk = getClock();
    if (clk) return clk->now();
    return SystemClock::nowSystem();
}
/******************* WIN32 FUNCTIONS ***************************/
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	bool	done=false;								// Bool Variable To Exit Loop

	StartGame n = StartGame();
	activityManager.push(&n);
	console.Open();

	// Create Our OpenGL Window
	if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight))
	{
		return 0;									// Quit If Window Was Not Created
	}

	Clock clock;
	double timeSinceLastUpdate = 0.0;

	Clock fpsCounterClock;
	double fpsCounterTime = 0.0;
	int fpsCounter = 0;

	clock.start();
	fpsCounterClock.start();

	//*******************************************GAME LOOP***********************************************************//

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=true;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			if(keys[VK_ESCAPE])
				done = true;

	
			if (!keys[VK_RETURN]){

				fpsCounterTime += fpsCounterClock.restart();

				timeSinceLastUpdate += clock.restart();	

				while (timeSinceLastUpdate > TIME_PER_FRAME) {
						
						fpsCounter++;
						timeSinceLastUpdate -= TIME_PER_FRAME;
						update(TIME_PER_FRAME);
				}

				
				if (fpsCounterTime > 1){
#ifdef displayFPS
					std::cout<<"\t\t\t\t\tFPS: "<<fpsCounter<<std::endl;
#endif
					fpsCounterTime = 0;
					
					fpsCounter = 0;
				}
				
			}
			display();					// Draw The Scene

			SwapBuffers(hDC);				// Swap Buffers (Double Buffering)
		}
	}



	console.Close();

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (int)(msg.wParam);						// Exit The Program
}
/*
 * ======== clockIdle ========
 * Wrapper function for IDL objects calling
 * Clock::tick()
 */
void clockIdle(void)
{ 
    cl0.tick();
    return;
} 
int main(){
	std::list<Player*> players; //создаём список объектов класса;
	std::list<Player*>::iterator it; //итератор для первичной обратки
	std::list<Player*>::iterator at; //для вторичной обработки
	std::list<Player*>::iterator that; //для третичной

	Font font;//шрифт 
	font.loadFromFile("CyrilicOld.ttf");//передаем нашему шрифту файл шрифта
	Text text("", font, 19);//создаем объект текст. закидываем в объект текст строку, шрифт, размер шрифта(в пикселях);//сам объект текст (не строка)
	text.setColor(Color::Red);//покрасили текст в красный. если убрать эту строку, то по умолчанию он белый
	text.setStyle(sf::Text::Italic | sf::Text::Underlined);//жирный и подчеркнутый текст. по умолчанию он "худой":)) и не подчеркнутый

	int tempX = 0; //временная коорд Х.Снимаем ее после нажатия прав клав мыши
	int tempY = 0; //коорд Y
	float distance = 0;//это расстояние от объекта до тыка курсора

	float CurrentFrame = 0;//хранит текущий кадр
	Clock clock;
	RenderWindow window(sf::VideoMode(821, 730), "CHESS! Author: IldarkinAlexey; PS-22."); // создаём окно размером 821x730 (в нашем случае)
	Texture BGtexture;
	BGtexture.loadFromFile("images/chess.png");

	Texture Paneltexture;
	Paneltexture.loadFromFile("images/panel.png");

	Sprite BGsprite;
	BGsprite.setTexture(BGtexture);
	BGsprite.setTextureRect(IntRect(2, 0, 730, 730)); //задаём координаты нашей фигурки [смотрим их в пэйнте]; (начало по х, по у, размер, размер);
	BGsprite.setPosition(0, 0); //выводим спрайт в позицию x y 

	Sprite Panelsprite;
	Panelsprite.setTexture(Paneltexture);
	Panelsprite.setTextureRect(IntRect(2, 0, 100, 730)); //задаём координаты нашей фигурки [смотрим их в пэйнте]; (начало по х, по у, размер, размер);
	Panelsprite.setPosition(730, 0); //выводим спрайт в позицию x y 

	Texture exitButton_texture;
	exitButton_texture.loadFromFile("images/logout.png");

	Sprite exitButton_sprite;
	exitButton_sprite.setTexture(exitButton_texture);
	exitButton_sprite.setTextureRect(IntRect(0, 0, 32, 32));
	exitButton_sprite.setPosition(740, 5);

	Texture restartButton_texture;
	restartButton_texture.loadFromFile("images/restart.png");

	Sprite restartButton_sprite;
	restartButton_sprite.setTexture(restartButton_texture);
	restartButton_sprite.setTextureRect(IntRect(0, 0, 32, 32));
	restartButton_sprite.setPosition(774, 5);

	players.push_back(new Player("w_peshka.png", 53.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 131.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 209.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 287.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 365.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 443.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 521.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("w_peshka.png", 599.0, 524.0, size_move, size_move, type_peshka, color_white));
	players.push_back(new Player("b_peshka.png", 53.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 131.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 209.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 287.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 365.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 443.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 521.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_peshka.png", 599.0, 130.0, size_move, size_move, type_peshka, color_black));
	players.push_back(new Player("b_tower.png", 53.0, 53.0, size_move, size_move, type_tower, color_black));
	players.push_back(new Player("b_tower.png", 599.0, 53.0, size_move, size_move, type_tower, color_black));
	players.push_back(new Player("b_horse.png", 131.0, 53.0, size_move, size_move, type_horse, color_black));
	players.push_back(new Player("b_horse.png", 521.0, 53.0, size_move, size_move, type_horse, color_black));
	players.push_back(new Player("b_ladya.png", 209.0, 53.0, size_move, size_move, type_ladya, color_black));
	players.push_back(new Player("b_ladya.png", 443.0, 53.0, size_move, size_move, type_ladya, color_black));
	players.push_back(new Player("b_king.png", 365.0, 53.0, size_move, size_move, type_king, color_black));
	players.push_back(new Player("b_ferz.png", 287.0, 53.0, size_move, size_move, type_ferz, color_black));
	players.push_back(new Player("w_tower.png", 53.0, 602.0, size_move, size_move, type_tower, color_white));
	players.push_back(new Player("w_tower.png", 602.0, 602.0, size_move, size_move, type_tower, color_white));
	players.push_back(new Player("w_horse.png", 131.0, 602.0, size_move, size_move, type_horse, color_white));
	players.push_back(new Player("w_horse.png", 521.0, 602.0, size_move, size_move, type_horse, color_white));
	players.push_back(new Player("w_ladya.png", 209.0, 602.0, size_move, size_move, type_ladya, color_white));
	players.push_back(new Player("w_ladya.png", 443.0, 602.0, size_move, size_move, type_ladya, color_white));
	players.push_back(new Player("w_king.png", 365.0, 602.0, size_move, size_move, type_king, color_white));
	players.push_back(new Player("w_ferz.png", 287.0, 602.0, size_move, size_move, type_ferz, color_white));
	players.push_back(new Player("empty_sprite.png", 0.0, 0.0, 60.0, 60.0, type_empty, color_neutral));

	bool isMove = false;
	bool game = true;
	bool gameOVER = true;
	string moving_color = color_white;
	while ((window.isOpen())) {
		float time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time = time / 800;
		Vector2i pixelPos = Mouse::getPosition(window);//забираем коорд курсора
		Vector2f pos = window.mapPixelToCoords(pixelPos);//переводим их в игровые (уходим от коорд окна)
		sf::Event event;
		while ((window.pollEvent(event))) {
			if (event.type == sf::Event::Closed)
				window.close();
			if (game)
				if (event.type == Event::MouseButtonPressed, !(isMove)) { //если нажата клавиша мыши 
					if (event.key.code == Mouse::Left) { //а именно левая
						if (exitButton_sprite.getGlobalBounds().contains(pos.x, pos.y)) {
							window.close();
						}
						if (restartButton_sprite.getGlobalBounds().contains(pos.x, pos.y)) {
							window.close();
							main();
						}
						for (it = players.begin(); it != players.end(); it++) {
							if ((*it)->sprite.getGlobalBounds().contains(pos.x, pos.y)) { //и при этом координата курсора попадает в спрайт
								if ((*it)->color == moving_color) {
									((*it)->sprite).setColor(Color::Green);
									isMove = true;
									((*it)->isSelect) = true;
								}
							}
						}
						if (!(isMove))
							break;
					}
				}

			if (isMove)//если выбрали объект
				if (event.type == Event::MouseButtonPressed)//если нажата клавиша мыши
					if ((event.key.code == Mouse::Right) && ((min_border_board < pos.x) && ((max_border_board + 20) > pos.x)) && ((min_border_board < pos.y) && ((max_border_board + 20) > pos.y))) {
						for (it = players.begin(); it != players.end(); it++) {
							if (((*it)->isSelect) == true) {
								((*it)->isMove) = true;//то начинаем движение
								((*it)->isSelect) = false;//объект уже не выбран
								((*it)->sprite).setColor(Color::White);//возвращаем обычный цвет спрайту
								tempX = pos.x;//забираем координату нажатия курсора Х
								tempY = pos.y;//и Y
							}
						}
					}
					else {
						isMove = false;
						for (it = players.begin(); it != players.end(); it++) {
							if ((*it)->isSelect) {
								(*it)->isSelect = false;
								((*it)->sprite).setColor(Color::White);
							}
						}
					}
		}
		for (it = players.begin(); it != players.end(); it++) {
			if (((*it)->isMove) && (isMove)) {
				string checkReady = readyNone;
				if ((*it)->type == type_peshka) {
					checkReady = CheckLegalOfMove(players, (*it), tempX, tempY);
					if (checkReady == readyGo) {
						(*it)->step_Peshka(tempX, tempY);
						if (((*it)->color == color_white) && ((*it)->y < 60)) {
							(*it)->life = false;
							players.push_back(new Player("w_ferz.png", (*it)->x, (*it)->y, size_move, size_move, type_ferz, color_white));
						}
						if (((*it)->color == color_black) && (((*it)->y + size_move) > 650)) {
							(*it)->life = false;
							players.push_back(new Player("b_ferz.png", (*it)->x, (*it)->y, size_move, size_move, type_ferz, color_black));
						}
					}
				}
				if ((*it)->type == type_tower){
					checkReady = CheckLegalOfMove(players, (*it), tempX, tempY);
					if (checkReady == readyGo) {
						(*it)->step_Tower(tempX, tempY);
					}
				}
				if ((*it)->type == type_ladya) {
					checkReady = CheckLegalOfMove(players, (*it), tempX, tempY);
					if (checkReady == readyGo) {
						(*it)->step_Ladya(tempX, tempY);
					}
				}
				if ((*it)->type == type_ferz) {
					checkReady = CheckLegalOfMove(players, (*it), tempX, tempY);
					if (checkReady == readyGo) {
						(*it)->step_Ferz(tempX, tempY);
					}
				}
				if ((*it)->type == type_horse) {
					checkReady = CheckLegalOfMove(players, (*it), tempX, tempY);
					if (checkReady == readyGo) {
						float current_x = (*it)->x;
						float current_y = (*it)->y;
						(*it)->step_Horse(tempX, tempY);
						if (((min_border_board > (*it)->x) || (max_border_board < (*it)->x)) || (((min_border_board + 1) >(*it)->y) || (max_border_board < (*it)->y))) {
							(*it)->x = current_x;
							(*it)->y = current_y;
						}
					}
				}
				if ((*it)->type == type_king) {
					checkReady = CheckLegalOfMove(players, (*it), tempX, tempY);
					if (checkReady == readyGo) {
						(*it)->step_Peshka(tempX, tempY);
					}
				}
				((*it)->isMove) = false;
				isMove = false;
				if (checkReady == readyGo) {
					if (moving_color == color_white)
					{
						moving_color = color_black;
					}
					else
						moving_color = color_white;
				}
			}
		}
		window.clear();
		window.draw(BGsprite);
		window.draw(Panelsprite);
		for (it = players.begin(); it != players.end();) {
			Player*b = *it;
			b->update(time);
			if (b->life == false) {
				if (b->type == type_king) {
					gameOVER = false;
				}
				it = players.erase(it);
				delete(b);
			}
			else {
				it++;
			}
		}

		for (it = players.begin(); it != players.end(); it++) {
			if (gameOVER) {
				if (moving_color == color_white) {
					text.setString(color_white);//задает строку тексту
					text.setPosition(748, 649);//задаем позицию текста, центр камеры
				}
				else {
					text.setString(color_black);//задает строку тексту
					text.setPosition(752, 63);//задаем позицию текста, центр камеры
				}
			}
			else {
				text.setString("G\nA\nM\nE\n\nO\nV\nE\nR\n");//задает строку тексту
				text.setPosition(765, 295);//задаем позицию текста, центр камеры
				window.draw(text);
				window.draw((*it)->sprite);
				game = false;
			}
			window.draw(text);//рисую этот текст
			window.draw((*it)->sprite);
		}
		window.draw(exitButton_sprite);
		window.draw(restartButton_sprite);
		window.display();
	}
	return 0;
}
Beispiel #13
0
int main( int argc, char* args[] )
{
    //Quit flag
    bool quit = false;

    //Initialize
    if( init() == false )
    {
        return 1;
    }

    //Load the files
    if( load_files() == false )
    {
        return 1;
    }

    //Clip range for the top left
    clip[ 0 ].x = 0;
    clip[ 0 ].y = 0;
    clip[ 0 ].w = 100;
    clip[ 0 ].h = 100;

    //Clip range for the top right
    clip[ 1 ].x = 100;
    clip[ 1 ].y = 0;
    clip[ 1 ].w = 100;
    clip[ 1 ].h = 100;

    //Clip range for the bottom left
    clip[ 2 ].x = 0;
    clip[ 2 ].y = 100;
    clip[ 2 ].w = 100;
    clip[ 2 ].h = 100;

    //Clip range for the bottom right
    clip[ 3 ].x = 100;
    clip[ 3 ].y = 100;
    clip[ 3 ].w = 100;
    clip[ 3 ].h = 100;

    //Fill the screen white
    SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );

	int i = 0;
	float xPos = 0;
	float yPos = 0;

    //Apply the sprites to the screen
	Uint8* keystates = SDL_GetKeyState(NULL);
	while(!quit) 		//While the user hasn't quit
	{
		clock.update();
		if(clock.allowTick()) //time based stuff goes in here.
		{
			//Fill/Reset the screen 
			SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0, 0, 0xFF ) );

			//Timer
			Uint32 timeElapsedMs = clock.timeElapsed;

			//While there's events to handle
			while( SDL_PollEvent( &event ) )
			{
				//If the user has Xed out the window
				if( event.type == SDL_QUIT )
				{
					//Quit the program
					quit = true;
				}
			}

			controller->update();		

			if(controller->releaseCancel())
			{
				quit = true; //ESC terminates the program
			}

			

			animationTest->update(timeElapsedMs);
			deathPlayer->update(timeElapsedMs);
			testMonster->update(timeElapsedMs);
			animationTest->draw(xPos,yPos, screen); 
			deathPlayer->draw(screen);
			testMonster->draw(screen);

			SDL_Rect playerLocation;
			SDL_Rect collisionBoxClip;
			collisionBoxClip.x = 0; 
			collisionBoxClip.y = 0; 
			collisionBoxClip.w = deathPlayer->collisionBox.w;
			collisionBoxClip.h = deathPlayer->collisionBox.h;
			playerLocation.x = deathPlayer->collisionBox.x;
			playerLocation.y = deathPlayer->collisionBox.y;
			SDL_BlitSurface(blackTest, &collisionBoxClip,
				screen, &playerLocation);

			//Render the text
			std::string s;
			std::stringstream out2;
			out2 << timeElapsedMs;
			string resultCursorStr = "TimeElapsed: " + out2.str();
			string text = resultCursorStr;
		
			SDL_Surface *message = TTF_RenderText_Solid( font, text.c_str(), textColor );
    
			//If there was an error in rendering the text
			if( message == NULL )
			{
				return 1;    
			}
    
			//Apply the images to the screen
			apply_surface( 0, 150, message, screen );
		
			//Update the screen
			if( SDL_Flip( screen ) == -1 )
			{
				return 1;
			}
		}//end clockTick check
	}
    //Free the images and quit SDL
    clean_up();

    return 0;
}
Beispiel #14
0
void GameStart() {
	RenderWindow window(VideoMode(MapWidth * SpriteSize, MapHeight * SpriteSize), "Snake");
	Clock clock;
	Game* game;
	NewGame(game);
	Text text = game->game_text->text;

	while (window.isOpen()) //разбить на 3 метода
	{
		float time = clock.getElapsedTime().asSeconds();
		clock.restart();
		game->consts->time_counter += time;

		ProcessEvents(window, game);

		if (game->state == STARTGAME) {
			window.clear();
			text.setCharacterSize(120);
			text.setString("       Snake!\n\nPress 'U' to start!");
			text.setPosition(250, 50);
			window.draw(text);
		}
		else if (game->state == RESTART) {
			DestroyGame(game);
			NewGame(game);
			text = game->game_text->text;
			game->state = PLAY;
		}
		else if (game->state == PAUSE) {
			window.clear();
			Render(window, game);
			text.setCharacterSize(150);
			text.setString("Pause");
			text.setPosition(455, 160);
			window.draw(text);
		}
		else if (game->state == PLAY) {
			while (game->consts->time_counter > game->consts->speed) {
				game->consts->time_counter = 0;

				//Snake movement

				Step(game->snake);

				int snake_draw_counter = SnakeLength(game->snake);

				ProcessCollisions(snake_draw_counter, game);
			}
			Render(window, game);
		}
		else if (game->state == ENDGAME) {
			window.clear();
			text.setCharacterSize(120);
			text.setString("       Score: " + ToString(game->consts->score) + "\n Press 'Esc' to exit\n Press 'R' to restart");
			text.setPosition(170, 28);
			window.draw(text);
		}

		window.display();
	}
	DestroyGame(game);
}
volatile char shutterLagTest(char key, char first)
{
//  static uint8_t cable;
	uint16_t start_lag, end_lag;

	if(first)
	{
//    cable = 0;
		lcd.cls();
		menu.setTitle(TEXT("Shutter Lag Test"));
		menu.setBar(TEXT("Test 1"), TEXT("Test 2 "));
		lcd.update();
	}

	if(key == FL_KEY || key == FR_KEY)
	{
		lcd.eraseBox(10, 18, 80, 38);
		lcd.writeString(10, 18, TEXT("Result:"));

		ENABLE_SHUTTER;
		ENABLE_MIRROR;
		ENABLE_AUX_PORT;

		_delay_ms(100);

		if(key == FR_KEY)
		{
			MIRROR_UP;
			_delay_ms(1000);
		}

		SHUTTER_OPEN;
		clock.tare();

		while(!AUX_INPUT1)
		{
			if(clock.eventMs() >= 1000)
				break;
		}

		start_lag = (uint16_t)clock.eventMs();

		_delay_ms(50);

		SHUTTER_CLOSE;
		clock.tare();

		while(AUX_INPUT1)
		{
			if(clock.eventMs() > 1000)
				break;
		}

		end_lag = (uint16_t)clock.eventMs();

		lcd.writeNumber(56, 18, start_lag, 'U', 'L');
		lcd.writeNumber(56, 28, end_lag, 'U', 'L');

		lcd.update();
	}

	if(key == LEFT_KEY)
		return FN_CANCEL;

	return FN_CONTINUE;
}
//The protocol/transport stack test driver
//
// Reads two command line arguments
// Arg1 chooses the transport, memory or file (m|f)
// Arg2 chooses the protocol, binary/compact/json (b|c|j)
// example: 
//     proto_write_times f j
// to run the test with a file transport and JSON protocol
int main(int argc, char *argv[]) {
    if (argc != 3) {					
        std::cout << "usage: " << argv[0] 
                  << " (m[emory]|f[file]) (b[inary]|c[ompact]|j[son])" 
         << std::endl;
        return -1;
    }

	//Set the Transport
    boost::shared_ptr<TTransport> trans;			
    if (argv[1][0] == 'm' || argv[1][0] == 'M') {
        const int mem_size = 1024*1024*64;
        trans.reset(new TMemoryBuffer(mem_size));
        std::cout << "Writing memory, buffer size: " << mem_size 
                  << std::endl;
    }
    else if (argv[1][0] == 'f' || argv[1][0] == 'F') {
        const std::string path_name("/tmp/thrift_data");
        trans.reset(new TSimpleFileTransport(path_name, false, true));
        std::cout << "Writing to: " << path_name << std::endl;
    }
    else {
        std::cout << "usage: " << argv[0] 
                  << " (m[emory]|f[file]) (b[inary]|c[ompact]|j[son])" 
                  << std::endl;
        return -1;
    }

	//Set the Protocol
    std::unique_ptr<TProtocol> proto;			
    if (argv[2][0] == 'b' || argv[2][0] == 'B')
        proto.reset(new TBinaryProtocol(trans));
    else if (argv[2][0] == 'c' || argv[2][0] == 'C')
        proto.reset(new TCompactProtocol(trans));
    else if (argv[2][0] == 'j' || argv[2][0] == 'J')
        proto.reset(new TJSONProtocol(trans));
    else {
        std::cout << "usage: " << argv[0] << 
 			" (m[emory]|f[file]) (b[inary]|c[ompact]|j[son])" 
                  << std::endl;
        return -1;
    }

	//Report clock information
    Clock<std::chrono::steady_clock> clock;
    std::cout << "Clock precision in seconds: " << clock.precision() 	
 		  << " (steady: " << clock.isSteady() << ")" << std::endl;

	//Init the object (different values can have an affect on 
	//JSON ad Compact protocol performance !)
    Trade trade;
    trade.symbol[0] = 'F'; trade.symbol[1] = '\0';
    trade.price = 13.10;
    trade.size = 2500;

	//Serialize the object and write to the transport 1mm times
    auto start = clock.now();
    int i = 0;
    for (int loop_count = 0; loop_count < 1000000; ++loop_count) { 
        i += proto->writeStructBegin("Trade");

        i += proto->writeFieldBegin("symbol", 
                                    ::apache::thrift::protocol::T_STRING, 
                                    1);
        i += proto->writeString(std::string(trade.symbol));
        i += proto->writeFieldEnd();

        i += proto->writeFieldBegin("price", 
                                    ::apache::thrift::protocol::T_DOUBLE, 
                                    2);
        i += proto->writeDouble(trade.price);
        i += proto->writeFieldEnd();

        i += proto->writeFieldBegin("size", 
                                    ::apache::thrift::protocol::T_I32, 3);
        i += proto->writeI32(trade.size);
        i += proto->writeFieldEnd();

        i += proto->writeFieldStop();
        i += proto->writeStructEnd();
    }

	//Report the results
    std::cout << "elapsed: " << clock.elapsed(start, clock.now()) 
              << std::endl;
    std::cout << "Wrote " << i << " bytes" << std::endl;
}
volatile char batteryStatus(char key, char first)
{
//	uint16_t batt_high = 645;
//	uint16_t batt_low = 540;
	static uint8_t charging;
	char stat = battery_status();

	if(first)
	{
		charging = (stat > 0);
	}

//	unsigned int batt_level = battery_read_raw();

#define BATT_LINES 36

//	uint8_t lines = ((batt_level - batt_low) * BATT_LINES) / (batt_high - batt_low);
	uint8_t lines = (uint8_t)((uint16_t)battery_percent * BATT_LINES / 100);

	if(lines > BATT_LINES - 1 && stat == 1)
		lines = BATT_LINES - 1;

	if(lines > BATT_LINES || stat == 2)
		lines = BATT_LINES;

	lcd.cls();

	char* text;

	text = getChargingStatus();

	char l = lcd.measureStringTiny(text) / 2;

	if(battery_status())
		lcd.writeStringTiny(41 - l, 31, text);

	// Draw Battery Outline //
	lcd.drawLine(20, 15, 60, 15);
	lcd.drawLine(20, 16, 20, 27);
	lcd.drawLine(21, 27, 60, 27);
	lcd.drawLine(60, 16, 60, 19);
	lcd.drawLine(60, 23, 60, 26);
	lcd.drawLine(61, 19, 61, 23);

	// Draw Battery Charge //
	for(uint8_t i = 0; i <= lines; i++)
	{
		lcd.drawLine(22 + i, 17, 22 + i, 25);
	}

	menu.setTitle(TEXT("Battery Status"));
	menu.setBar(TEXT("RETURN"), BLANK_STR);
	lcd.update();

	if(stat == 0 && charging)
	{
		clock.awake();
		return FN_CANCEL; // unplugged
	}
	if(key == FL_KEY)
		return FN_CANCEL;

	return FN_CONTINUE;
}
  virtual bool execJoined(rti1516::RTIambassador& ambassador)
  {
    rti1516::InteractionClassHandle requestHandle;
    try {
      requestHandle = ambassador.getInteractionClassHandle(L"Request");
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    rti1516::ParameterHandle requestTypeHandle;
    try {
      requestTypeHandle = ambassador.getParameterHandle(requestHandle, L"requestType");
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    try {
      interactionClassHandle0 = ambassador.getInteractionClassHandle(L"InteractionClass0");
      interactionClassHandle1 = ambassador.getInteractionClassHandle(L"InteractionClass1");
      interactionClassHandle2 = ambassador.getInteractionClassHandle(L"InteractionClass2");
      interactionClassHandle3 = ambassador.getInteractionClassHandle(L"InteractionClass3");
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    try {
      class0Parameter0Handle = ambassador.getParameterHandle(interactionClassHandle0, L"parameter0");
      class1Parameter0Handle = ambassador.getParameterHandle(interactionClassHandle1, L"parameter0");
      class1Parameter1Handle = ambassador.getParameterHandle(interactionClassHandle1, L"parameter1");
      class2Parameter0Handle = ambassador.getParameterHandle(interactionClassHandle2, L"parameter0");
      class2Parameter1Handle = ambassador.getParameterHandle(interactionClassHandle2, L"parameter1");
      class2Parameter2Handle = ambassador.getParameterHandle(interactionClassHandle2, L"parameter2");
      class3Parameter0Handle = ambassador.getParameterHandle(interactionClassHandle3, L"parameter0");
      class3Parameter1Handle = ambassador.getParameterHandle(interactionClassHandle3, L"parameter1");
      class3Parameter3Handle = ambassador.getParameterHandle(interactionClassHandle3, L"parameter3");
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    try {
      ambassador.publishInteractionClass(requestHandle);
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    try {
      ambassador.subscribeInteractionClass(interactionClassHandle0);
      ambassador.subscribeInteractionClass(interactionClassHandle1);
      ambassador.subscribeInteractionClass(interactionClassHandle2);
      ambassador.subscribeInteractionClass(interactionClassHandle3);
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    if (!waitForAllFederates(ambassador))
      return false;

    double t = 0;
    for (unsigned i = 0; i < 100; ++i) {

      Clock clock = Clock::now();

      try {
        rti1516::ParameterHandleValueMap parameterValues;
        rti1516::VariableLengthData tag = toVariableLengthData("parameter0");
        parameterValues[requestTypeHandle] = toVariableLengthData(unsigned(Interaction1));
        ambassador.sendInteraction(requestHandle, parameterValues, tag);

      } catch (const rti1516::Exception& e) {
        std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
        return false;
      } catch (...) {
        std::wcout << L"Unknown Exception!" << std::endl;
        return false;
      }

      try {
        _receivedInteraction = false;
        Clock timeout = Clock::now() + Clock::fromSeconds(10);
        while (!_receivedInteraction) {
          if (ambassador.evokeCallback(10.0))
            continue;
          if (timeout < Clock::now()) {
            std::wcout << L"Timeout waiting for response!" << std::endl;
            return false;
          }
        }

      } catch (const rti1516::Exception& e) {
        std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
        return false;
      } catch (...) {
        std::wcout << L"Unknown Exception!" << std::endl;
        return false;
      }

      clock = Clock::now() - clock;
      t += 1e-9*clock.getNSec();
    }

    std::cout << t / 100 << std::endl;

    try {
      rti1516::ParameterHandleValueMap parameterValues;
      rti1516::VariableLengthData tag = toVariableLengthData("parameter0");
      parameterValues[requestTypeHandle] = toVariableLengthData(unsigned(Finished));
      ambassador.sendInteraction(requestHandle, parameterValues, tag);

    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    if (!waitForAllFederates(ambassador))
      return false;

    try {
      ambassador.unpublishInteractionClass(requestHandle);
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    try {
      ambassador.unsubscribeInteractionClass(interactionClassHandle0);
      ambassador.unsubscribeInteractionClass(interactionClassHandle1);
      ambassador.unsubscribeInteractionClass(interactionClassHandle2);
      ambassador.unsubscribeInteractionClass(interactionClassHandle3);
    } catch (const rti1516::Exception& e) {
      std::wcout << L"rti1516::Exception: \"" << e.what() << L"\"" << std::endl;
      return false;
    } catch (...) {
      std::wcout << L"Unknown Exception!" << std::endl;
      return false;
    }

    return true;
  }
Beispiel #19
0
void audioCallback(void* udata, uint8_t* stream0, int len) {

	int16_t* stream = (int16_t*) stream0;

	for (len >>= 2; len; len--) {
		clk.tic();

		// update controls

		// update sequencer
		seq.tic();
		glide.tic();
		float f = glide.out;
		osc1.freq = f;
		osc2.freq = f / 3.01;

		// update oscillators
		osc1.tic();
		osc2.tic();
		osc3.tic();

		float o1 = osc1.out;
		float o2 = osc2.out;
		float o3 = osc3.out;


		// o3 = (1 - o3) / 2;
		o3 = map(o3, -1, 1, 0, 0.5);
		osc1.width = o3;
		osc2.width = o3;

		// simple mix + amplification
		mix = (o1 + o2);

		// envelope
		env.tic();
		float e = env.out;

		// apply filter
		fltrSmoothCutoff.tic();
		fltr.cutoff = e * fltrSmoothCutoff.out;
		fltr.tic();

		// if (filterActive) dry = mix - fltr.out;  // hi-pass filter
		if (filterActive) dry = fltr.out;        // low-pass filter
		else dry = mix; // no filter

		// amplification envelope
		dry *= e;

		// main amplification
		dry *= amp;

		// apply reverb
		reverb.tic();

		float outL = dry + reverb.outL * 0.11;
		float outR = dry * 0.9 + reverb.outR * 0.14;

		// trim overload
		outL = mainLimiterDisto(outL);
		outR = mainLimiterDisto(outR);
		/*if (outL < -2) outL = -2;
		if (outL >  2) outL =  2;

		if (outR < -2) outR = -2;
		if (outR >  2) outR =  2;*/

		// convert to output format
		outL = 0xFFF * outL * mute;
		outL = round(outL);

		outR = 0xFFF * outR * mute;
		outR = round(outR);

		// write in buffer
		*stream++ = outL;
		*stream++ = outR;
	}
}
Beispiel #20
0
int main()
{
	RenderWindow window(VideoMode(1312, 800), "Skarlet"); /// Без тулбара, можно поменять 

	StartMenu startMenu(window);
	Pause pause(window);
	am::AudioManager mgr;

	mgr.playMusic("menu.ogg");
	startMenu.exec();

	lv::Level map;
	map.LoadFromFile("resources/maps/TestMap.tmx");
	std::vector<lv::Object> solidObj;
	std::vector<lv::Object> groundObj;
	std::vector<lv::Object> allObj;
	solidObj = map.GetObjects("solid"); // стены итд 
	groundObj = map.GetObjects("ground"); // земля, пол 
	allObj = map.GetAllObjects();


	Texture SimpleGroundEnemyRun; //Текстура врага для бега
	SimpleGroundEnemyRun.loadFromFile("resources/images/RobotWalk.png");

	Texture SimpleGroundEnemyShoot;//Текстура врага для стрельбы
	SimpleGroundEnemyShoot.loadFromFile("resources/images/RobotShooting.png");

	Animation EnemyAnimation[1];

	EnemyAnimation[0].setSpriteSheet(SimpleGroundEnemyRun); //Анимация бега врага
	EnemyAnimation[0].loadFromXml("resources/animations/RobotWalk.xml");

	EnemyAnimation[1].setSpriteSheet(SimpleGroundEnemyShoot); //Анимация стрельбы врага
	EnemyAnimation[1].loadFromXml("resources/animations/RobotShooting.xml");


	Texture heroRight; ///Текстура нашего игрока 
	heroRight.loadFromFile("resources/images/TanyaRunRight.png");

	Texture heroLeft;
	heroLeft.loadFromFile("resources/images/TanyaRunLeft.png");

	Texture heroFireLeft;
	heroFireLeft.loadFromFile("resources/images/TanyaRunShotLeft.png");

	Texture heroFireRight;
	heroFireRight.loadFromFile("resources/images/TanyaRunShotRight.png");

	Texture heroFireRunRight;
	heroFireRunRight.loadFromFile("resources/images/TanyaRunShotRight.png");

	Texture heroFireRunLeft;
	heroFireRunLeft.loadFromFile("resources/images/TanyaRunShotLeft.png");

	Animation PlayerAnim[8];
	PlayerAnim[0].setSpriteSheet(heroRight);
	PlayerAnim[0].loadFromXml("resources/animations/TanyRunRight.xml");  // Правая анимация стоя
	PlayerAnim[1].setSpriteSheet(heroLeft);
	PlayerAnim[1].loadFromXml("resources/animations/TanyRunLeft.xml"); // Левая анимация стоя
	PlayerAnim[2].setSpriteSheet(heroRight);
	PlayerAnim[2].loadFromXml("resources/animations/TanyRunRight.xml");  // Анимация бег в право 
	PlayerAnim[3].setSpriteSheet(heroLeft);
	PlayerAnim[3].loadFromXml("resources/animations/TanyRunLeft.xml");  // Анимация бег в лево

	PlayerAnim[4].setSpriteSheet(heroFireRunRight);
	PlayerAnim[4].loadFromXml("resources/animations/TanyaRunFireRight.xml"); // Стрельа на ходу право

	PlayerAnim[5].setSpriteSheet(heroFireRunLeft);
	PlayerAnim[5].loadFromXml("resources/animations/TanyaRunFireLeft.xml"); // Стрельба на ходу лево

	PlayerAnim[6].setSpriteSheet(heroFireLeft);
	PlayerAnim[6].loadFromXml("resources/animations/TanyaRunFireLeft.xml");//Стрельба стоя лево

	PlayerAnim[7].setSpriteSheet(heroFireRight);
	PlayerAnim[7].loadFromXml("resources/animations/TanyaRunFireRight.xml");//Стрельба стоя право 


	Hero her;
	her.setHeroAnimation(PlayerAnim);
	her.setHeroPossition(80, 500);
	her.setHeroAnimationSpeed(0.6f);
	her.setHeroSpeed(80);
	her.setHeroJump(6.5);
	her.setGraviForHero(3.3);
	Vector2f enmPosition(500, 450);
	SimpleGroundEnemy enm(enmPosition, "Enemy", 50, 50, EnemyAnimation);
	enm.setAnimationSpeed(0.6f);

	Kamera kamera(her, map, window);

	Clock clock;// Наши часики 
	Time time;
	float frametime = NULL;

	mgr.playMusic("level1.ogg");

	while (window.isOpen())
	{

		frametime = clock.getElapsedTime().asMilliseconds();
		time = clock.getElapsedTime();
		clock.restart();
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();

			if (event.type == sf::Event::Resized)
				pause.exec();

			if (event.type == sf::Event::KeyPressed)
			{
				if (event.key.code == sf::Keyboard::Escape)
				{
					pause.exec();
				}

			}

		}



		window.clear();
		map.Draw(window);
		her.updateAndDrawHero(frametime, time, solidObj, groundObj, window);
		enm.updateAndDraw(time, allObj, window);
		renderHpBar(her.getHeroHp() + 50, kamera.getPossition().x + 10, kamera.getPossition().y + 10, 130, 23, window, Color::Red);
		window.display();
		kamera.updateKamera();


	}

	return 0;
}
Beispiel #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;
	 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();
    }

}
Beispiel #22
0
int main() {

	srand(time(NULL));

	system("clear");

	unsigned int numeroElementos;
	do {
		cout << "Introduce el número de elementos del vector: ";
		cin >> numeroElementos;
	} while (not numeroElementos);
	

	/**		PARAMETROS PARA LAS MEDICIONES **/
	Quicksort qs;
	QuicksortInsercion qsI;
	QuicksortMediana qsM;

	unsigned int elementosInsercion = 0;
	do {
		cout << endl << "Introduzca el limite inferior para ordenar el vector segun el metodo de Insercion: ";
		cin >> elementosInsercion;
	} while (0 >= elementosInsercion);
	qsI.setElementosInsercion(elementosInsercion);


	unsigned int elementosMediana = 0;
	do {
		cout << "Introduzca el limite para usar la mediana en el quicksort: ";
		cin >> elementosMediana;
	} while (0 >= elementosMediana);
	qsM.setElementosMediana(elementosMediana);


	cout << endl;





	/**********************************************/
	/** 			MEDICIONES					**/

	Clock clock;
	Medicion quicksort, quicksortInsercion, quicksortMediana;

	vector<int> vector, aux, auxII, auxIII;

	rellenarVector(vector, numeroElementos);

	aux = vector;

	cout << endl << endl << "Número de elementos: " << numeroElementos << endl;

	/*** QUICKSORT ***/
	clock.start();
	qs.quickSort(aux, 0,  aux.size()-1);
	clock.stop();
	assert(estaOrdenado(aux));

	quicksort.appendTime(clock.elapsed());
	quicksort.appendX(numeroElementos);
	cout << endl << "  tiempo Quicksort : " << clock.elapsed() << endl;


	cout << endl;
	/*** QUICKSORT - INSERCION ***/
	for (unsigned int j = elementosInsercion; j < elementosInsercion*10; j+= elementosInsercion) {
		auxII = vector;
		assert(auxII == vector);

		qsI.setElementosInsercion(j);

		clock.start();
		qsI.quickSort(auxII, 0,  auxII.size()-1);
		clock.stop();
		assert(estaOrdenado(auxII));
		quicksortInsercion.appendTime(clock.elapsed());
		quicksortInsercion.appendX(j);
		cout << "  tiempo Quicksort-Insercion (x=" << j << "): " << clock.elapsed() << endl;
	}


	cout << endl;
	/*** QUICKSORT - MEDIANA ***/
	for (unsigned int j = elementosMediana; j < elementosMediana*10; j+=elementosMediana) {
		auxIII = vector;
		assert(auxIII == vector);
		qsM.setElementosMediana(j);

		clock.start();
		qsM.quickSort(auxIII, 0,  auxIII.size()-1);
		clock.stop();
		assert(estaOrdenado(auxIII));
		quicksortMediana.appendTime(clock.elapsed());
		quicksortMediana.appendX(j);
		cout << "  tiempo Quicksort-Mediana (x=" << j << "): " << clock.elapsed() << endl;
	}

	//COMPROBAR QUE TODOS LOS VECTORES TIENEN LOS MISMOS ELEMENTOS EN EL MISMO ORDEN
	for (unsigned int i = 0; i < aux.size(); i++) {
		assert(aux[i] == auxII[i]);
		assert(auxII[i] == auxIII[i]);
	}

	vector.clear();
	aux.clear();
	auxII.clear();
	auxIII.clear();




	guardarDatos(
		numeroElementos,
		//Como solo se usa una vez el Quicksort normal se coge el valor que tarda en ordenar
		quicksort.getTiempos()[0],
		quicksortInsercion.getTiempos(),
		quicksortInsercion.getNumElementos(),
		quicksortMediana.getTiempos(),
		quicksortMediana.getNumElementos()
	);

	return 0;
}
/**
    \fn initializeAudio
    \brief Initialize audio
*/
bool  GUIPlayback::initializeAudio(void)

{
    uint32_t state,latency, preload;
    uint32_t small_;
    uint32_t channels,frequency;

    wavbuf = 0;
    uint64_t startPts=firstPts;
    int32_t shift=0; // unit is ms, + => delay audio, -=> advance audio
    
    // if audio shift is activated, take it into account
    //
    EditableAudioTrack *ed=video_body->getDefaultEditableAudioTrack();
    if(!ed)
        return false;
    if(ed->audioEncodingConfig.shiftEnabled)
        shift=ed->audioEncodingConfig.shiftInMs;
    playbackAudio = createPlaybackFilter(startPts,shift);
    if(!playbackAudio) 
    {
        ADM_info("No audio\n");
        return false;
    }

    channels= playbackAudio->getInfo()->channels;
    frequency=playbackAudio->getInfo()->frequency;
    preload=  (frequency * channels)/5;	// 200 ms preload
    // 4 sec buffer..
    wavbuf =  (float *)  ADM_alloc((20*sizeof(float)*preload)); // 4 secs buffers
    ADM_assert(wavbuf);
    // Read a at least one block to have the proper channel mapping
    uint32_t fill=0;
    AUD_Status status;
    small_ = playbackAudio->fill(channels, wavbuf,&status);
    fill+=small_;
    // Call it twice to be sure it is properly setup
     state = AVDM_AudioSetup(frequency,  channels ,playbackAudio->getChannelMapping());
     AVDM_AudioClose();
     state = AVDM_AudioSetup(frequency,  channels ,playbackAudio->getChannelMapping());
     latency=AVDM_GetLayencyMs();
     printf("[Playback] Latency : %d ms\n",latency);
     audioLatency=latency; // ms -> us
      if (!state)
      {
          GUI_Error_HIG(QT_TR_NOOP("Trouble initializing audio device"), NULL);
          cleanupAudio();
          return false;
      }
    while(fill<preload)
    {
      if (!(small_ = playbackAudio->fill(preload-fill, wavbuf+fill,&status)))
      {
        break;
      }
      fill+=small_;
    }
    nbSamplesSent = fill/channels;  // In sample
    AVDM_AudioPlay(wavbuf, fill);
    // Let audio latency sets in...
    ticktock.reset();
    uint32_t slice=(frequency * channels)/100; // 10 ms
    // pump data until latency is over
    updateVu();
    #if 0
    while(ticktock.getElapsedMS()<latency)
    {
        if(AVDM_getMsFullness()<AUDIO_PRELOAD)
        {
          if (!(small_ = playbackAudio->fill(slice, wavbuf,&status)))
          {
            printf("[Playback] Compensating for latency failed\n");
            break;
          }
          AVDM_AudioPlay(wavbuf, slice);
        }
       ADM_usleep(10*1000);
       updateVu();
    }
    #endif
    printf("[Playback] Latency is now %u\n",ticktock.getElapsedMS());
    return true;
}
Beispiel #24
0
//
// Object class
//
Object::Object(const std::string& name, Clock& clock)
    : m_parent(NULL), m_name(name), m_fqn(name), m_clock(clock), m_kernel(clock.GetKernel())
{
}
Beispiel #25
0
int main()
{  
    RenderWindow window(VideoMode(800, 250), "Mario v0.1 Alpha");
	Texture tileSet;
	tileSet.loadFromFile("Mario_Tileset.png");

	//===========================
	PLAYER Mario(tileSet);
	//==========[Bot]============
	ENEMY  enemy[3];
	enemy[0].set(tileSet,48*16,13*16);//1lvl
	enemy[1].set(tileSet,110*16,13*16);
	enemy[2].set(tileSet,48*16,30*16);//2lvl
	/*enemy[3].set(tileSet,110*16,13*16);
	enemy[4].set(tileSet,48*16,13*16);//3lvl
	enemy[5].set(tileSet,110*16,13*16);*/
	//===========================
	Sprite tile(tileSet);
	SoundBuffer buffer;
	//==========[«вук]============
	buffer.loadFromFile("Jump.ogg");
	Sound sound(buffer);
	//==========[Ўрифты]==========
	sf::Font font;
	font.loadFromFile("arial.ttf");
	//==========[ћеню]============
	Texture menu_texture1,menu_texture2,menu_texture3,about_texture;
	menu_texture1.loadFromFile("111.png");
	menu_texture2.loadFromFile("222.png");
    menu_texture3.loadFromFile("333.png");
	about_texture.loadFromFile("about.png");
	Sprite menu1(menu_texture1),menu2(menu_texture2),menu3(menu_texture3),about(about_texture);
	if(NewGm==true) {
		NewGame:
		GameOver=false;
		Mario.rect.left=100; Mario.rect.top=180;
		Mario.sprite.setPosition(100, 180);  
		offsetX = Mario.rect.left-100; 
		enemy[0].life=true; enemy[1].life=true;
		offsetY = Mario.rect.top-180; 
		std::cout<<Mario.rect.left<<"   "<< Mario.rect.top<<std::endl;
		NewGm=false;
	}

	bool Menu=1;
	int MenuNum=0;
	menu1.setPosition(100,30);
	menu2.setPosition(100,90);
    menu3.setPosition(100,150);

	while(Menu)
	{	   
	   menu1.setColor(Color::White);
	   menu2.setColor(Color::White);
	   menu3.setColor(Color::White);
	   MenuNum=0;
	   window.clear(Color(0,0,0));

	   if (IntRect(100,30,300,50).contains(Mouse::getPosition(window))) {menu1.setColor(Color::Yellow); MenuNum=1;}
       if (IntRect(100,90,300,50).contains(Mouse::getPosition(window))) {menu2.setColor(Color::Yellow); MenuNum=2;}
       if (IntRect(100,150,300,50).contains(Mouse::getPosition(window))) {menu3.setColor(Color::Yellow); MenuNum=3;}

	   if (Mouse::isButtonPressed(Mouse::Left))
	     {
			 if (MenuNum==1) Menu=false;
			 if (MenuNum==2) {window.draw(about); window.display(); while(!Keyboard::isKeyPressed(Keyboard::Escape)) ;}
			 if (MenuNum==3)  {window.close();Menu=false;}

	     }
		window.draw(menu1);
        window.draw(menu2);
		window.draw(menu3);
		window.display();
	}
	//==========[¬рубаем музыку в игру]============
	Music music;
    music.openFromFile("Mario_Theme.ogg");
    music.play();
	//==================[»гра]=====================
	Clock clock;

    while (GameOver==false)
    { 
		float time = clock.getElapsedTime().asMicroseconds();
		clock.restart();
		time = time/500;
		if (time > 20) time = 20; 

        Event event;
        while (window.pollEvent(event))
        {
            if (event.type == Event::Closed)      
                window.close();
		}
		if (Keyboard::isKeyPressed(Keyboard::Left)) Mario.dx=-0.1; 
	    if (Keyboard::isKeyPressed(Keyboard::Right)) Mario.dx=0.1;
	    if (Keyboard::isKeyPressed(Keyboard::Up)) if (Mario.onGround) { Mario.dy=-0.27; Mario.onGround=false;  sound.play(); }
	 
		 Mario.update(time);
		 enemy[0].update(time);
		 enemy[1].update(time);
		 enemy[2].update(time);

		 if  (Mario.rect.intersects(enemy[0].rect))
		 {
			 if (enemy[0].life) {
				 if (Mario.dy>0) { enemy[0].dx=0; Mario.dy=-0.2; enemy[0].life=false;}
				 else { Mario.dy=-0.27; GameOver=true; }
			 }
		 }
		 if  (Mario.rect.intersects(enemy[1].rect))
		 {
			 if (enemy[1].life) {
				 if (Mario.dy>0) { enemy[1].dx=0; Mario.dy=-0.2; enemy[1].life=false;}
				 else { Mario.dy=-0.27; GameOver=true; }
			 }
		 }
		 if  (Mario.rect.intersects(enemy[2].rect))
		 {
			 if (enemy[2].life) {
				 if (Mario.dy>0) { enemy[2].dx=0; Mario.dy=-0.2; enemy[2].life=false;}
				 else { Mario.dy=-0.27; GameOver=true; }
			 }
		 }
		 if (Mario.rect.left>200) offsetX = Mario.rect.left-200;
		 window.clear(Color(107,140,255));
		 for (int i=0; i<H; i++)
			 for (int j=0; j<W; j++)
			 { 
				switch(TileMap[i][j]) {
					case 'P':  tile.setTextureRect( IntRect(143-16*3,112,16,16)); break; 
					case 'k': tile.setTextureRect( IntRect(143,112,16,16)); break; 
					case 'c': tile.setTextureRect( IntRect(143-16,112,16,16)); break; 
					case 't': tile.setTextureRect( IntRect(0,47,32,95-47)); break; 
					case 'm': tile.setTextureRect( IntRect(96,6,202-47,111)); break; 
					case 'g': tile.setTextureRect( IntRect(0,16*9-5,3*16,16*2+5)); break; 
					case 'G': tile.setTextureRect( IntRect(145,222,222-145,255-222)); break; 
					case 'd': tile.setTextureRect( IntRect(0,106,74,127-106)); break; 
					case 'w': tile.setTextureRect( IntRect(99,224,140-99,255-224)); break; 
					case 'r': tile.setTextureRect( IntRect(143-32,112,16,16)); break; 
					default: continue;
				}

  			    tile.setPosition(j*16-offsetX,i*16 - offsetY) ; 
		        window.draw(tile);
			}
		window.draw(Mario.sprite);
	    window.draw(enemy[0].sprite);
		window.draw(enemy[1].sprite);
		window.draw(enemy[2].sprite);
		window.display();
    }
	while(Win)
	{	
		GameOver=false;
		window.clear(Color(0,0,0));
		sf::Text text("You Win! :3", font); 
		text.setPosition(100,30);
		text.setCharacterSize(30);
		text.setStyle(sf::Text::Bold);
		text.setColor(sf::Color::Yellow);
		window.draw(text);	
		sf::Text text1("Press ESC", font); 
		text1.setPosition(100,60);
		text1.setCharacterSize(30);
		text1.setStyle(sf::Text::Bold);
		text1.setColor(sf::Color::Red);
		window.draw(text1);	
		window.display();
		if (Keyboard::isKeyPressed(Keyboard::Escape)) { goto NewGame; NewGm=true; }
	}
	while(GameOver)
	{	   
		window.clear(Color(0,0,0));
		sf::Text text("Game Over :c", font); 
		text.setPosition(100,30);
		text.setCharacterSize(30);
		text.setStyle(sf::Text::Bold);
		text.setColor(sf::Color::Red);
		window.draw(text);	
		sf::Text text1("Press ESC", font); 
		text1.setPosition(100,60);
		text1.setCharacterSize(30);
		text1.setStyle(sf::Text::Bold);
		text1.setColor(sf::Color::Red);
		window.draw(text1);	
		window.display();
		if (Keyboard::isKeyPressed(Keyboard::Escape)) { goto NewGame; NewGm=true; }
	}
    return 0;
}
Beispiel #26
0
namespace S_M_T {
    const Time DISAPPEAR_DELAY=seconds(5), REAPPEAR_DELAY=seconds(2);
    bool thisRunning, changing;
    Clock clock;
    long long int date;
    unsigned char round;
    S_M::ScreenText movementMessage, escapeMessage, spaceBarMessage;
    void init() {
        thisRunning=true;
        round=0;
        changing=false;
        date=0;
        if(INFO::backwardKey == Keyboard::O) {
            movementMessage.set("Use ',.aoe to Control Thrust", Vector2f(0,0), Color::White, &INFO::spaceFont, 24, 10, true, 0);
        } else {
            movementMessage.set("Use qweasd to Control Thrust", Vector2f(0,0), Color::White, &INFO::spaceFont, 24, 10, true, 0);
        }
        escapeMessage.set("Hold Escape to Enter Sortie Vortex", Vector2f(0, 0), Color::White, &INFO::spaceFont, 24, 10, false, 0);
        spaceBarMessage.set("Hold Spacebar to Stabilize", Vector2f(0,0), Color::White, &INFO::spaceFont, 24, 10, false, 0);   //see the text class for explaination
    }
    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;
        }
    }
    void display(bool ending) {
        if(!thisRunning || ending) return;
        switch(round) {
            case 0:
                INFO::window.draw(movementMessage.draw());
                break;
            case 1:
                INFO::window.draw(spaceBarMessage.draw());
                break;
            case 2:
                INFO::window.draw(escapeMessage.draw());
                break;
            case 3:
                thisRunning=false;
                break;
        }
    }
}
void StartGame()
{
	//players last shoot time
	float lastShootPlayer = 0;

	//map struct
	tileMap myMap;

	Sprites mySprites;
	mySprites.InitImages();

	vector<Chest> chests;

	vector<Enemy> enemies;
	InitEnemies(enemies, mySprites);

	//create player
	Player player(mySprites.heroTexture, PLAYER_POSITION_X, PLAYER_POSITION_Y, PLAYER_WIDTH, PLAYER_HEIGHT, "Hero", 6);

	RenderWindow window(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Game");

	view.reset(FloatRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT));

	//clock
	Clock clock;
	Clock gameTimer;

	//last player hit time
	float hitTimer = 0;

	//game time
	float gameTime;

	//current level
	int level = 1;

	while (window.isOpen())
	{
		level = InitializeLevel(player);

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

		//game time
		if (player.health > 0)
		{
			gameTime = gameTimer.getElapsedTime().asSeconds();
		}

		//event
		ProcessEvents(window);

		player.Update(time, gameTime, lastShootPlayer, mySprites.wallBackgroundSprite, view);

		UpdateEnemies(enemies, time, gameTime, window, level);

		AddChest(level, chests, enemies);
		CheckEnemyCollidesPlayer(gameTime, hitTimer, player, enemies);

		//view
		window.setView(view);

		/////////////////////////////
		window.clear();

		DrawBackground(window, mySprites.wallBackgroundSprite, mySprites.floorBackgroundSprite);

		DrawPlayersHealth(player.health, window, view);

		DrawEnemies(window, level, enemies);

		myMap.drawMap(window, IsLevelCleared(level, enemies));

		UpdateChests(chests, window, player);

		UpdateBullets(player, enemies, gameTime, bullets, time, window, mySprites);

		DrawPlayer(player, window);

		window.display();
		/////////////////////////////
	}
}
volatile char motionTrigger(char key, char first)
{
	uint8_t i;
	uint16_t val;
	static uint16_t lv[3];
	static uint8_t threshold = 2;

	if(key == LEFT_KEY)
	{
		if(threshold > 0) threshold--;
		first = 1;
	}
	if(key == RIGHT_KEY)
	{
		if(threshold < 4) threshold++;
		first = 1;
	}

	if(first)
	{
		sleepOk = 0;
		clock.tare();
		lcd.cls();
		menu.setTitle(TEXT("Motion Sensor"));
		menu.setBar(TEXT("RETURN"), BLANK_STR);

		lcd.drawLine(10, 22, 84-10, 22);
		lcd.drawLine(11, 21, 11, 23);
		lcd.drawLine(84-11, 21, 84-11, 23);
		lcd.drawLine(12, 20, 12, 24);
		lcd.drawLine(84-12, 20, 84-12, 24);
		lcd.drawLine(13, 20, 13, 24);
		lcd.drawLine(84-13, 20, 84-13, 24);
		lcd.setPixel(42, 21);
		lcd.setPixel(42+10, 21);
		lcd.setPixel(42-10, 21);
		lcd.setPixel(42+20, 21);
		lcd.setPixel(42-20, 21);

		i = threshold * 10;
		lcd.drawLine(42-3-20+i, 16, 42+3-20+i, 16);
		lcd.drawLine(42-2-20+i, 17, 42+2-20+i, 17);
		lcd.drawLine(42-1-20+i, 18, 42+1-20+i, 18);
		lcd.setPixel(42-20+i, 19);

		lcd.writeStringTiny(19, 25, TEXT("SENSITIVITY"));

		lcd.update();
		lcd.backlight(0);
		hardware_flashlight(0);
		_delay_ms(50);
		for(i = 0; i < 3; i++)
		{
			lv[i] = (uint16_t)hardware_readLight(i);
		}
	}

	uint8_t thres = 4 - threshold + 2;
	if((4 - threshold) > 2) thres += ((4 - threshold) - 1) * 2;

	for(i = 0; i < 3; i++)
	{
		val = (uint16_t)hardware_readLight(i);
		if(clock.eventMs() > 1000 && val > thres && (val < (lv[i] - thres) || val > (lv[i] + thres)))
		{
			clock.tare();
			shutter_capture();
		}
		lv[i] = val;
	}

	if(key == FL_KEY)
	{
		sleepOk = 1;
		lcd.backlight(255);
		return FN_CANCEL;
	}

	return FN_CONTINUE;
}
void RodSoundApp::update()
{
  if (!running) return;
  
  if (curSample % 5000 == 0 && curSample != 0 && c.getTicks() % multiSample == 0) {
    std::cout << curSample << " / " << BufferSize << " (" << (curSample*100.0)/BufferSize << "%)\n";
    PROFILER_PRINT_ELAPSED();
    PROFILER_RESET_ALL();
    std::cout << "\n";
  }
  
  if (curSample >= BufferSize || stopNow) { // We're done!
    sampleBuffer[0] = 0.0; // To prevent the click of forces suddenly being applied
    double max = 0;
    for (int i=0; i<BufferSize; i++) {
      max = std::max(max, std::fabs(sampleBuffer[i]));
    }
    std::cout << "Max1: " << max << "\n";
    uint16_t buffer[BufferSize];
    for (int i=0; i<BufferSize; i++) {
      buffer[i] = toSample(sampleBuffer[i], max);
    }
    writeWAVData((constants::ResultPath+"result.wav").data(), buffer,
                 curSample * sizeof(uint16_t), SampleRate, 1);
    
    sampleBuffer2[0] = 0.0;
    max = 0;
    for (int i=0; i<BufferSize; i++) {
      max = std::max(max, std::fabs(sampleBuffer2[i]));
    }
    std::cout << "Max2: " << max << "\n";
    for (int i=0; i<BufferSize; i++) {
      buffer[i] = toSample(sampleBuffer2[i], max);
    }
    writeWAVData((constants::ResultPath+"result2.wav").data(), buffer,
                 curSample * sizeof(uint16_t), SampleRate, 1);
    
    sampleBuffer3[0] = 0.0;
    max = 0;
    for (int i=0; i<BufferSize; i++) {
      max = std::max(max, std::fabs(sampleBuffer3[i]));
    }
    std::cout << "Max3: " << max << "\n";
    for (int i=0; i<BufferSize; i++) {
      buffer[i] = toSample(sampleBuffer3[i], max);
    }
    writeWAVData((constants::ResultPath+"result3.wav").data(), buffer,
                 curSample * sizeof(uint16_t), SampleRate, 1);
    
    fe.writeMPEG("result");
    std::cout << "Total simulation time: " << app::getElapsedSeconds() << "\n"; // FIXME: This is inaccurate
    
    running = false;
    return;
  }
  
  PROFILER_START("Update");
  
  c.suggestTimestep(1.0 / (real) SampleRate / multiSample);
  // FIXME: Normally the frame exporter would suggest a timestep, but this interferes with the audio
  // recording, as it assumes all timesteps are 1/SampleRate. However, any error the frame exporter
  // experiences is small since 1/60 >> 1/SampleRate.
  // fe.suggestTimestep(c);
  
  Vec3e mp;
  if (isMouseDown) mp << mousePosition.x, mousePosition.y, mousePosition.z;
  mouseSpring->setMouse(mp, isMouseDown);
  
  if (!integrator->integrate(c)) throw;
  
  /// Update Bishop frame
  r->next().updateReferenceFrames(r->cur());
  
  // Sound Calculations
  if (c.getTicks() % multiSample == 0) {
    real sample = 0;
    real sample2 = 0;
    real avgX = 0;
    VecXe jerkVec = r->next().dVel - r->cur().dVel;
    for (int i=1; i<r->numCPs()-1; i++) {
      avgX += r->next().VEL(i).x();
      
      // Calculate jerk
      Vec3e jerk = jerkVec.segment<3>(3*i);
      // Project jerk to transverse plane
      Vec3e tPlaneNormal = (r->next().edge(i-1) + r->next().edge(i)).normalized();
      jerk = jerk - jerk.dot(tPlaneNormal) * tPlaneNormal; // Vector rejection of jerk from tPlaneNormal
      
      /*
      real m0 = r->restVoronoiLength(i)*constants::pi*r->radius()*r->radius()*constants::rhoAir;
      // Rotation to align system so that the cylinder is coaxial with the z-axis
      Eigen::Quaternion<real> q = Eigen::Quaternion<real>::FromTwoVectors(tPlaneNormal, Vec3e(0, 0, 1));
      Vec3e rotJerk = q * jerk;
      rotJerk = rotJerk.cwiseProduct(Vec3e(2.0*m0, 2.0*m0, m0));
      
      // Calculate sample contribution
      Vec3e earVec = CtoE(eyePos) - r->next().points[i].pos;
      sample +=  (q * earVec).dot(rotJerk) / (4.0 * constants::pi * constants::cAir * earVec.dot(earVec));
      
      earVec = ear2Pos - r->next().points[i].pos;
      sample2 +=  (q * earVec).dot(rotJerk) / (4.0 * constants::pi * constants::cAir * earVec.dot(earVec));
      */
       
      
      Vec3e earVec = CtoE(eyePos) - r->next().POS(i);
      // Calculate sample contribution
      sample += r->getCS()[i].calcSample(earVec, jerk);
    
      earVec = ear2Pos - r->next().POS(i);
      sample2 += r->getCS()[i].calcSample(earVec, jerk);
    }
    avgX = avgX/(r->numCPs()-2);
    sampleBuffer[curSample] = sample;
    sampleBuffer2[curSample] = sample2;
    
    sampleBuffer3[curSample] = r->next().VEL(r->numCPs()/2).x() - avgX;
    
    curSample++;
  }
  
  // Swap Rods
  r->swapRods();

  c.increment();
  PROFILER_STOP("Update");
}
Beispiel #30
0
void Game::startGame()
{
	using namespace sf;

	RenderWindow window(VideoMode(static_cast<int>(width), static_cast<int>(height)), "Pong", Style::Fullscreen);
	window.setFramerateLimit(60);

	bool isMainMenu = true, isHowToPlayMenu = false, isRoundWinMenu = false, isGameOverMenu = false;

	bool isPlaying = false;

	bool isWin = false, isPlayerWin = false, isGameOver = false;

	int playerScore = 0, cpuScore = 0;

	Clock clock;

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

		// Record deltatime every frame
		float dt = clock.restart().asSeconds();

		while (window.pollEvent(event))
		{
			// Exit the game
			if ((event.type == Event::Closed) || Keyboard::isKeyPressed(Keyboard::Escape))
			{
				window.close();
			}

			// Start the game
			else if (event.type == Event::KeyPressed)
			{
				if (isMainMenu)
				{
					isMainMenu = false;
					isHowToPlayMenu = false;
					isRoundWinMenu = false;
					isGameOverMenu = false;
					isPlaying = false;
					isWin = false;
					isPlayerWin = false;
					isGameOver = false;

					if (Keyboard::isKeyPressed(Keyboard::H))
					{
						isHowToPlayMenu = true;
					}
					else
					{
						isPlaying = true;
					}
				}
				else if (isHowToPlayMenu)
				{
					isHowToPlayMenu = false;
					isMainMenu = true;
				}
				else
				{
					if (isRoundWinMenu)
					{
						isRoundWinMenu = false;
						if (!isGameOver)
						{
							isPlaying = true;
						}
					}
					else if (isGameOverMenu)
					{
						isGameOverMenu = false;
						isMainMenu = true;
						isPlaying = false;
						isGameOver = false;
					}

					isWin = false;
					isPlayerWin = false;
				}
			}
		}

		// Use up and down arrow keys or W and S keys for paddle movement
		if (isPlaying && (Keyboard::isKeyPressed(Keyboard::Up) || Keyboard::isKeyPressed(Keyboard::W)))
		{
			player.move(dt, true);
		}

		if (isPlaying && (Keyboard::isKeyPressed(Keyboard::Down) || Keyboard::isKeyPressed(Keyboard::S)))
		{
			player.move(dt, false);
		}

		if (isPlaying)
		{
			ball.move(dt);

			// Reflect ball left or right when collided with a paddle
			if (!ball.isLeft())
			{
				if (collisionManager.isCollision(ball, cpu))
					ball.toggleHorizontalDirection();
			}
			else
			{
				if (collisionManager.isCollision(ball, player))
					ball.toggleHorizontalDirection();
			}

			// Reflect ball up or down when collided with top or bottom walls
			if ((ball.getBall().getPosition().y < ball.getBall().getRadius()) || ball.getBall().getPosition().y > (height - ball.getBall().getRadius()))
			{
				ball.wallCollision(height / 2.0f);
			}

			// Score player or cpu and go to next round until game is over
			if (ball.getBall().getPosition().x < 1)
			{
				++cpuScore;
				cpuScoreText.setString(std::to_string(cpuScore));
				cpuScoreText.setOrigin(cpuScoreText.getLocalBounds().width / 2.0f, cpuScoreText.getLocalBounds().height / 2.0f);
				cpuScoreText.setPosition(width * 0.75f, cpuScoreText.getPosition().y);

				isPlaying = false;
				isWin = true;
				isPlayerWin = false;
				isRoundWinMenu = true;
				if (static_cast<unsigned int>(abs(cpuScore - playerScore)) >= scoreDifferenceForWin)
				{
					isGameOver = true;
					isGameOverMenu = true;
					playerScore = 0;
					cpuScore = 0;
				}
			}
			else if (ball.getBall().getPosition().x > width)
			{
				++playerScore;
				playerScoreText.setString(std::to_string(playerScore));
				playerScoreText.setOrigin(playerScoreText.getLocalBounds().width / 2.0f, playerScoreText.getLocalBounds().height / 2.0f);
				playerScoreText.setPosition(width / 4.0f, playerScoreText.getPosition().y);

				isPlaying = false;
				isWin = true;
				isPlayerWin = true;
				isRoundWinMenu = true;
				if (static_cast<unsigned int>(abs(playerScore - cpuScore)) >= scoreDifferenceForWin)
				{
					isGameOver = true;
					isGameOverMenu = true;
					playerScore = 0;
					cpuScore = 0;
				}
			}

			// CPU follows ball's y direction if the ball is heading the right direction
			if (!ball.isLeft())
			{
				if (ball.getBall().getPosition().y < cpu.getPaddle().getPosition().y)
				{
					cpu.move(dt, true);
				}
				else
				{
					cpu.move(dt, false);
				}
			}

			// CPU goes back to the middle
			else
			{
				if ((cpu.getPaddle().getPosition().y < ((height / 2.0f) - (cpu.getPaddle().getLocalBounds().height / 10.0f))) || 
					(cpu.getPaddle().getPosition().y > ((height / 2.0f) + (cpu.getPaddle().getLocalBounds().height / 10.0f))))
				{
					if (cpu.getPaddle().getPosition().y > (height / 2.0f))
					{
						cpu.move(dt, true);
					}
					else
					{
						cpu.move(dt, false);
					}
				}
			}
		}

		// Draw the game
		window.clear(Color(200, 200, 200, 255));

		if (!isPlaying)
		{
			// Round win
			if (isWin)
			{
				if (isPlayerWin)
				{
					for (sf::Text text : playerWinMenu)
						window.draw(text);
				}
				else
				{
					for (sf::Text text : cpuWinMenu)
						window.draw(text);
				}

				nextRound(player, cpu, ball);
			}

			// Game over
			else if (isGameOver)
			{
				for (sf::Text text : gameOverMenu)
					window.draw(text);

				nextRound(player, cpu, ball);
			}

			// How to play menu
			else if (isHowToPlayMenu)
			{
				for (sf::Text text : howToPlayMenu)
					window.draw(text);
			}

			// Main menu
			else
			{
				for (sf::Text text : menu)
					window.draw(text);
			}
		}
		else
		{
			for (sf::RectangleShape rectangle : background)
				window.draw(rectangle);

			window.draw(player.getPaddle());
			window.draw(cpu.getPaddle());
			window.draw(ball.getBall());

			for (sf::Text text : scoreLabels)
				window.draw(text);

			window.draw(playerScoreText);
			window.draw(cpuScoreText);
		}

		window.display();
	}
}