void RenderState::WindowInterface(sel::State &p_lua_state, sf::RenderWindow &p_window) { auto lua_interface = p_lua_state["interface"]; lua_interface["createWindow"] = [&p_window] (int p_w, int p_h, int p_bpp, int p_fps, const std::string &p_title) -> void { //Check for negative values - no support for unsigned types in Selene if(p_w < 0 || p_h < 0 || p_bpp < 0 || p_fps < 0) throw std::runtime_error("Invalid video mode requested"); p_window.create(sf::VideoMode(p_w, p_h, p_bpp), p_title, sf::Style::None); p_window.setFramerateLimit(p_fps); p_window.setKeyRepeatEnabled(false); return; }; lua_interface["closeWindow"] = [&p_window] () -> void { p_window.close(); return; }; lua_interface["resizeWindow"] = [&p_window] (int p_w, int p_h) -> void { //Check for negative values - no support for unsigned types in Selene if(p_w < 0 || p_h < 0) throw std::runtime_error("Invalid video mode requested"); p_window.setSize(sf::Vector2u(p_w, p_h)); return; }; return; }
int main(){ window.create(sf::VideoMode((unsigned int)windowWidth,(unsigned int)windowHeight),"MyWindow"); window.setFramerateLimit(60); Setup(); running=true; while(running){ while(window.pollEvent(event)){ if(event.type==sf::Event::Closed) running=false; else if(event.type==sf::Event::Resized) ReshapeWindow((float)event.size.width,(float)event.size.height); } if (currentState == MAIN) { cmain.HandleKeyboard(); cmain.mouseControl(); } else if (currentState == GAME) { cgame.HandleKeyboard(); handleKeyboard(); } Display(); window.display(); } return 0; }
void StateBasedGame::handleEvents(sf::RenderWindow& container) { sf::Event event; while (container.pollEvent(event)) { if (event.type == sf::Event::Closed) container.close(); if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::Escape) container.close(); if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::F11) { if(!winState.fullscreen) { container.create(winState.mode, winState.title, sf::Style::Fullscreen, winState.settings); container.setVerticalSyncEnabled(winState.vSync); container.setMouseCursorVisible(winState.cursor); } else { container.create(winState.mode, winState.title, sf::Style::Default, winState.settings); container.setVerticalSyncEnabled(winState.vSync); container.setMouseCursorVisible(winState.cursor); } winState.fullscreen = !winState.fullscreen; } #ifdef DEBUG if(event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::F12) { Debug::OVERLAY_ON = !Debug::OVERLAY_ON; } #endif if(!enterTransition && !leaveTransition && currentState->isInitialized()) { currentState->handleEvents(event, *this); } } }
void toggleFullscreen() { if (!bfullscreen) { screenW = VideoMode::getDesktopMode().width; screenH = VideoMode::getDesktopMode().height; } else { screenW = 800; screenH = 600; } mainWindow.create(sf::VideoMode(screenW, screenH),"SBRTS"); theMap.setViewSize(screenW, screenH); debug("Switching screen to %d:%d",screenW,screenH); bfullscreen = !bfullscreen; }
int main(int argc, char** argv) { srand((unsigned)time(nullptr)); window.create(sf::VideoMode(800, 600), "sfml", sf::Style::Titlebar || sf::Style::Close); window.setFramerateLimit(60); window.setMouseCursorVisible(false); sf::Listener::setPosition(400, 300, -400); font.init(); walls.init(); player.init(); stars.resize(100); sort(stars.begin(), stars.end(), [](const Star& a, const Star& b) { return a.getSpeed() < b.getSpeed(); }); while (window.isOpen()) { sf::Event e; while (window.pollEvent(e)) { switch (e.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: if (e.key.code == sf::Keyboard::Escape) window.close(); break; default: break; } } window.clear(); update(); draw(); window.display(); } return 0; }
inline void recreateWindow() { if(renderWindow.isOpen()) renderWindow.close(); renderWindow.create({width, height}, title, fullscreen ? sf::Style::Fullscreen : sf::Style::Default, sf::ContextSettings{0, 0, antialiasingLevel, 0, 0}); renderWindow.setSize(Vec2u(width * pixelMult, height * pixelMult)); renderWindow.setVerticalSyncEnabled(vsync); renderWindow.setFramerateLimit(fpsLimited ? maxFPS : 0); inputState.reset(); mustRecreate = false; onRecreation(); }
int main() { window.create(sf::VideoMode(800, 600), "Breakfree"); window.setVerticalSyncEnabled(true); //, sf::Style::Close|sf::Style::Titlebar); if (!font.loadFromFile("Nirmala.ttf")) return EXIT_FAILURE; Levels lv; Paddle pad; InputManager input; while (window.isOpen()) { switch (level) { case 0: lv.loadLv0(); break; } while (playing) { input.ExecuteEvents(window); pad.Update(); window.clear(); // ------draw graphics here------- sf::Text text("Score: " + std::to_string(score), font, 20); text.setPosition(660, 220); window.draw(text); lv.Draw(window); window.draw(pad.sprite); window.draw(pad.ball); window.display(); // ----------------------- } } return 0; }
int main() { using namespace sf; Color bg = randCol(); bool run = true; unsigned score = 0; VideoMode v = VideoMode::getDesktopMode(); v.width = 1; v.height = 1; w1.create(v, "Score: 0", Style::None); while (run) { Event event; while (w1.pollEvent(event)) { switch (event.type) { case Event::Closed: run = false; break; case Event::MouseButtonReleased: { std::stringstream scoreStream; scoreStream << "Score: " << ++score; w1.setTitle(scoreStream.str()); w1.setPosition(randPos()); bg = randCol(); break; } default: break; } } w1.clear(bg); w1.display(); } w1.close(); }
void Game::Start() { if (_gameState != Uninitialized) return; _mainWindow.create(sf::VideoMode(1280, 720), "BIT GAME"); _mainWindow.setIcon(BitGameIcon.width, BitGameIcon.height, BitGameIcon.pixel_data); //_p1.load("Images/Player.png"); _p1.setPosition(1280/2, 720/2); _p1.setOrigin(25, 45); _p1.setFillColor(sf::Color(0,0,255,255)); _p1.setRadius(10.f); _gameState = Game::ShowingSplash; while (!IsExiting()) { GameLoop(); } _mainWindow.close(); }
void Setup::setOptions( sf::RenderWindow& window) { //sf::ContextSettings settings window.create(sf::VideoMode(800, 608), "MASim", sf::Style::Default, sf::ContextSettings(32)); window.setVerticalSyncEnabled(true); window.setFramerateLimit(60); /* // Load an OpenGL texture. // We could directly use a sf::Texture as an OpenGL texture (with its Bind() member function), // but here we want more control on it (generate mipmaps, ...) so we create a new one from an image // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glClearDepth(1.f); // Setup a perspective projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.f, 1.f, 1.f, 500.f);*/ }
// Program entry point int main(int argc, char ** argv) { titleImg.loadFromFile("assets/title.png"); sf::SoundBuffer sb; sb.loadFromFile("assets/avalanche.ogg"); boulderSound.setBuffer(sb); boulderSound.setLoop(true); boulderSound.play(); sf::SoundBuffer sb2; sb2.loadFromFile("assets/death.ogg"); fallingSound.setBuffer(sb2); fallingSound.setRelativeToListener(true); sf::SoundBuffer sb3; sb3.loadFromFile("assets/jump.wav"); jumpingSound.setBuffer(sb3); jumpingSound.setRelativeToListener(true); sf::SoundBuffer sb4; sb4.loadFromFile("assets/POL-flash-run-short.wav"); musicSound.setBuffer(sb4); musicSound.setRelativeToListener(true); musicSound.setVolume(15.f); musicSound.setLoop(true); musicSound.play(); sf::SoundBuffer sb5; sb5.loadFromFile("assets/footsteps.ogg"); feetSound.setRelativeToListener(true); feetSound.setBuffer(sb5); feetSound.setLoop(true); feetSound.setVolume(50); feetSound.play(); sf::SoundBuffer sb6; sb6.loadFromFile("assets/bump.ogg"); bumpSound.setRelativeToListener(true); bumpSound.setBuffer(sb6); bumpSound.setVolume(40); sf::SoundBuffer sb7; sb7.loadFromFile("assets/gem.ogg"); gemSound.setRelativeToListener(true); gemSound.setBuffer(sb7); gemSound.setVolume(60); sf::SoundBuffer sb8; sb8.loadFromFile("assets/Powerup3.wav"); powerSound.setRelativeToListener(true); powerSound.setBuffer(sb8); powerSound.setVolume(80); sf::SoundBuffer sb9; sb9.loadFromFile("assets/alert.ogg"); alertSound.setRelativeToListener(true); alertSound.setBuffer(sb9); //powerSound.setVolume(80); // Create the SFML window window.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "A Bolder Escape"); while (window.isOpen()) { events(); if (!menu) logic(); render(); } return 0; }
void Administrador::ventanaPrincipal() { sf::Texture text_fondo, txt_lateral, txt_nuevaRuta, text_consultar, text_eliminar, text_salir; sf::Sprite back_fondo, back_lateral, back_nuevaRuta, back_consultar, back_eliminar, back_salir; sf::Texture txt_puntos[23]; sf::Sprite back_puntos[23]; window.create(sf::VideoMode(1280,680),"Transportes Inter-Urbanos"); window.setPosition(sf::Vector2i(50,0)); text_fondo.loadFromFile("mapa.png"); back_fondo.setTexture(text_fondo); txt_lateral.loadFromFile("barra_lateral.png"); back_lateral.setTexture(txt_lateral); back_lateral.setPosition(1100,0); txt_nuevaRuta.loadFromFile("botones/nueva_ruta.png"); back_nuevaRuta.setTexture(txt_nuevaRuta); back_nuevaRuta.setPosition(1105,60); text_consultar.loadFromFile("botones/consultar_ruta.png"); back_consultar.setTexture(text_consultar); back_consultar.setPosition(1105,130); text_eliminar.loadFromFile("botones/eliminar_ruta.png"); back_eliminar.setTexture(text_eliminar); back_eliminar.setPosition(1105,200); text_salir.loadFromFile("botones/btnSalir.png"); back_salir.setTexture(text_salir); back_salir.setPosition(1105,270); ruta->llenarPuntos(); ruta->setAdyacencias(); ruta->setCaminos(); ruta->setPesos(); ruta->rutasPosibles(); while(window.isOpen()) { sf::Event event; while(window.pollEvent(event)) { mouse = window.mapPixelToCoords(sf::Mouse::getPosition(window)); } if(utility->clickSprite(back_nuevaRuta,mouse)) { crearRuta(); } if(utility->clickSprite(back_consultar,mouse)) { ventanaConsultarCaminos(); } if(utility->clickSprite(back_eliminar,mouse)) { ventanaEliminar(); } if(utility->clickSprite(back_salir,mouse)) { window.close(); } window.draw(back_fondo); window.draw(back_lateral); window.draw(back_nuevaRuta); window.draw(back_consultar); window.draw(back_eliminar); window.draw(back_salir); dibujarPuntos(txt_puntos, back_puntos); drawLineas(); window.display(); } }
int main() { sf::ContextSettings settings; settings.antialiasingLevel = 8; //smoother shapes window.create(sf::VideoMode(800, 600), "AKB48 Ongaku Geimu (alpha) v0.4", sf::Style::Default, settings); window.setVerticalSyncEnabled(true); /* window.setMouseCursorVisible(false); // Hide cursor sf::View fixed = window.getView(); // Create a fixed view // Load image and create sprite sf::Texture mouseTexture; mouseTexture.loadFromFile("cursors/mayuyu.png"); sf::Sprite mouseSprite(mouseTexture); mouseSprite.rotate(-45); */ srand(time(NULL)); //seed random based on time //load fonts sf::Font gameFont; if (!gameFont.loadFromFile("gothic.ttf")) { //error std::cout << "Cannot load font\n"; } sf::Font japaneseFont; if (!japaneseFont.loadFromFile("msmincho.ttc")) { //error std::cout << "Cannot load font\n"; } //load background sf::Texture backTexture; if (!backTexture.loadFromFile("title_screen.png")) { //error } backTexture.setSmooth(true); backTexture.setRepeated(false); sf::Sprite backSprite; backSprite.setTexture(backTexture); backSprite.setColor(sf::Color(255, 255, 255, 224)); //semi-transparent //Load title text sf::Text titleText; titleText.setCharacterSize(50); //load buttons sf::RectangleShape startButton(sf::Vector2f(300,100)); startButton.setFillColor(sf::Color(200, 50, 5, 128)); startButton.setOutlineThickness(5); startButton.setOutlineColor(sf::Color(200, 50, 5, 128)); startButton.setPosition(250, 250); sf::RectangleShape createButton(sf::Vector2f(300, 100)); createButton.setFillColor(sf::Color(10, 150, 55, 192)); createButton.setOutlineThickness(5); createButton.setOutlineColor(sf::Color(10, 150, 55, 192)); createButton.setPosition(250, 400); //load button text sf::Text startText; startText.setCharacterSize(50); sf::Text createText; createText.setCharacterSize(40); //load music player graphics //music player black container sf::RectangleShape musicBox(sf::Vector2f(311, 30)); musicBox.setFillColor(sf::Color(32, 32, 32, 224)); musicBox.setPosition(sf::Vector2f(484, 565)); //play button sf::CircleShape playButton; playButton.setPointCount(3); playButton.setRotation(210); playButton.setRadius(10); playButton.setFillColor(sf::Color(224, 224, 224, 224)); playButton.setOutlineColor(sf::Color(128, 128, 128, 224)); playButton.setPosition(sf::Vector2f(498, 593)); //stop button sf::CircleShape stopButton; stopButton.setPointCount(4); stopButton.setRadius(11); stopButton.setRotation(45); stopButton.setFillColor(sf::Color(224, 224, 224, 224)); stopButton.setOutlineColor(sf::Color(128, 128, 128, 224)); stopButton.setPosition(sf::Vector2f(523, 565)); //skip left button sf::CircleShape skipLeftButton; skipLeftButton.setPointCount(3); skipLeftButton.setRotation(30); skipLeftButton.setRadius(5); skipLeftButton.setFillColor(sf::Color(224, 224, 224, 224)); skipLeftButton.setOutlineColor(sf::Color(128, 128, 128, 224)); //skip right button sf::CircleShape skipRightButton; skipRightButton.setPointCount(3); skipRightButton.setRotation(210); skipRightButton.setRadius(5); skipRightButton.setFillColor(sf::Color(224, 224, 224, 224)); skipRightButton.setOutlineColor(sf::Color(128, 128, 128, 224)); //music text used for displaying time and song title sf::Text musicText; musicText.setFont(gameFont); musicText.setCharacterSize(12); //duration bar sf::RectangleShape timeDurBar(sf::Vector2f(100, 10)); timeDurBar.setFillColor(sf::Color(160, 160, 160, 224)); timeDurBar.setPosition(sf::Vector2f(632, 582)); //current time bar sf::RectangleShape curTimeBar(sf::Vector2f(5, 12)); curTimeBar.setFillColor(sf::Color(224, 224, 224, 224)); //song name bar container sf::RectangleShape songNameBar(sf::Vector2f(170,10)); songNameBar.setFillColor(sf::Color(16, 16, 16, 160)); songNameBar.setPosition(sf::Vector2f(597, 568)); //volume container sf::RectangleShape volBar(sf::Vector2f(20,24)); volBar.setFillColor(sf::Color(16, 16, 16, 160)); volBar.setPosition(sf::Vector2f(772, 568)); //current volume sf::RectangleShape curVolBar; curVolBar.setFillColor(sf::Color(224, 224, 224, 224)); //divider for buttons sf::RectangleShape buttonDivider(sf::Vector2f(2, 30)); buttonDivider.setFillColor(sf::Color(160, 160, 160, 224)); //randomly play music on title screen bool musicPermaStop = false; //permanently stops music (do not play next music) if stop button was pressed std::deque<std::string> previousPlayedSongs; //holds previous played songs (for skip left button) sf::Music music; std::string titleMusic[5] = { "Heavy Rotation", "Aitakatta", "Koi Suru Fortune Cookie", "Halloween Night", "Yankee Machine Gun" }; std::string musicChoice = titleMusic[rand() % 5]; if (!music.openFromFile(musicChoice + ".ogg")) { return -1; // error } music.setVolume(50); music.play(); while (window.isOpen()) { //window.setMouseCursorVisible(false); // Hide cursor whenever we return to the title screen //if music ended, pick another song from our title screen jukebox (could be the same song again) if (music.getStatus() == 0 && !musicPermaStop) { previousPlayedSongs.push_back(musicChoice); //finished playing current song, push it to previous played song list musicChoice = titleMusic[rand() % 5]; if (!music.openFromFile(musicChoice + ".ogg")) { return -1; // error } music.play(); } sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::TextEntered) { std::cout << event.text.unicode << "\n"; //debug } if (event.type == sf::Event::MouseMoved) { sf::Vector2i localPos = sf::Mouse::getPosition(window); if (localPos.x >= 250 && localPos.x <= 550 && localPos.y >= 250 && localPos.y <= 350) { //start button startButton.setFillColor(sf::Color(200, 50, 5, 224)); startButton.setOutlineColor(sf::Color(200, 50, 5, 224)); } else if (localPos.x >= 250 && localPos.x <= 550 && localPos.y >= 400 && localPos.y <= 500) { //create button createButton.setFillColor(sf::Color(10, 150, 55, 224)); createButton.setOutlineColor(sf::Color(10, 150, 55, 224)); } else if (localPos.x >= 484 && localPos.x <= 509 && localPos.y >= 565 && localPos.y <= 595) { //play button playButton.setFillColor(sf::Color(35, 149, 207, 224)); //reset colors of other buttons stopButton.setFillColor(sf::Color(224, 224, 224, 224)); skipLeftButton.setFillColor(sf::Color(224, 224, 224, 224)); skipRightButton.setFillColor(sf::Color(224, 224, 224, 224)); } else if (localPos.x >= 511 && localPos.x <= 536 && localPos.y >= 565 && localPos.y <= 595) { //stop button stopButton.setFillColor(sf::Color(35, 149, 207, 224)); //reset colors of other buttons playButton.setFillColor(sf::Color(224, 224, 224, 224)); skipLeftButton.setFillColor(sf::Color(224, 224, 224, 224)); skipRightButton.setFillColor(sf::Color(224, 224, 224, 224)); } else if (localPos.x >= 538 && localPos.x <= 563 && localPos.y >= 565 && localPos.y <= 595) { //skip left button skipLeftButton.setFillColor(sf::Color(35, 149, 207, 224)); //reset colors of other buttons playButton.setFillColor(sf::Color(224, 224, 224, 224)); stopButton.setFillColor(sf::Color(224, 224, 224, 224)); skipRightButton.setFillColor(sf::Color(224, 224, 224, 224)); } else if (localPos.x >= 565 && localPos.x <= 590 && localPos.y >= 565 && localPos.y <= 595) { //skip right button skipRightButton.setFillColor(sf::Color(35, 149, 207, 224)); //reset colors of other buttons playButton.setFillColor(sf::Color(224, 224, 224, 224)); stopButton.setFillColor(sf::Color(224, 224, 224, 224)); skipLeftButton.setFillColor(sf::Color(224, 224, 224, 224)); } else { //reset colors startButton.setFillColor(sf::Color(200, 50, 5, 192)); createButton.setFillColor(sf::Color(10, 150, 55, 192)); startButton.setOutlineColor(sf::Color(200, 50, 5, 192)); createButton.setOutlineColor(sf::Color(10, 150, 55, 192)); playButton.setFillColor(sf::Color(224, 224, 224, 224)); stopButton.setFillColor(sf::Color(224, 224, 224, 224)); skipLeftButton.setFillColor(sf::Color(224, 224, 224, 224)); skipRightButton.setFillColor(sf::Color(224, 224, 224, 224)); } } if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Left) { sf::Vector2i localPos = sf::Mouse::getPosition(window); if (localPos.x >= 250 && localPos.x <= 550 && localPos.y >= 250 && localPos.y <= 350) { //start button //std::cout << "Starting campaign\n"; //debug music.stop(); //window.setMouseCursorVisible(true); song_selection(&window, "battle"); } else if (localPos.x >= 250 && localPos.x <= 550 && localPos.y >= 400 && localPos.y <= 500) { //create button //std::cout << "Starting beat maker\n"; //debug music.stop(); //window.setMouseCursorVisible(true); song_selection(&window, "make"); } else if (localPos.x >= 484 && localPos.x <= 509 && localPos.y >= 565 && localPos.y <= 595) { //play button std::cout << "status code: " << music.getStatus() << "\n"; //debug if (music.getStatus() == 0 || music.getStatus() == 1) { std::cout << "\ttrying to play music\n"; //debug music.play(); musicPermaStop = false; } else if (music.getStatus() == 2) { std::cout << "\ttrying to pause music\n"; //debug music.pause(); musicPermaStop = false; } std::cout << "\tcode now: " << music.getStatus() << "\n"; //debug } else if (localPos.x >= 511 && localPos.x <= 536 && localPos.y >= 565 && localPos.y <= 595) { //stop button std::cout << "stopping music\n"; //debug music.stop(); musicPermaStop = true; std::cout << "\tcode now: " << music.getStatus() << "\n"; //debug } else if (localPos.x >= 538 && localPos.x <= 563 && localPos.y >= 565 && localPos.y <= 595) { //skip left button if (previousPlayedSongs.size() > 0) { //play the most recent previously played song music.stop(); musicChoice = previousPlayedSongs.back(); previousPlayedSongs.pop_back(); music.openFromFile(musicChoice + ".ogg"); music.play(); } else { music.setPlayingOffset(sf::milliseconds(0)); //just reset current song if we don't have any previous played songs } } else if (localPos.x >= 565 && localPos.x <= 590 && localPos.y >= 565 && localPos.y <= 595) { //skip right button music.stop(); } else if (localPos.x >= 632 && localPos.x <= 732 && localPos.y >= 582 && localPos.y <= 592) { //set playing offset for music float xDelta = localPos.x - timeDurBar.getPosition().x; float timeMultiplier = xDelta / timeDurBar.getSize().x; music.setPlayingOffset(sf::milliseconds( int(music.getDuration().asMilliseconds() * timeMultiplier) )); } else if (localPos.x >= volBar.getPosition().x && localPos.x <= volBar.getPosition().x + volBar.getSize().x && localPos.y >= volBar.getPosition().y && localPos.y <= volBar.getPosition().y + volBar.getSize().y) { //set volume float yDelta = localPos.y - volBar.getPosition().y; float volMultiplier = (volBar.getSize().y - yDelta) / volBar.getSize().y; const int maxVolume = 100.0; music.setVolume(maxVolume * volMultiplier); } } if (event.type == sf::Event::Closed) { window.close(); } } //drawing stage window.clear(sf::Color::Black); window.draw(backSprite); titleText.setFont(gameFont); titleText.setString("AKB48"); titleText.setPosition(200, 20); window.draw(titleText); //hacky-ish way of displaying unicode non-English characters on the title screen //this is hardcoded, so can't do this for long japanese inputs sf::Uint32 titleUniCharList[5] = { sf::Uint32(38899), sf::Uint32(27005), sf::Uint32(12466), sf::Uint32(12452), sf::Uint32(12512) }; titleText.setFont(japaneseFont); for (int i = 0; i < 5; i++) { titleText.setString(titleUniCharList[i]); titleText.setPosition(300 + 50 * (i+1), 20); window.draw(titleText); } window.draw(startButton); window.draw(createButton); //hacky-ish way of displaying unicode non-English characters on the title screen //this is hardcoded, so can't do this for long japanese inputs sf::Uint32 startUniCharList[6] = { sf::Uint32(12461), sf::Uint32(12515), sf::Uint32(12531), sf::Uint32(12506), sf::Uint32(12540), sf::Uint32(12531) }; startText.setFont(japaneseFont); for (int i = 0; i < 6; i++) { startText.setString(startUniCharList[i]); startText.setPosition(250 + 50 * i, 265); window.draw(startText); } //hacky-ish way of displaying unicode non-English characters on the title screen //this is hardcoded, so can't do this for long japanese inputs sf::Uint32 createUniCharList[7] = { sf::Uint32(12499), sf::Uint32(12540), sf::Uint32(12488), sf::Uint32(12513), sf::Uint32(12540), sf::Uint32(12459), sf::Uint32(12540) }; createText.setFont(japaneseFont); for (int i = 0; i < 7; i++) { createText.setString(createUniCharList[i]); createText.setPosition(260 + 40 * i, 420); window.draw(createText); } //draw music player window.draw(musicBox); window.draw(playButton); buttonDivider.setPosition(sf::Vector2f(509, 565)); window.draw(buttonDivider); window.draw(stopButton); buttonDivider.setPosition(sf::Vector2f(536, 565)); window.draw(buttonDivider); skipLeftButton.setPosition(sf::Vector2f(544, 572)); window.draw(skipLeftButton); skipLeftButton.setPosition(sf::Vector2f(554, 572)); window.draw(skipLeftButton); buttonDivider.setPosition(sf::Vector2f(563, 565)); window.draw(buttonDivider); skipRightButton.setPosition(sf::Vector2f(574, 585)); window.draw(skipRightButton); skipRightButton.setPosition(sf::Vector2f(584, 585)); window.draw(skipRightButton); buttonDivider.setPosition(sf::Vector2f(590, 565)); window.draw(buttonDivider); window.draw(timeDurBar); //calculate position of curTimeBar based on current position in the song sf::Time musicCurTime = music.getPlayingOffset(); sf::Time musicTotalDur = music.getDuration(); curTimeBar.setPosition(sf::Vector2f(632 + (float(musicCurTime.asMilliseconds())/musicTotalDur.asMilliseconds()) * (timeDurBar.getSize().x-curTimeBar.getSize().x), 581)); window.draw(curTimeBar); window.draw(songNameBar); //display song title musicText.setPosition(sf::Vector2f(597, 565)); musicText.setString(musicChoice); window.draw(musicText); //display current time in song musicText.setPosition(sf::Vector2f(597, 580)); std::string leftSideCurTime = std::to_string(int(musicCurTime.asSeconds()) / 60); if (leftSideCurTime.length() == 1) { leftSideCurTime = "0" + leftSideCurTime; } std::string rightSideCurTime = std::to_string(int(musicCurTime.asSeconds()) % 60); if (rightSideCurTime.length() == 1) { rightSideCurTime = "0" + rightSideCurTime; } musicText.setString(leftSideCurTime + ":" + rightSideCurTime); window.draw(musicText); //display total song duration musicText.setPosition(sf::Vector2f(737, 580)); std::string leftSideTotalDur = std::to_string(int(musicTotalDur.asSeconds()) / 60); if (leftSideTotalDur.length() == 1) { leftSideTotalDur = "0" + leftSideTotalDur; } std::string rightSideTotalDur = std::to_string(int(musicTotalDur.asSeconds()) % 60); if (rightSideTotalDur.length() == 1) { rightSideTotalDur = "0" + rightSideTotalDur; } musicText.setString(leftSideTotalDur + ":" + rightSideTotalDur); window.draw(musicText); window.draw(volBar); const float maxVolume = 100.0; float curVolume = music.getVolume(); curVolBar.setSize(sf::Vector2f(volBar.getSize().x, volBar.getSize().y * curVolume/maxVolume)); curVolBar.setPosition(sf::Vector2f(volBar.getPosition().x, volBar.getPosition().y + volBar.getSize().y - curVolBar.getSize().y)); window.draw(curVolBar); /* // Set mouse sprite position mouseSprite.setPosition(static_cast<sf::Vector2f>(sf::Mouse::getPosition(window))); window.draw(mouseSprite); */ window.display(); } return 0; }
void setWindowSettings(const std::string &_p_name, uint16_t _p_width, uint16_t _p_height, bool _p_fullscreen) { m_window.create(sf::VideoMode(_p_width, _p_height), _p_name, _p_fullscreen ? sf::Style::Fullscreen : sf::Style::Close); m_window.setVerticalSyncEnabled(true); }
int main() { deltaTime = 0; sfg::SFGUI sfgui; // map sprite sf::Texture map_texture; sf::Sprite map_sprite; map_texture.loadFromFile("resources/map.png"); map_sprite.setTexture(map_texture); // window window.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32), "Runestone"); view.setSize(sf::Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT)); view.setCenter(sf::Vector2f(0, 0)); window.setView(view); // timer sf::Clock clock; // thor actions thor::Action quit(sf::Event::Closed); thor::Action left(sf::Keyboard::A, thor::Action::Hold); thor::Action right(sf::Keyboard::D, thor::Action::Hold); thor::Action up(sf::Keyboard::W, thor::Action::Hold); thor::Action down(sf::Keyboard::S, thor::Action::Hold); thor::Action mouse_down(sf::Mouse::Left, thor::Action::PressOnce); thor::Action mouse_up(sf::Mouse::Left, thor::Action::ReleaseOnce); // thor action map thor::ActionMap<std::string> action_map; action_map["quit"] = quit; action_map["left"] = left; action_map["right"] = right; action_map["up"] = up; action_map["down"] = down; action_map["mouse_down"] = mouse_down; action_map["mouse_up"] = mouse_up; thor::ActionMap<std::string>::CallbackSystem action_callbacks; action_callbacks.connect("quit", &OnQuit); action_callbacks.connect("left", &OnLeft); action_callbacks.connect("right", &OnRight); action_callbacks.connect("up", &OnUp); action_callbacks.connect("down", &OnDown); action_callbacks.connect("mouse_down", &OnMouseDown); action_callbacks.connect("mouse_up", &OnMouseUp); // thor particles sf::Texture particleTexture; particleTexture.loadFromFile("Media/particle.png"); emitter.setEmissionRate(100.0f); emitter.setParticleLifetime(sf::seconds(1.0f)); particle_system.setTexture(particleTexture); // sfgui auto sfgui_window = sfg::Window::Create(); sfgui_window->SetTitle("Runestones: "); auto rune_one = sfg::Button::Create("Rune One"); rune_one->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnRuneOne)); rune_one->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnButtonClicked)); auto rune_two = sfg::Button::Create("Rune Two"); rune_two->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnRuneTwo)); rune_two->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnButtonClicked)); auto rune_three = sfg::Button::Create("Rune Three"); rune_three->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnRuneThree)); rune_three->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnButtonClicked)); auto rune_four = sfg::Button::Create("Rune Four"); rune_four->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnRuneFour)); rune_four->GetSignal(sfg::Button::OnMouseLeftPress).Connect(std::bind(&OnButtonClicked)); auto hbox = sfg::Box::Create(sfg::Box::Orientation::HORIZONTAL, 4.0f); hbox->Pack(rune_one); hbox->Pack(rune_two); hbox->Pack(rune_three); hbox->Pack(rune_four); sfgui_window->Add(hbox); sfgui_window->SetStyle(!sfg::Window::Style::RESIZE); sfgui_window->SetPosition(sf::Vector2f((WINDOW_WIDTH / 2.0f) - (sfgui_window->GetAllocation().width / 2.0f), WINDOW_HEIGHT - sfgui_window->GetAllocation().height)); // tileset sf::Texture tileTexture; tileTexture.loadFromFile("resources/tiles.png"); rf::TileMap tileMap(4, 8); tileMap.setTexture(tileTexture); int layout[4][8] = { {-1, -1, -1, 1, 1, -1, -1, -1}, {1,1,1,1,1,1,1,1}, {-1,-1,1,1,1,1,-1,-1}, {1,1,1,1,1,1,1,1} }; for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 8; j++) { tileMap.setTile(layout[i][j], i, j); } } while (window.isOpen()) { deltaTime = clock.restart().asSeconds(); action_map.clearEvents(); sf::Event event; while (window.pollEvent(event)) { sfgui_window->HandleEvent(event); action_map.pushEvent(event); } particle_system.update(sf::seconds(deltaTime)); sfgui_window->Update(deltaTime); action_map.invokeCallbacks(action_callbacks, &window); window.setView(view); window.clear(sf::Color::Black); window.draw(map_sprite); window.draw(tileMap); window.draw(particle_system); sfgui.Display(window); window.display(); } return 0; }
int Menu::chooseAnActionNumber(sf::RenderWindow &window) { window.create(sf::VideoMode::getDesktopMode(), "Rambanana !" ); sf::View view(sf::Vector2f(window.getSize().x/2,window.getSize().y/2), sf::Vector2f(window.getSize())); window.setView(view); int choix = -1; int x = -1; int y = -1; sf::Font titleFont; sf::Font itemFont; if(!titleFont.loadFromFile("../font/Bananananananana.ttf") || !itemFont.loadFromFile("../font/BATMAN.TTF")) return -1; sf::Text textTitle; textTitle.setFont(titleFont); textTitle.setString(m_title); textTitle.setCharacterSize(TITLESIZE); textTitle.setColor(sf::Color::Yellow); textTitle.setPosition(sf::Vector2f(SPACEONTEXTSIDE, SPACEONTEXTTOP)); std::vector <sf::Text> textItems; std::vector <sf::IntRect> rectItems; int yText = SPACEONTEXTTOP + TITLESIZE + INTERLIGNE; for(unsigned int i=0; i<=m_items.size(); i++) { sf::Text text; text.setFont(itemFont); text.setCharacterSize(LABELSIZE); text.setColor(sf::Color::Green); text.setPosition(sf::Vector2f(SPACEONTEXTSIDE, yText)); std::string str; if(i<m_items.size()) str = m_items[i].label; else str = "Quitter"; str.insert(0, "["); str.append("]"); text.setString(str); textItems.push_back(text); sf::IntRect rect(SPACEONTEXTSIDE, yText, Menu::getMaxTextWidth()-SPACEONTEXTSIDE, LABELSIZE * 1.5); rectItems.push_back(rect); yText += LABELSIZE + INTERLIGNE; } while((choix < 0) && window.isOpen()) { sf::Event event; while(window.pollEvent(event)) { switch(event.type) { case sf::Event::Closed: window.close(); choix = -1; break; case sf::Event::MouseButtonPressed: x = event.mouseButton.x; y = event.mouseButton.y; break; default: break; } } window.clear(sf::Color::Black); for(unsigned int i=0; i<rectItems.size(); i++) { window.draw(textItems[i]); } window.draw(textTitle); window.display(); for(unsigned int i=0; i<rectItems.size(); i++) { if(((x > rectItems[i].left) && (x < (rectItems[i].left + rectItems[i].width)))&&(y > rectItems[i].top && (y < (rectItems[i].top + rectItems[i].height)))) { choix = i; x=-1; y=-1; } } } if(choix==(int)m_items.size()) // si on choisis de quitter le programme return -1; else return choix; }
void Window::Create() { auto style = _isFullscreen ? sf::Style::Fullscreen : sf::Style::Default; _window.create({ _windowSize.x, _windowSize.y, 32 }, _windowTitle, style); }
int main(){ logger.logNoEndl("Setting up window..."); window.create(sf::VideoMode(430,430), "GL"); logger.continueln(" done!"); logger.logNoEndl("Setting up variables..."); rect1.setFillColor(sf::Color(200,200,200)); rect1.setOutlineColor(sf::Color(0,0,0)); rect1.setOutlineThickness(-2); rect1.setPosition(10,10); rect2.setFillColor(sf::Color(200,200,200)); rect2.setOutlineColor(sf::Color(0,0,0)); rect2.setOutlineThickness(-2); rect2.setPosition(220,10); rect3.setFillColor(sf::Color(200,200,200)); rect3.setOutlineColor(sf::Color(0,0,0)); rect3.setOutlineThickness(-2); rect3.setPosition(10,220); rect4.setFillColor(sf::Color(200,200,200)); rect4.setOutlineColor(sf::Color(0,0,0)); rect4.setOutlineThickness(-2); rect4.setPosition(220,220); sf::Font font; if (!font.loadFromFile("arial.ttf")){ logger.log(Logger::LogType::Error, "Arial font not found. Cannot continue..."); return 1; } sf::Text label1("Solid White", font); label1.setColor(sf::Color::Black); label1.setPosition(rect1.getPosition().x + rect1.getSize().x / 2 - label1.getLocalBounds().width / 2, rect1.getPosition().y + rect1.getSize().y / 2 - label1.getLocalBounds().height / 2 - 10); sf::Text label2("Marquee", font); label2.setColor(sf::Color::Black); label2.setPosition(rect2.getPosition().x + rect2.getSize().x / 2 - label2.getLocalBounds().width / 2, rect2.getPosition().y + rect2.getSize().y / 2 - label2.getLocalBounds().height / 2 - 10); sf::Text label3("Color Cycle", font); label3.setColor(sf::Color::Black); label3.setPosition(rect3.getPosition().x + rect3.getSize().x / 2 - label3.getLocalBounds().width / 2, rect3.getPosition().y + rect3.getSize().y / 2 - label3.getLocalBounds().height / 2 - 10); sf::Text label4("Pew", font); label4.setColor(sf::Color::Black); label4.setPosition(rect4.getPosition().x + rect4.getSize().x / 2 - label4.getLocalBounds().width / 2, rect4.getPosition().y + rect4.getSize().y / 2 - label4.getLocalBounds().height / 2 - 10); unsigned short r = 0, g = 0, b = 0; logger.continueln(" done!"); logger.log("Running until told to stop."); bool running = true; while(running){ sf::Event event; while (window.pollEvent(event)){ if (event.type == sf::Event::Closed){ running = false; } else if (event.type == sf::Event::MouseMoved){ doMouseMove(); } else if (event.type == sf::Event::MouseButtonPressed || event.type == sf::Event::MouseButtonReleased){ doMouseButton(event.mouseButton.button); } } window.clear(sf::Color::White); window.draw(rect1); window.draw(rect2); window.draw(rect3); window.draw(rect4); window.draw(label1); window.draw(label2); window.draw(label3); window.draw(label4); window.display(); } logger.log("Closing..."); }
void Init() { GameWin.create(sf::VideoMode(800, 600, 32), "Physics Test - [SFML & Box2D]"); if (!font.loadFromFile("arial.ttf")) { exit(0); } PauseText.setFont(font); pauseText = to_string(Paused); PauseText.setCharacterSize(10); PauseText.setString("PAUSED:" + pauseText); PauseText.setPosition(sf::Vector2f(700, 10)); PauseText.setFillColor(sf::Color::Yellow); box.setPosition(sf::Vector2f(15, 5)); box.setSize(sf::Vector2f(10, 10)); box.setFillColor(sf::Color(255, 0, 0)); box2.setPosition(sf::Vector2f(50, 5)); box2.setSize(sf::Vector2f(15, 15)); box2.setFillColor(sf::Color(0, 255, 0)); ground.setPosition(sf::Vector2f(0, 540)); ground.setSize(sf::Vector2f(800, 560)); ground.setFillColor(sf::Color(0, 0,255)); wall.setPosition(sf::Vector2f(1, 1)); wall.setSize(sf::Vector2f(10, 580)); wall.setFillColor(sf::Color(0, 0, 255)); wall2.setPosition(sf::Vector2f(790, 1)); wall2.setSize(sf::Vector2f(10, 580)); wall2.setFillColor(sf::Color(0, 0, 255)); World = new b2World(gravity); World->SetGravity(gravity); groundBodyDef.type = b2_staticBody; groundBodyDef.position.Set(0, 540); groundBody = World->CreateBody(&groundBodyDef); wallBodyDef.type = b2_staticBody; wallBodyDef.position.Set(10, 580); wallBody = World->CreateBody(&wallBodyDef); wallBodyDef2.type = b2_staticBody; wallBodyDef2.position.Set(790, 1); wallBody2 = World->CreateBody(&wallBodyDef2); ballBodyDef.type = b2_dynamicBody; ballVector.Set(10, 10); ballBodyDef.angularVelocity = 0.0f; ballBodyDef.linearVelocity = ballVector; ballBodyDef2.type = b2_dynamicBody; ballVector2.Set(15, 15); ballBodyDef2.angularVelocity = 0.0f; ballBodyDef2.linearVelocity = ballVector2; ballBodyDef.position.Set(15, 0); ballBodyDef.awake = true; Body = World->CreateBody(&ballBodyDef); ballBodyDef2.position.Set(30, 0); ballBodyDef2.awake = true; Body2 = World->CreateBody(&ballBodyDef2); boxShapeDef.shape = &groundBox; boxShapeDef.density = 2.0f; boxShapeDef.restitution = 0.5f; groundBox.SetAsBox(800, 0); groundBody->CreateFixture(&groundBox, 0); wallBoxDef.shape = &wallBox; wallBoxDef.density = 2.0f; wallBoxDef.restitution = 0.5f; wallBox.SetAsBox(1, 600); wallBody->CreateFixture(&wallBox, 0); wallBoxDef2.shape = &wallBox2; wallBoxDef2.density = 2.0f; wallBoxDef2.restitution = 0.5f; wallBox2.SetAsBox(1, 600); wallBody2->CreateFixture(&wallBox2, 0); dynamicBox.SetAsBox(10.0f, 10.0f); dynamicBox2.SetAsBox(10.0f, 10.0f); fixtureDef.shape = &dynamicBox; fixtureDef.density = 2.0f; fixtureDef.friction = 1.5f; fixtureDef.restitution = 0.9f; Body->CreateFixture(&fixtureDef); fixtureDef2.shape = &dynamicBox2; fixtureDef2.density = 5.0f; fixtureDef2.friction = 5.0f; fixtureDef2.restitution = 1.0f; Body2->CreateFixture(&fixtureDef2); timeStep = 1.0f / 600.0f; velIter = 1; posIter = 1; World->Step(timeStep, velIter, posIter); b2Vec2 pos = Body->GetPosition(); float angle = Body->GetAngle(); box.setPosition(pos.x, pos.y); box.setRotation(angle); b2Vec2 pos2 = Body2->GetPosition(); float angle2 = Body2->GetAngle(); box2.setPosition(pos2.x, pos2.y); box2.setRotation(angle2); }
void DrawingFunction() { window.create(sf::VideoMode(800, 600), "Client"); //window.setFramerateLimit(60); // Set color and depth clear value glClearDepth(1.f); glClearColor(0.f, 0.f, 0.f, 0.f); // Enable Z-buffer read and write glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); // Setup a perspective projection gluPerspective(90.f, 1.f, 1.f, 500.f); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Resized) { // adjust the viewport when the window is resized glViewport(0, 0, event.size.width, event.size.height); } else if (event.type == sf::Event::GainedFocus) { isActive = true; } else if (event.type == sf::Event::LostFocus) { isActive = false; } } // Input if (isActive) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { world.GetClient()->Translate(-0.1f, 0, 0); std::cout << "MOVING: " << world.GetClient()->playerId << std::endl; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { world.GetClient()->Translate(0.1f, 0, 0); std::cout << "MOVING: " << world.GetClient()->playerId << std::endl; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { world.GetClient()->Translate(0.0f, 0.1f, 0); std::cout << "MOVING: " << world.GetClient()->playerId << std::endl; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { world.GetClient()->Translate(0.0f, -0.1f, 0); std::cout << "MOVING: " << world.GetClient()->playerId << std::endl; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) { world.GetClient()->Translate(0.0f, 0.0f, -0.1f); std::cout << "MOVING: " << world.GetClient()->playerId << std::endl; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::E)) { world.GetClient()->Translate(0.0f, 0.0f, 0.1f); std::cout << "MOVING: " << world.GetClient()->playerId << std::endl; } } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glBegin(GL_TRIANGLES); glColor3f(0.2f, 0.2f, 0.2f); // ??? world.DrawWorld(); // Draw all players glColor3f(1.0f, 0.0f, 0.0f); // RED world.DrawPlayers(); glEnd(); // triangles window.pushGLStates(); // SFML drawing sf::RectangleShape rectangle(sf::Vector2f(120, 50)); rectangle.setFillColor(sf::Color::Blue); rectangle.setPosition(0, 0); window.draw(rectangle); window.popGLStates(); // /SFML drawing window.display(); } }
int main() { sf::Clock clock; double s = 0; double viewZoom = 1.0f; srand(time(0)); for (u32 i = 0; i < PN; i++) { particule[i]._px = rand() % WINX; particule[i]._py = rand() % WINY; if (INITIAL_SPEED_ACTIVATE) { particule[i]._mx = ((rand() % INITIAL_SPEED) - INITIAL_SPEED / 2) / INITIAL_SPEED_DIV; particule[i]._my = ((rand() % INITIAL_SPEED) - INITIAL_SPEED / 2) / INITIAL_SPEED_DIV; } else { particule[i]._mx = 0; particule[i]._my = 0; } particule[i]._mass = PAR_MASS; particule[i]._color = PCOLOR; } planet.setPosition(sf::Vector2f(WINX/2, WINY/2)); planet.setOrigin(sf::Vector2f(10.0f, 10.0f)); planet.setFillColor(sf::Color::Blue); win.create(sf::VideoMode(WINX, WINY), "ORBITE"); win.setFramerateLimit(MAXFPS); clock.restart(); while (win.isOpen()) { s = clock.restart().asSeconds(); s *= SPEED; sf::View view = win.getDefaultView(); view.zoom(viewZoom); while (win.pollEvent(eve)) { if (eve.type == sf::Event::Closed) win.close(); if (eve.type == sf::Event::KeyPressed) { if (eve.key.code == sf::Keyboard::Add) viewZoom -= 0.25f; else if (eve.key.code == sf::Keyboard::Subtract) viewZoom += 0.25f; else if (eve.key.code == sf::Keyboard::Space) { trace.clear(); for (u32 i = 0; i < PN; i++) { particule[i]._px = rand() % WINX; particule[i]._py = rand() % WINY; if (INITIAL_SPEED_ACTIVATE) { particule[i]._mx = ((rand() % INITIAL_SPEED) - INITIAL_SPEED / 2) / INITIAL_SPEED_DIV; particule[i]._my = ((rand() % INITIAL_SPEED) - INITIAL_SPEED / 2) / INITIAL_SPEED_DIV; } else { particule[i]._mx = 0; particule[i]._my = 0; } particule[i]._mass = PAR_MASS; particule[i]._color = PCOLOR; } } } } planet.setPosition((sf::Vector2f)sf::Mouse::getPosition(win)); for (u32 i = 0; i < PN; i++) { particule[i].updateToPosition(planet.getPosition(), PL_MASS, s); part[i].position = sf::Vector2f(particule[i]._px, particule[i]._py); part[i].color = particule[i]._color; if (ACTIVATE_ORBIT_TRACE) { sf::Vertex cpy = part[i]; trace.append(cpy); } } win.setView(view); win.clear(sf::Color::Black); win.draw(planet); win.draw(part); win.draw(trace); win.display(); } return (0); }
int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "ERROR, no port provided\n"); exit(0); } port_no = atoi(argv[1]); host_name = argv[2]; Menu::init_window(); if (isHost) { run_host(); } else { run_non_host(); } // creating num_players no. of players for (int i = 0; i < num_players; i++) { Player pl(100 * (i + 1), 200 * (i + 1), 230, 100, team_vec[i]); pl.player_id = i; players_vec.push_back(pl); } // creating AI Players num_ai_players = num_total_players - num_players; for (int i = num_players; i < num_total_players; i++) { bool ai_team; if(count_team_a < num_total_players/2){ ai_team = 0; count_team_a++; team_vec.push_back(0); } else { ai_team = 1; count_team_b++; team_vec.push_back(1); } Player pl(100 * (i + 1), 200 * (i + 1), 230, 100, ai_team); pl.ai_mode = true; pl.player_id = i; players_vec.push_back(pl); } // new window window.create(sf::VideoMode(window_width, window_height), "QUIDDITCH: PLAY IT MY WAY", sf::Style::Default); sf::Music music; if (!music.openFromFile("cat.ogg")) { error("Failed to open music file. The file may have been removed."); } music.play(); music.setPlayingOffset(sf::seconds(10)); music.setVolume(75); // strategic time out struct timeval timeout; timeout.tv_sec = (time_t) 1; timeout.tv_usec = 1; if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); // st timeout ends // background image sprite sf::Texture image_bkg; image_bkg.loadFromFile("background.png"); sf::Sprite sprite_bkg; sprite_bkg.setTexture(image_bkg); sprite_bkg.setScale(sf::Vector2f(1.0f, 1.2f)); // creating a array which decides the order in which info is send/received char ord_send_rcv[num_players]; for (int i = 0; i < num_players; i++) { ord_send_rcv[i] = 'r'; } ord_send_rcv[player_id] = 's'; int index_calculator_ball_state = 1; sf::Clock clock; double time_elapsed = 0; bool break_off = false; bool break_off_oth = false; int katta_wala = -1; int id_error_check_init; int id_error_check_end; while (window.isOpen()) { handle_ball_counter++; players_vec[player_id].action(); // includes instructions like keyboard,etc too // Sending and receiving player information... if (!isHost) { if (player_id > 0) { timeout.tv_sec = (time_t) 0; timeout.tv_usec = 100000*player_id; if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...in Non Host: " << endl; // exit(0); } } bzero(arr_buf_s[0], 1024); memcpy(arr_buf_s[0], &player_id, sizeof(int)); bzero(arr_buf_s[1], 1024); memcpy(arr_buf_s[1], &players_vec[player_id].move_left, sizeof(bool)); bzero(arr_buf_s[2], 1024); memcpy(arr_buf_s[2], &players_vec[player_id].move_right, sizeof(bool)); bzero(arr_buf_s[3], 1024); memcpy(arr_buf_s[3], &players_vec[player_id].move_up, sizeof(bool)); bzero(arr_buf_s[4], 1024); memcpy(arr_buf_s[4], &players_vec[player_id].move_down, sizeof(bool)); bzero(arr_buf_s[5], 1024); memcpy(arr_buf_s[5], &players_vec[player_id].throw_call, sizeof(bool)); bzero(arr_buf_s[6], 1024); memcpy(arr_buf_s[6], &players_vec[player_id].mouse_pos_x, sizeof(int)); bzero(arr_buf_s[7], 1024); memcpy(arr_buf_s[7], &players_vec[player_id].mouse_pos_y, sizeof(int)); for (int j = 0; j < PARAMS; j++) { sendto(sock, arr_buf_s[j], 1024, 0, (struct sockaddr *) &server, length); } sendto(sock, arr_buf_s[0], 1024, 0, (struct sockaddr *) &server, length); if (player_id < num_players - 2) { sendto(sock, "Go on Bitch", strlen("Go on Bitch"), 0, (struct sockaddr *) &from_vec[player_id + 1], length); } while (1) { time_elapsed = clock.getElapsedTime().asMilliseconds(); if (time_elapsed > 1) { clock.restart(); break; } } } else { timeout.tv_sec = (time_t) 1; timeout.tv_usec = 1; if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); for (int rs = 0; rs < num_players - 1; rs++) { bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { if(!break_off_oth){ katta_wala = rs; } break_off = true; break; // exit(0); } memcpy(&id_error_check_init, buf_r, sizeof(int)); if(id_error_check_init!=rs){ if(!break_off_oth){ katta_wala = rs; break_off = true; break_off_oth = true; } } bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].move_left, buf_r, sizeof(bool)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].move_right, buf_r, sizeof(bool)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].move_up, buf_r, sizeof(bool)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].move_down, buf_r, sizeof(bool)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].throw_call, buf_r, sizeof(bool)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].mouse_pos_x, buf_r, sizeof(int)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&players_vec[rs].mouse_pos_y, buf_r, sizeof(int)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { break_off = true; break; // exit(0); } memcpy(&id_error_check_end, buf_r, sizeof(int)); if(id_error_check_init!=id_error_check_end){ if(!break_off_oth){ katta_wala = id_error_check_init; break_off = true; break_off_oth = true; } } } while (1) { time_elapsed = clock.getElapsedTime().asMilliseconds(); if (time_elapsed > 1) { clock.restart(); break; } } if(break_off){ break_off = false; cout << "Network Disconnected For: "<<katta_wala<<endl; for(int i=0; i<num_players-1; i++){ sendto(sock, "wait", strlen("wait"), 0, (struct sockaddr *) &from_vec[i], length); bzero(arr_buf_s[0], 1024); memcpy(arr_buf_s[0], &katta_wala, sizeof(int)); sendto(sock, arr_buf_s, 1024, 0, (struct sockaddr *) &from_vec[i], length); } while (1) { time_elapsed = clock.getElapsedTime().asMilliseconds(); if (time_elapsed > 1000) { clock.restart(); break; } } //vector<Player> players_vec_tmp; players_vec[katta_wala].ai_mode = true; from_vec.push_back(from_vec[katta_wala]); players_vec.push_back(players_vec[katta_wala]); for(int i = katta_wala+1; i <num_players+1; i++){ // struct sockaddr_in temp = from_vec[i]; { from_vec[i - 1] = from_vec[i]; players_vec[i-1]=players_vec[i]; //players_vec_tmp.push_back(players_vec[i]); } } from_vec.pop_back(); players_vec.pop_back(); if(player_id > katta_wala){ player_id--; } num_players--; continue; } } if (isHost) { for (int i = 0; i < num_total_players; i++) { players_vec[i].cal_my_nextstate(); } // check collision for all players check_collision_all_players(); // now all players are validly placed...now we move the ball since we also know now the instruction given to ball like throw, etc. for (int i = 0; i < num_total_players; i++) { players_vec[i].draw_player(); // this step needs to be done as the rectangle must be set positioned before calling move_ball } q_ball.move_ball(); // now we are done away with positioning the ball at valid spot...we can draw the ball now // send each player calculated params of all players for (int i = 0; i < num_players - 1; i++) { for (int j = 0; j < num_total_players; j++) { bzero(arr_buf_s[0], 1024); memcpy(arr_buf_s[0], &players_vec[j].x_left, sizeof(float)); bzero(arr_buf_s[1], 1024); memcpy(arr_buf_s[1], &players_vec[j].y_up, sizeof(float)); bzero(arr_buf_s[2], 1024); memcpy(arr_buf_s[2], &players_vec[j].orientation, sizeof(bool)); for (int k = 0; k < 3; k++) { sendto(sock, arr_buf_s[k], 1024, 0, (struct sockaddr *) &from_vec[i], length); } } } // send each player params_ball for (int i = 0; i < num_players - 1; i++) { bzero(arr_buf_s[0], 1024); memcpy(arr_buf_s[0], &q_ball.center_x, sizeof(float)); bzero(arr_buf_s[1], 1024); memcpy(arr_buf_s[1], &q_ball.center_y, sizeof(float)); // sending socres of team_a and team_b bzero(arr_buf_s[2], 1024); memcpy(arr_buf_s[2], &teamAscore, sizeof(int)); bzero(arr_buf_s[3], 1024); memcpy(arr_buf_s[3], &teamBscore, sizeof(int)); for (int j = 0; j < 4; j++) { sendto(sock, arr_buf_s[j], 1024, 0, (struct sockaddr *) &from_vec[i], length); } } } else { timeout.tv_sec = (time_t) 2; timeout.tv_usec = 1; if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) < 0) error("setsockopt failed\n"); // receive params of all players for (int i = 0; i < num_total_players; i++) { bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; break_off = true; break; // exit(0); } string s = buf_r; if(s == "wait") { break_off = true; cout << "Waiting as it is not a host error but someone else's network Connection error."<<endl; bzero(buf_r, 1024); recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length); memcpy(&katta_wala, buf_r, sizeof(int)); cout << "Network Disconnected for: " << katta_wala <<endl; break; } else{ memcpy(&players_vec[i].x_left, buf_r, sizeof(float)); } bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; break_off = true; break; // exit(0); } memcpy(&players_vec[i].y_up, buf_r, sizeof(float)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; break_off = true; break; // exit(0); } memcpy(&players_vec[i].orientation, buf_r, sizeof(bool)); // call draw player function to position player's rectangle players_vec[i].draw_player(); } if(break_off){ break_off = false; players_vec[katta_wala].ai_mode = true; from_vec.push_back(from_vec[katta_wala]); players_vec.push_back(players_vec[katta_wala]); for(int i = katta_wala+1; i <num_players+1; i++){ { from_vec[i - 1] = from_vec[i]; players_vec[i-1]=players_vec[i]; } } from_vec.pop_back(); players_vec.pop_back(); if(player_id > katta_wala){ player_id--; } num_players--; continue; } // recieve params_ball bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; exit(0); } memcpy(&q_ball.center_x, buf_r, sizeof(float)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; exit(0); } memcpy(&q_ball.center_y, buf_r, sizeof(float)); // receiving scores bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; exit(0); } memcpy(&teamAscore, buf_r, sizeof(int)); bzero(buf_r, 1024); if (recvfrom(sock, buf_r, 1024, 0, (struct sockaddr *) &from, &length) < 0) { cout << "Exiting...Connection Failure!!!...Error in Host..." << endl; exit(0); } memcpy(&teamBscore, buf_r, sizeof(int)); } // To display various objects on window... window.clear(); window.draw(sprite_bkg); //window.draw(q_ball.circle); q_ball.draw_ball(); window.draw(goal.line); for (int i = 0; i < num_total_players; i++) { // players_vec[i].draw_player(); window.draw(players_vec[i].rectangle); } drawscore(teamBscore, 'b'); drawscore(teamAscore, 'a'); window.display(); while (1) { time_elapsed = clock.getElapsedTime().asMilliseconds(); // cout << time_elapsed << endl; if (time_elapsed > 25) { clock.restart(); break; } } } }