void radarStateClass::update(sf::RenderWindow& window) { sf::Event event; while(window.pollEvent(event)) { if(event.type == sf::Event::Closed) { window.close(); return; } else if(event.type == sf::Event::KeyPressed) { if(event.key.code == sf::Keyboard::Tab) { stopScan(); global::activeGameStateStack->pop(); return; } } } ++currentFrame; if(currentFrame > numberOfWaitFrame) { currentFrame = 0; } if(currentFrame == 0) { for(auto circleIte = listOfCircle.begin(); circleIte != listOfCircle.end(); ) { if(circleIte->getOutlineThickness() < maxThickness) { circleIte->setOutlineThickness(circleIte->getOutlineThickness() + 1); if(circleIte->getOutlineThickness() >= maxThickness) { circleIte->setFillColor(sf::Color::Transparent); } } else { circleIte->setRadius(circleIte->getRadius() + 0.1); } if(circleIte->getRadius() > maxRadius) { listOfCircle.erase(circleIte++); continue; } circleIte->setOrigin(circleIte->getRadius(), circleIte->getRadius()); ++circleIte; } } if(scannerTimer.getElapsedTime().asSeconds() > timeBetweenScan && inScan == false) { startScan(); } if(inScan == true) { moveScannerAndScan(); } global::activeGameStateStack->oldUpdate(window); }
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 editLevelStateClass::update(sf::RenderWindow& window) { sf::Event event; while(window.pollEvent(event)) { if(event.type == sf::Event::Closed) { window.close(); } else if(event.type == sf::Event::KeyPressed) { switch(event.key.code) { case sf::Keyboard::Escape: { setNoMode(); break; } case sf::Keyboard::A: { drawAllFloor = !drawAllFloor; break; } case sf::Keyboard::F: { setAddFloorMode(); break; } case sf::Keyboard::W: { setAddWallMode("WALL"); break; } case sf::Keyboard::X: { setAddWallMode("STICKMAN_WALL"); break; } case sf::Keyboard::P: { currentMode = PLACE_PLAYER; break; } case sf::Keyboard::Return: { returnPressed(); break; } case sf::Keyboard::BackSpace: { backspacePressed(); break; } case sf::Keyboard::Delete: { deletePressed(); break; } case sf::Keyboard::LShift: { speedFactor = 5; break; } case sf::Keyboard::O: { saveLevel(); break; } case sf::Keyboard::I: { loadLevel(); break; } case sf::Keyboard::H: { moveAllLevel(-1, 0); break; } case sf::Keyboard::J: { moveAllLevel(0, 1); break; } case sf::Keyboard::K: { moveAllLevel(0, -1); break; } case sf::Keyboard::L: { moveAllLevel(1, 0); break; } case sf::Keyboard::F10: { global::activeGameStateStack->set(new mainMenuStateClass()); return; } case sf::Keyboard::Add: { if(static_cast<unsigned int>(currentFloor - 1) < listOfFloor.size()) { ++currentFloor; } break; } case sf::Keyboard::Subtract: { if(currentFloor > 0) { --currentFloor; } break; } case sf::Keyboard::B: { if(chooseNameOfLevel == false) { chooseNameOfLevel = true; tmpIndexOfLevel = currentIndexOfLevel; } else { --tmpIndexOfLevel; if(tmpIndexOfLevel < 0) { tmpIndexOfLevel = listOfLevel.size() - 1; } } nameOfLevelTextHasChanged(); break; } case sf::Keyboard::N: { if(chooseNameOfLevel == false) { chooseNameOfLevel = true; tmpIndexOfLevel = currentIndexOfLevel; } else { ++tmpIndexOfLevel; if(static_cast<unsigned int>(tmpIndexOfLevel) >= listOfLevel.size()) { tmpIndexOfLevel = 0; } } nameOfLevelTextHasChanged(); break; } case sf::Keyboard::M: { if(chooseNameOfLevel == true) { chooseNameOfLevel = false; currentIndexOfLevel = tmpIndexOfLevel; loadThisLevel(listOfLevel[currentIndexOfLevel]); } break; } default: { break; } } } else if(event.type == sf::Event::KeyReleased) { if(event.key.code == sf::Keyboard::LShift) { speedFactor = 1; } } else if(event.type == sf::Event::MouseButtonPressed) { if(event.mouseButton.button == sf::Mouse::Left) { leftClick(view.getCenter().x - ((WIDTH_SCREEN / 2) * zoomLevel) + event.mouseButton.x * zoomLevel, view.getCenter().y - ((HEIGHT_SCREEN / 2) * zoomLevel) + event.mouseButton.y * zoomLevel); } else if(event.mouseButton.button == sf::Mouse::Right) { rightClick(view.getCenter().x - ((WIDTH_SCREEN / 2) * zoomLevel) + event.mouseButton.x * zoomLevel, view.getCenter().y - ((HEIGHT_SCREEN / 2) * zoomLevel) + event.mouseButton.y * zoomLevel); } } else if(event.type == sf::Event::MouseWheelMoved) { zoomView(event.mouseWheel.delta); } if(event.type == sf::Event::TextEntered) { char character = static_cast<char>(event.text.unicode); if(character >= 48 && character <= 57 && currentMode == NO_MODE) { if(character - 48 < static_cast<char>(listOfFloor.size())) { currentFloor = character - 48; } } } } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) { moveView(-speedView * zoomLevel - 1, 0); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { moveView(speedView * zoomLevel + 1, 0); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)) { moveView(0, -speedView * zoomLevel - 1); } if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { moveView(0, speedView * zoomLevel + 1); } if(chooseNameOfLevel == true) { updateNameOfLevelText(); } }
void Solo::afficher(sf::RenderWindow& fenetre) { sf::Event e; while (fenetre.pollEvent(e)) { if (e.type == sf::Event::KeyPressed) { if (e.key.code == sf::Keyboard::P) { m_solo = m_pause; this->pause(fenetre); } if(e.key.code == sf::Keyboard::Escape) { m_solo = m_quitter; return; } } sf::Font font; sf::Text textVie, textScore, sfScore; Joueur joueur; Alien ali; Bouclier boucli; Missile miss; Collision col; sf::Texture fond; fond.loadFromFile("ressource/fond.png"); fond.setSmooth(true); sf::Sprite fond_jeu; fond_jeu.setTexture(fond); float x = 36.00, y = 70.00, yPlus = 45.00; int boool = 1, depVaisseauX = 0, cpt1, depAlienX = 0, depAlienY = -50, depHorizontal = 0, ok = 5, depMissileY = 525, depMissileX = 0, missileVaisseauOk = 2, depMissileAlienX, depMissileAlienY = 0, missileAlienOk = 0, viesJoueur = joueur.getNbVie(), score = 000; sf::Sprite tabAlien[5][11], tabAlienBis[5][11], tabBouclier[3][16], spriteVaisseau, spriteVaisseauExplose, spriteMissileVaisseau, spriteMissileAlien, vie1, vie2, vie3; sf::Vector2f vecBou, vecAli, vecVai; sf::Sound soundExplosionVaisseau, soundTire, soundExplosionAlien; //On ajoute 1 vaisseau pour chaque vie. vie1 = joueur.ajouterVaisseau(spriteVaisseau, 440, 5); vie2 = joueur.ajouterVaisseau(spriteVaisseau, 490, 5); vie3 = joueur.ajouterVaisseau(spriteVaisseau, 540, 5); // Ligne en dessous de score sf::RectangleShape borderTop; borderTop.setSize(sf::Vector2f(600, 5)); borderTop.setPosition(0, 35); borderTop.setFillColor(sf::Color(240, 248, 255)); sf::RectangleShape borderBottom; borderBottom.setSize(sf::Vector2f(600, 30)); borderBottom.setPosition(0, 570); borderBottom.setFillColor(sf::Color(240, 248, 255)); bool tabAlienSup[5][11], tabBouclierSup[3][16], explose = false; //Tableau des aliens éliminés, false si éliminé. for (int j = 0; j < 5; j++) { for (int i = 0; i < 11; i++) { tabAlienSup[j][i] = true; } } //Tableau des boucliers détruits, false si détruit. for (int j = 0; j < 3; j++) { for (int i = 0; i < 16; i++) { tabBouclierSup[j][i] = true; } } sf::SoundBuffer bufferExplosionVaisseau, bufferTire, bufferExplosionAlien; if (!bufferExplosionVaisseau.loadFromFile("ressource/vaisseauExplosion.wav")) { std::cout << "Erreur durant le chargement de vaisseauExplosion.wav" << std::endl; } else { soundExplosionVaisseau.setBuffer(bufferExplosionVaisseau); } if (!bufferExplosionAlien.loadFromFile("ressource/alienExplosion.wav")) { std::cout << "Erreur durant le chargement de alienExplosion.wav" << std::endl; } else { soundExplosionAlien.setBuffer(bufferExplosionAlien); } if (!bufferTire.loadFromFile("ressource/tire.wav")) { std::cout << "Erreur durant le chargement de tire.wav" << std::endl; } else { soundTire.setBuffer(bufferTire); } ali.alien.setSmooth(true); joueur.vaisseau.setSmooth(true); boucli.bouclier.setSmooth(true); int jeuFini = 0; while (fenetre.isOpen()) { if (!font.loadFromFile("ressource/fonts.ttf")) { std::cout << "Erreur durant le chargement de ficher fonts.ttf" << std::endl; } else { textScore.setFont(font); textScore.setString("Score : "); textScore.setCharacterSize(30); textScore.setPosition(10, 0); textScore.setStyle(sf::Text::Bold); std::string scoreString; std::ostringstream os; os << score; scoreString = os.str(); sfScore.setFont(font); sfScore.setString(scoreString); sfScore.setCharacterSize(25); sfScore.setPosition(140, 5); sfScore.setColor(sf::Color(255, 255, 255)); sfScore.setStyle(sf::Text::Bold); textVie.setFont(font); textVie.setString("Vies: "); textVie.setCharacterSize(30); textVie.setPosition(365, 0); textVie.setStyle(sf::Text::Bold); } //Si le joueur atteint 0 point de vie: if (viesJoueur == 0) { std::cout << "!!!!! GAME OVER !!!!!" << std::endl; std::ifstream fichierLire("ressource/record.txt", std::ios::in); // on ouvre le fichier en lecture. if(fichierLire) { int contenu = 0; fichierLire >> contenu; if(score < contenu) score = contenu; fichierLire.close(); } else std::cout << "fichier record.txt introuvable." << std::endl; std::ofstream fichierEcrire("ressource/record.txt", std::ios::out | std::ios::trunc); // on ouvre le fichier en lecture. if(fichierEcrire) // si réussi { fichierEcrire << score; fichierEcrire.close(); } else std::cout << "fichier record.txt introuvable." << std::endl; m_solo = m_fin; return; } //On parcours le tableau des aliens éliminés. for (int j = 0; j < 5; j++) { for (int i = 0; i < 11; i++) { //Si l'alien en [j][i] est éliminé: if (!tabAlienSup[j][i]) //On incrémente jeuFini. jeuFini += 1; } } //On sait qu'il y a 5 * 11 aliens, soit 55. //Si jeuFini = 55: if (jeuFini == 55) { //Retourner au menu %menu std::cout << "!!!!!! Victoire !!!!!!" << std::endl;; m_solo = m_fin; // return; } else //Sinon, on reinitialise jeuFini pour la prochaine vérification. jeuFini = 0; // random de 1 à 11 pour choisir aléatoirement quel alien dans la rangée horizontal va tirer int randomAlienTireX = rand() % 11 + 1; // random de 1 à 5 pour choisir aléatoirement quel alien dans la rangée vertical va tirer int randomAlienTireY = rand() % 5 + 1; // random de 1 à 2, pour que ça tire de façon aléatoire int randomAlienMissile = rand() % 2 + 1; sf::Event event; while (fenetre.pollEvent(event)) { //Si l'utilisateur clique sur la croix pour fermer la fenetre du jeu: if (event.type == sf::Event::Closed) fenetre.close(); // déplacer vaisseau à gauche if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) //Pour ne pas se déplacer hors de la fenetre. if (depVaisseauX > 50) depVaisseauX = depVaisseauX - 10; // déplacer vaisseau à droite if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) //Pour ne pas se déplacer hors de la fenetre. if (depVaisseauX < 500) depVaisseauX = depVaisseauX + 10; // tirer avec le vaisseau if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { if (missileVaisseauOk == 2) { soundTire.play(); missileVaisseauOk = 0; depMissileY = 525; depMissileX = depVaisseauX; } } } fenetre.clear(); fenetre.draw(fond_jeu); //spriteVaisseauExplose = joueur.vaisseauExplose(spriteVaisseauExplose, depVaisseauX, 535); spriteVaisseau = joueur.ajouterVaisseau(spriteVaisseau, depVaisseauX, 535); //app.draw(spriteVaisseau); //Si randomAlienMissile tombe sur 1, on peut tirer. if (randomAlienMissile == 1) { if (missileAlienOk == 2) { missileAlienOk = 0; depMissileAlienX = (x * (randomAlienTireX)) + depAlienX - 8; depMissileAlienY = (y + yPlus * (randomAlienTireY)) + depAlienY + 45; } } if (col.collisionVaisseau(spriteVaisseau, spriteMissileAlien)) { spriteMissileAlien = miss.supprimerMissile(spriteMissileAlien); viesJoueur -= 1; explose = true; //std::cout << " collision vaisseau missile alien" << std::endl; // app.draw(spriteVaisseau); //sleep(1); missileAlienOk = 2; } if (missileVaisseauOk == 0) spriteMissileVaisseau = miss.ajouterMissileVaisseau(spriteMissileVaisseau, depMissileX + 21, depMissileY); if (missileAlienOk == 0) spriteMissileAlien = miss.ajouterMissileAlien(spriteMissileAlien, depMissileAlienX + 21, depMissileAlienY); // boucliers int dix = 450, vingt = 90, quatre = 0; for (int j = 0; j < 3; j++) { for (int i = 0; i < 16; i++) { if (tabBouclierSup[j][i]) { tabBouclier[j][i] = boucli.ajouterBouclier(tabBouclier[j][i], vingt + 160 * j, dix); fenetre.draw(tabBouclier[j][i]); } vingt = vingt + 20; quatre = quatre + 1; if (vingt == 170) vingt = 90; if (quatre == 4) { dix = dix + 10; quatre = 0; } if (col.collisionBouclier(tabBouclier[j][i], spriteMissileVaisseau)) { vecBou = boucli.getPosition(tabBouclier[j][i]); if (vecBou.y + 10 == depMissileY) { spriteMissileVaisseau = miss.supprimerMissile(spriteMissileVaisseau); tabBouclier[j][i] = miss.supprimerMissile(tabBouclier[j][i]); tabBouclierSup[j][i] = false; missileVaisseauOk = 2; } } if (col.collisionBouclier(tabBouclier[j][i], spriteMissileAlien)) { spriteMissileAlien = miss.supprimerMissile(spriteMissileAlien); tabBouclier[j][i] = miss.supprimerMissile(tabBouclier[j][i]); tabBouclierSup[j][i] = false; missileAlienOk = 2; } } dix = 450; vingt = 90; } for (int j = 0; j < 5; j++) { for (int i = 0; i < 11; i++) { // Colision missile alien - alien if (col.collisionAlien(tabAlien[j][i], spriteMissileAlien)) { vecAli = ali.getPosition(tabAlien[j][i]); if (vecAli.y + 20 == depMissileAlienY) { spriteMissileAlien = miss.supprimerMissile(spriteMissileAlien); missileAlienOk = 2; } } // Colision missile vaisseau - alien if (col.collisionAlien(tabAlien[j][i], spriteMissileVaisseau)) { vecVai = ali.getPosition(tabAlien[j][i]); if (vecVai.y + 20 == depMissileY) { soundExplosionAlien.play(); tabAlienSup[j][i] = false; spriteMissileVaisseau = miss.supprimerMissile(spriteMissileVaisseau); tabAlien[j][i] = miss.supprimerMissile(tabAlien[j][i]); tabAlienBis[j][i] = miss.supprimerMissile(tabAlienBis[j][i]); missileVaisseauOk = 2; if (j==0 || j==1) score += 10; if (j==2 || j==3) score += 20; if (j==4 ) score += 50; } } } } // aliens if (boool > 50) { for (cpt1 = 0; cpt1 < 11; cpt1++) { //On vérifie s'ils sont éliminés. if (tabAlienSup[0][cpt1]) // alien ligne 1 (en partant du bas) tabAlien[0][cpt1] = ali.ajouterAlien1_1(tabAlien[0][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 5) + depAlienY); fenetre.draw(tabAlien[0][cpt1]); if (tabAlienSup[1][cpt1]) // alien ligne 2 (en partant du bas) tabAlien[1][cpt1] = ali.ajouterAlien1_1(tabAlien[1][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 4) + depAlienY); fenetre.draw(tabAlien[1][cpt1]); if (tabAlienSup[2][cpt1]) // alien ligne 3 (en partant du bas) tabAlien[2][cpt1] = ali.ajouterAlien2_1(tabAlien[2][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 3) + depAlienY); fenetre.draw(tabAlien[2][cpt1]); if (tabAlienSup[3][cpt1]) // alien ligne 4 (en partant du bas) tabAlien[3][cpt1] = ali.ajouterAlien2_1(tabAlien[3][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 2) + depAlienY); fenetre.draw(tabAlien[3][cpt1]); if (tabAlienSup[4][cpt1]) // alien ligne 5 (en partant du bas) tabAlien[4][cpt1] = ali.ajouterAlien3_1(tabAlien[4][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 1) + depAlienY); fenetre.draw(tabAlien[4][cpt1]); } } else if (boool < 50) { for (cpt1 = 0; cpt1 < 11; cpt1++) { if (tabAlienSup[0][cpt1]) // alien 1 bis (en partant du bas) tabAlienBis[0][cpt1] = ali.ajouterAlien1_2(tabAlienBis[0][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 5) + depAlienY); fenetre.draw(tabAlienBis[0][cpt1]); if (tabAlienSup[1][cpt1]) // alien 2 bis (en partant du bas) tabAlienBis[1][cpt1] = ali.ajouterAlien1_2(tabAlienBis[1][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 4) + depAlienY); fenetre.draw(tabAlienBis[1][cpt1]); if (tabAlienSup[2][cpt1]) // alien 3 bis (en partant du bas) tabAlienBis[2][cpt1] = ali.ajouterAlien2_2(tabAlienBis[2][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 3) + depAlienY); fenetre.draw(tabAlienBis[2][cpt1]); if (tabAlienSup[3][cpt1]) // alien 4 bis (en partant du bas) tabAlienBis[3][cpt1] = ali.ajouterAlien2_2(tabAlienBis[3][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 2) + depAlienY); fenetre.draw(tabAlienBis[3][cpt1]); if (tabAlienSup[4][cpt1]) // alien 5 bis (en partant du bas) tabAlienBis[4][cpt1] = ali.ajouterAlien3_2(tabAlienBis[4][cpt1], (x * (cpt1 + 1)) + depAlienX, (y + yPlus * 1) + depAlienY); fenetre.draw(tabAlienBis[4][cpt1]); } } // fin test. if (boool == 100) boool = 0; else boool += 1; if (depMissileY == 40) { missileVaisseauOk = 2; depMissileY = 40; } else { depMissileY -= 5; fenetre.draw(spriteMissileVaisseau); } if (depMissileAlienY == 575) { //nazerkkm missileAlienOk = 2; depMissileAlienY = 600; } else { depMissileAlienY += 5; fenetre.draw(spriteMissileAlien); } if (depHorizontal == 50) { if (depAlienX > 130) { if (ok != 5) { depAlienY += 10; // si la vague descend trop if (depAlienY == 140) { // le vaisseau perd 1 point de vie. viesJoueur -= 1; explose = true; // app.draw(spriteVaisseau); //sleep(1); depAlienY -= 40; } } ok = 1; } if (depAlienX == 0) { if (ok != 5) { depAlienY += 10; // si la vague descend trop if (depAlienY == 140) { // le vaisseau perd 1 point de vie. viesJoueur -= 1; explose = true; // app.draw(spriteVaisseau); //sleep(1); depAlienY -= 40; } } ok = 0; } if (ok == 0) depAlienX += 132 / 18; if (ok == 1) depAlienX -= 132 / 18; depHorizontal = 0; } else depHorizontal += 1; if (explose) { spriteVaisseauExplose = joueur.vaisseauExplose(spriteVaisseauExplose, depVaisseauX, 535); fenetre.draw(spriteVaisseauExplose); soundExplosionVaisseau.play(); fenetre.display(); } else { fenetre.draw(spriteVaisseau); } if (explose) sleep(1); // vies du vaisseau switch (viesJoueur) { case 3://Si 3 vies: fenetre.draw(vie1); fenetre.draw(vie2); fenetre.draw(vie3); break; case 2://Si 2 vies: fenetre.draw(vie1); fenetre.draw(vie2); break; case 1://Si 1 vie: fenetre.draw(vie1); break; default: break; } fenetre.draw(borderTop); fenetre.draw(textVie); fenetre.draw(textScore); fenetre.draw(borderBottom); fenetre.draw(sfScore); explose = false; fenetre.display(); }
int main(){ wrldmgr.res.loadTexture("art/ChestBlue.png"); wrldmgr.res.loadTexture("art/Coin.png"); wrldmgr.res.loadTexture("art/Gem.png"); ///////////////////////////////////////////////////////////////////// bool doSleep = true; world.SetAllowSleeping(doSleep); controlled obj1;{ b2BodyDef bodyDef; //bodyDef.fixedRotation = true; bodyDef.type = b2_dynamicBody; bodyDef.position.Set(300.0f/SCALE, 15.f/SCALE); b2PolygonShape dynamicBox; dynamicBox.SetAsBox((40.f/2)/SCALE, (40.f/2)/SCALE); b2FixtureDef fixtureDef; fixtureDef.shape = &dynamicBox; fixtureDef.density = 1.0f; fixtureDef.friction = 0.3f; fixtureDef.restitution = 0.4f; obj1.animations.push_back(animation(&wrldmgr.res.textures[0], sf::Vector2i(100,100), 2, 300));//wrldmgr.res.textures[0].getSize().x, wrldmgr.res.textures[0].getSize().y))); obj1.animations.push_back(animation(&wrldmgr.res.textures[2], sf::Vector2i(50,50))); obj1.animations[1].pos = sf::Vector2f(0,400); obj1.bd = world.CreateBody(&bodyDef); obj1.fx = obj1.bd->CreateFixture(&fixtureDef); obj1.refresh(); } wrldmgr.playerObj = obj1; object obj2;{ b2BodyDef bbd; bbd.position.Set(400.f/SCALE,30.f/SCALE); bbd.type = b2_dynamicBody; b2CircleShape ballshape; ballshape.m_radius = 50.f/SCALE; b2FixtureDef ballFixtureDef; ballFixtureDef.shape = &ballshape; ballFixtureDef.density = 1.0f; ballFixtureDef.friction = 0.3f; ballFixtureDef.restitution = 0.4f; obj2.animations.push_back(animation(&wrldmgr.res.textures[1], sf::Vector2i(100,100)));//wrldmgr.res.textures[1].getSize().x, wrldmgr.res.textures[1].getSize().y))); obj2.bd = world.CreateBody(&bbd); obj2.fx = obj2.bd->CreateFixture(&ballFixtureDef); obj2.refresh(); } wrldmgr.addObject(obj2); b2Body* ground;{ b2BodyDef bd; bd.position.Set(0.0f/SCALE, 0.0f/SCALE); ground = world.CreateBody(&bd); b2EdgeShape shape; b2FixtureDef sd; sd.shape = &shape; sd.density = 0.0f; sd.restitution = 0.4f; // Left vertical shape.Set(b2Vec2(10.0f/SCALE, 10.0f/SCALE), b2Vec2(10.0f/SCALE, (winh - 10.0f)/SCALE)); ground->CreateFixture(&sd); // Right vertical shape.Set(b2Vec2((winw - 10.0f)/SCALE, 10.0f/SCALE), b2Vec2((winw - 10.0f)/SCALE, (winh - 10.0f)/SCALE)); ground->CreateFixture(&sd); // Top horizontal shape.Set(b2Vec2(10.0f/SCALE, (winh - 10.0f)/SCALE), b2Vec2((winw - 10.0f)/SCALE, (winh - 10.0f)/SCALE)); ground->CreateFixture(&sd); // Bottom horizontal shape.Set(b2Vec2(10.0f/SCALE, 10.0f/SCALE), b2Vec2((winw - 10.0f)/SCALE, 10.0f/SCALE)); ground->CreateFixture(&sd); } ///////////////////////////////////////////// wrldmgr.initialize(); font.loadFromFile("art/Grundschrift-Normal.otf"); text.push_back(sf::Text("Hello!",font,20)); text.push_back(sf::Text("",font,15)); text.push_back(sf::Text("",font,15)); text.push_back(sf::Text("",font,15)); while (win.isOpen()){ while (win.pollEvent(event)){ if (event.type == sf::Event::Closed) win.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)){ win.close(); } float dt = gameclock.getElapsedTime().asSeconds(); gameclock.restart(); pupd(dt); text[1].setString("UPS: ");// + std::to_string(int(1/dt))); text[2].setString("Player Speed: ");// + std::to_string(wrldmgr.playerObj.bd->GetLinearVelocity().Length())); text[3].setString("Player Angular Speed: ");// + std::to_string(wrldmgr.playerObj.bd->GetAngularVelocity())); renderEdge(ground); oupd(); } return 0; }
void getEvent(sf::Event& event, sf::RenderWindow& window, Input& in) { switch (event.type) { case sf::Event::Closed: window.close(); break; case sf::Event::KeyPressed: switch (event.key.code) { case sf::Keyboard::W: in.W = true; break; case sf::Keyboard::A: in.A = true; break; case sf::Keyboard::S: in.S = true; break; case sf::Keyboard::D: in.D = true; break; case sf::Keyboard::Up: in.W = true; break; case sf::Keyboard::Left: in.A = true; break; case sf::Keyboard::Down: in.S = true; break; case sf::Keyboard::Right: in.D = true; break; case sf::Keyboard::I: in.record = true; break; case sf::Keyboard::O: in.edit = true; break; case sf::Keyboard::P: in.predict = true; break; case sf::Keyboard::Space: in.reset = true; break; case sf::Keyboard::Num0: in.action = 0; break; case sf::Keyboard::Num1: in.action = 1; break; case sf::Keyboard::Num2: in.action = 2; break; case sf::Keyboard::Num3: in.action = 3; break; case sf::Keyboard::Num4: in.action = 4; break; case sf::Keyboard::Num5: in.action = 5; break; case sf::Keyboard::Num6: in.action = 6; break; case sf::Keyboard::Num7: in.action = 7; break; case sf::Keyboard::Num8: in.action = 8; break; case sf::Keyboard::Num9: in.action = 9; break; case sf::Keyboard::Numpad0: in.action = 10; break; case sf::Keyboard::Numpad1: in.action = 11; break; case sf::Keyboard::Numpad2: in.action = 12; break; case sf::Keyboard::Numpad3: in.action = 13; break; case sf::Keyboard::Numpad4: in.action = 14; break; case sf::Keyboard::Numpad5: in.action = 15; break; case sf::Keyboard::Numpad6: in.action = 16; break; case sf::Keyboard::Numpad7: in.action = 17; break; case sf::Keyboard::Numpad8: in.action = 18; break; case sf::Keyboard::Numpad9: in.action = 19; break; case sf::Keyboard::X: in.zoom += 0.5f; break; case sf::Keyboard::Z: in.zoom -= 0.5f; break; case sf::Keyboard::F1: in.action = -2; default: break; } break; case sf::Event::KeyReleased: switch (event.key.code) { case sf::Keyboard::W: in.W = false; break; case sf::Keyboard::A: in.A = false; break; case sf::Keyboard::S: in.S = false; break; case sf::Keyboard::D: in.D = false; break; case sf::Keyboard::Up: in.W = false; break; case sf::Keyboard::Left: in.A = false; break; case sf::Keyboard::Down: in.S = false; break; case sf::Keyboard::Right: in.D = false; break; default: break; } default: break; } }
void rotateCube(sf::RenderWindow &window) { bool mouse = true; auto size = window.getSize(); int width = size.x; int height = size.y; /* sf::Image texture; texture.loadFromFile("models/cube.png"); auto texRaw = texture.getPixelsPtr(); Array2D<ColorRGBA> tex(24, 32); std::copy(texRaw, texRaw + (4 * 32 * 24), (unsigned char *)tex.data()); */ std::vector<Vec> verts; std::vector<int> tris; std::vector<Vec> normals; std::vector<int> triNormals; std::ifstream teapot("models/teapot.obj"); readObj(teapot, verts, &normals, nullptr, tris, &triNormals, nullptr); // rectify teapot model Mat teapotRectify = Mat::fromRows33(Vec(1, 0, 0), Vec(0, 0, -1), Vec(0, 1, 0)); Bounds bds = Bounds::fromIterators(verts.begin(), verts.end()); float roomSz = vabs(bds.size()).maxXYZEl(); float floorZ = bds.mins.y; // rectified Vec floorVerts[] = { {roomSz, roomSz, floorZ, 1}, {-roomSz, roomSz, floorZ, 1}, {-roomSz, -roomSz, floorZ, 1}, {roomSz, -roomSz, floorZ, 1}, }; int floorTris[] = { 0, 1, 3, 3, 1, 2, }; Camera cam; cam.position = Vec(30, 14, 5); // replace angle calc with mouse once it's ready cam.direction = -cam.position.normalized(); cam.up = Vec(0, 0, 1).normalTo(cam.direction).normalized(); sf::Texture screen; screen.create(width, height); sf::Sprite sprite; sprite.setTexture(screen); Array2D<float> zbuffer(height, width); Array2D<ColorRGBA> fragments(height, width); FpsCounter counter; Vec light = Vec(0, 30, 50); auto vertShade = [](VertexIn const &in, VertexGlobal const &global) -> VertexWithUnprojected { VertexWithUnprojected out; out.coord = in.coord; out.normal = global.modelView.withoutTranslation() * in.normal; out.vertex = global.modelViewProjection * in.vertex; out.vertexUnprojected = global.modelView * in.vertex; return out; }; ColorRGBA red { 255, 0, 0 }; ColorRGBA green { 0, 255, 0 }; ColorRGBA mixed; float mix = 0; auto fragShadeShiny = [&](VertexWithUnprojected const &v, VertexGlobal const &global) -> FragmentOut { FragmentOut f; Vec eyeLight = global.view * light; Vec toLight = (eyeLight - v.vertexUnprojected).normalized(); //Vec normal = v.normal.normalized(); Vec normal = v.normal; float diffuse = clamp(dot(normal, toLight), 0.0f, 1.0f); Vec reflection = toLight.projectedTo(normal) - toLight.normalTo(normal); float specular = clamp(-reflection.z, 0.0f, 1.0f); specular *= specular; specular *= specular; float ambient = 0.3; f.color = diffuse * mixed + specular * ColorRGBA(100, 200, 255) + ambient * ColorRGBA(100, 150, 200); //f.color = mixed; return f; }; auto fragShadeChecker = [&](VertexWithUnprojected const &v, VertexGlobal const &global) -> FragmentOut { static int i = 0; FragmentOut f; float SCALE = 0.2; int xx = 10000 + SCALE * v.coord.x; int yy = 10000 + SCALE * v.coord.y; if ((xx & 1) != (yy & 1)) { f.color = ColorRGBA(0, 0, 0); } else { f.color = ColorRGBA(0, 0x99 , 0xFF); } return f; }; // Declare and load a font sf::Font font; if (!font.loadFromFile("arial.ttf")) { std::cout << "failed to load font\n"; return; } // Create a text sf::Text text("hello", font); text.setCharacterSize(16); text.setColor(sf::Color::Red); text.setPosition(10, 10); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::P) { screen.copyToImage().saveToFile("../../molasses.png"); } if (event.key.code == sf::Keyboard::Q) { window.close(); } if (event.key.code == sf::Keyboard::M) { mouse = !mouse; } } if (event.type == sf::Event::MouseButtonPressed) { mix = 1.0; } } std::fill(zbuffer.begin(), zbuffer.end(), std::numeric_limits<float>::max()); std::fill(fragments.begin(), fragments.end(), ColorRGBA()); Mat camCsys = Mat::transpose(view(cam).withoutTranslation()); double speed = counter.sinceLast() * 80; Vec v = camCsys * keyVelocity(); cam.position = cam.position + speed * v; window.setMouseCursorVisible(!mouse); if (mouse) { auto mouse = sf::Mouse::getPosition(window); auto size = window.getSize(); auto middle = sf::Vector2i(size.x / 2, size.y / 2); auto dmouse = sf::Vector2i(mouse.x - middle.x, mouse.y - middle.y); dmouse.y *= -1; sf::Mouse::setPosition(middle, window); Vec mouseVelocity = Vec(dmouse.x, dmouse.y, 0) / 300.0; Vec worldTurn = camCsys * mouseVelocity; cam.direction = (cam.direction + worldTurn).normalized(); cam.up = Vec(0, 0, 1).normalTo(cam.direction).normalized(); // not most efficient } //cam.position = rot * cam.position; //cam.direction = -cam.position.normalized(); //cam.up = Vec(0, 0, 1).normalTo(cam.direction).normalized(); double fov = radians(60); VertexGlobal global; global.view = view(cam); global.modelView = view(cam) * teapotRectify; global.modelViewProjection = projection(fov, float(width)/height, 10, 100) * global.modelView; global.normal = Mat::transpose(Mat::invert(global.modelView)); Mat toScreen = normalizedToScreen(width, height); for (int i = 0; i < tris.size() / 3; ++i) { int *tri = tris.data() + (3 * i); int *triNorm = triNormals.data() + (3 * i); VertexIn vertices[3]; VertexWithUnprojected shaded[3]; for (int j = 0; j < 3; ++j) { vertices[j].vertex = verts[tri[j]]; vertices[j].normal = normals[triNorm[j]]; //vertices[j].coord = texCoords[tri[j]]; shaded[j] = vertShade(vertices[j], global); } rasterize(shaded[0], shaded[1], shaded[2], fragShadeShiny, zbuffer, fragments, toScreen, global); } global.view = view(cam); global.modelView = view(cam); global.modelViewProjection = projection(fov, float(width)/height, 1, 100) * global.modelView; global.normal = Mat::transpose(Mat::invert(global.modelView)); for (int i = 0; i < 2; ++i) { int *tri = floorTris + 3 * i; VertexIn vertices[3]; VertexWithUnprojected shaded[3]; for (int j = 0; j < 3; ++j) { vertices[j].vertex = floorVerts[tri[j]]; vertices[j].normal = {0, 0, 1}; vertices[j].coord = {vertices[j].vertex}; vertices[j].coord.z = 0; vertices[j].coord.w = 0; //std::cout << vertices[j].coord; shaded[j] = vertShade(vertices[j], global); } rasterize(shaded[0], shaded[1], shaded[2], fragShadeChecker, zbuffer, fragments, toScreen, global); } screen.update((sf::Uint8 const *)fragments.data(), width, height, 0, 0); counter.frame(); std::ostringstream oss; oss << (int)counter.fps() << " FPS" << std::endl; text.setString(oss.str()); window.clear(); window.draw(sprite); window.draw(text); window.display(); mix -= 2.0 * counter.sinceLast() * mix; mixed = mix * green + (1.0 - mix) * red; } }
int main() { srand(time(NULL)); Background::LoadBackground(); Sound::LoadSounds(); Sprites::LoadSprites(); Font::LoadFont(); window.setFramerateLimit(30); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shot_counter==0){ break; } window.draw(Background::BeforeGameStartSprite); window.display(); } Hero hero; Enemys enemys; while(window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } shot_counter++; shot_counter%=10; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shot_counter==0) { hero.fire(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { hero.MoveLeft(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { hero.MoveRight(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { hero.MoveUp(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { hero.MoveDown(); } Sound::PlayBackgroundMusic(); Background::show(window); hero.turn(window); enemys.turn(window); window.display(); if (hero.GetHealth()<=0) break; } return 0; }
void SampleApp::Run() { sf::Event event; //m_window.SetFramerateLimit( 60 ); //m_window.EnableVerticalSync( true ); // Tune Renderer sfg::Renderer::Get().TuneDepthTest( sfg::Renderer::ALTERNATE_DEPTH ); sfg::Renderer::Get().TuneAlphaThreshold( .2f ); sfg::Renderer::Get().TunePrecomputeBlending( true ); sfg::Renderer::Get().TuneCull( true ); // Create widgets. m_wndmain = sfg::Window::Create( sfg::Window::TITLEBAR | sfg::Window::BACKGROUND | sfg::Window::RESIZE ); m_wndmain->SetTitle( L"Example application" ); sfg::Button::Ptr btnaddbuttonh( sfg::Button::Create( L"Add button horizontally" ) ); sfg::Button::Ptr btnaddbuttonv( sfg::Button::Create( L"Add button vertically" ) ); m_titlebar_toggle = sfg::ToggleButton::Create( "Toggle titlebar" ); m_titlebar_toggle->SetActive( true ); { sf::Image add_image; if( add_image.loadFromFile( "data/add.png" ) ) { sfg::Image::Ptr image( sfg::Image::Create( add_image ) ); btnaddbuttonh->SetImage( image ); image = sfg::Image::Create( add_image ); btnaddbuttonv->SetImage( image ); } } sfg::Button::Ptr btnhidewindow( sfg::Button::Create( L"Close window" ) ); btnhidewindow->SetId( "close" ); { sf::Image close_image; if( close_image.loadFromFile( "data/delete.png" ) ) { sfg::Image::Ptr image( sfg::Image::Create( close_image ) ); btnhidewindow->SetImage( image ); } } sfg::Button::Ptr btntogglespace( sfg::Button::Create( L"Box Spacing") ); sfg::Button::Ptr btnloadstyle( sfg::Button::Create( L"Load theme") ); m_entry = sfg::Entry::Create( L"Type" ); m_entry->SetRequisition( sf::Vector2f( 100.f, .0f ) ); m_entry->AppendText( L" something!" ); m_limit_check = sfg::CheckButton::Create( L"Limit to 4 chars" ); m_limit_check->SetId( "limit_check" ); sfg::Entry::Ptr password( sfg::Entry::Create() ); password->HideText( '*' ); // Layout. sfg::Box::Ptr boxtoolbar( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); boxtoolbar->SetSpacing( 5.f ); boxtoolbar->Pack( btnaddbuttonh, false ); boxtoolbar->Pack( btnaddbuttonv, false ); boxtoolbar->Pack( m_titlebar_toggle, false ); boxtoolbar->Pack( btnhidewindow, false ); boxtoolbar->Pack( m_entry, true ); boxtoolbar->Pack( m_limit_check, false ); sfg::Frame::Ptr frame1( sfg::Frame::Create( L"Toolbar 1" ) ); frame1->Add( boxtoolbar ); sfg::Box::Ptr boxtoolbar2( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); boxtoolbar2->SetSpacing( 5.f ); boxtoolbar2->Pack( btntogglespace, false ); boxtoolbar2->Pack( btnloadstyle, false ); m_boxbuttonsh = sfg::Box::Create( sfg::Box::HORIZONTAL ); m_boxbuttonsh->SetSpacing( 5.f ); m_boxbuttonsv = sfg::Box::Create( sfg::Box::VERTICAL ); m_boxbuttonsv->SetSpacing( 5.f ); sfg::Entry::Ptr username_entry( sfg::Entry::Create() ); username_entry->SetMaximumLength( 8 ); m_progress = sfg::ProgressBar::Create( sfg::ProgressBar::HORIZONTAL ); m_progress->SetRequisition( sf::Vector2f( 0.f, 20.f ) ); m_progress_vert = sfg::ProgressBar::Create( sfg::ProgressBar::VERTICAL ); m_progress_vert->SetRequisition( sf::Vector2f( 20.f, 0.f ) ); sfg::Separator::Ptr separatorv( sfg::Separator::Create( sfg::Separator::VERTICAL ) ); m_table = sfg::Table::Create(); m_table->Attach( sfg::Label::Create( L"Please login using your username and password (span example)." ), sf::Rect<sf::Uint32>( 0, 0, 2, 1 ), sfg::Table::FILL, sfg::Table::FILL | sfg::Table::EXPAND ); m_table->Attach( sfg::Label::Create( L"Username:"******"Password:"******"Login" ), sf::Rect<sf::Uint32>( 2, 1, 1, 2 ), sfg::Table::FILL, sfg::Table::FILL ); m_table->Attach( separatorv, sf::Rect<sf::Uint32>( 3, 0, 1, 3 ), sfg::Table::FILL, sfg::Table::FILL ); m_table->Attach( m_progress_vert, sf::Rect<sf::Uint32>( 4, 0, 1, 3 ), sfg::Table::FILL, sfg::Table::FILL ); m_table->SetRowSpacings( 5.f ); m_table->SetColumnSpacings( 5.f ); m_scrolled_window_box = sfg::Box::Create( sfg::Box::VERTICAL ); for( int i = 0; i < 5; i++ ) { sfg::Box::Ptr box = sfg::Box::Create( sfg::Box::HORIZONTAL ); for( int j = 0; j < 20; j++ ) { box->Pack( sfg::Button::Create( L"One button among many" ), true ); } m_scrolled_window_box->Pack( box, false ); } m_scrolled_window = sfg::ScrolledWindow::Create(); m_scrolled_window->SetRequisition( sf::Vector2f( .0f, 150.f ) ); m_scrolled_window->SetScrollbarPolicy( sfg::ScrolledWindow::HORIZONTAL_AUTOMATIC | sfg::ScrolledWindow::VERTICAL_AUTOMATIC ); m_scrolled_window->SetPlacement( sfg::ScrolledWindow::TOP_LEFT ); m_scrolled_window->AddWithViewport( m_scrolled_window_box ); sfg::Scrollbar::Ptr scrollbar( sfg::Scrollbar::Create() ); scrollbar->SetRange( .0f, 100.f ); m_scale = sfg::Scale::Create(); m_scale->SetAdjustment( scrollbar->GetAdjustment() ); m_scale->SetRequisition( sf::Vector2f( 100.f, .0f ) ); boxtoolbar2->Pack( m_scale, false ); m_combo_box = sfg::ComboBox::Create(); m_combo_box->AppendItem( "Item 0" ); m_combo_box->AppendItem( "Item 1" ); m_combo_box->AppendItem( "Item 2" ); m_combo_box->AppendItem( "Item 3" ); boxtoolbar2->Pack( m_combo_box, true ); sfg::Frame::Ptr frame2( sfg::Frame::Create( L"Toolbar 2" ) ); frame2->Add( boxtoolbar2 ); frame2->SetAlignment( sf::Vector2f( .8f, .0f ) ); sfg::Separator::Ptr separatorh( sfg::Separator::Create( sfg::Separator::HORIZONTAL ) ); sfg::Box::Ptr box_image( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); box_image->SetSpacing( 5.f ); sfg::Fixed::Ptr fixed_container( sfg::Fixed::Create() ); sfg::Button::Ptr fixed_button( sfg::Button::Create( L"I'm at (34,61)" ) ); fixed_container->Put( fixed_button, sf::Vector2f( 34.f, 61.f ) ); box_image->Pack( fixed_container, false ); sf::Image sfgui_logo; sfg::Image::Ptr image = sfg::Image::Create(); if( sfgui_logo.loadFromFile("sfgui.png") ) { image->SetImage( sfgui_logo ); box_image->Pack( image, false ); } sfg::Box::Ptr spinner_box( sfg::Box::Create( sfg::Box::VERTICAL ) ); m_spinner = sfg::Spinner::Create(); m_spinner->SetRequisition( sf::Vector2f( 40.f, 40.f ) ); m_spinner->Start(); sfg::ToggleButton::Ptr spinner_toggle( sfg::ToggleButton::Create( L"Spin") ); spinner_toggle->SetActive( true ); spinner_box->SetSpacing( 5.f ); spinner_box->Pack( m_spinner, false ); spinner_box->Pack( spinner_toggle, false ); box_image->Pack( spinner_box, false ); sfg::ComboBox::Ptr aligned_combo_box( sfg::ComboBox::Create() ); aligned_combo_box->AppendItem( L"I'm way over here" ); aligned_combo_box->AppendItem( L"Me too" ); aligned_combo_box->AppendItem( L"Me three" ); aligned_combo_box->SelectItem( 0 ); sfg::Alignment::Ptr alignment( sfg::Alignment::Create() ); alignment->Add( aligned_combo_box ); box_image->Pack( alignment, true ); alignment->SetAlignment( sf::Vector2f( 1.f, .5f ) ); alignment->SetScale( sf::Vector2f( 0.f, .01f ) ); sfg::Box::Ptr boxmain( sfg::Box::Create( sfg::Box::VERTICAL ) ); boxmain->SetSpacing( 5.f ); boxmain->Pack( scrollbar, false ); boxmain->Pack( m_progress, false ); boxmain->Pack( frame1, false ); boxmain->Pack( frame2, false ); boxmain->Pack( m_boxbuttonsh, false ); boxmain->Pack( m_boxbuttonsv, false ); boxmain->Pack( box_image, true ); boxmain->Pack( separatorh, false ); boxmain->Pack( m_table, true ); boxmain->Pack( m_scrolled_window ); sfg::Notebook::Ptr notebook1( sfg::Notebook::Create() ); sfg::Notebook::Ptr notebook2( sfg::Notebook::Create() ); sfg::Notebook::Ptr notebook3( sfg::Notebook::Create() ); sfg::Notebook::Ptr notebook4( sfg::Notebook::Create() ); notebook1->SetTabPosition( sfg::Notebook::TOP ); notebook2->SetTabPosition( sfg::Notebook::RIGHT ); notebook3->SetTabPosition( sfg::Notebook::BOTTOM ); notebook4->SetTabPosition( sfg::Notebook::LEFT ); sfg::Box::Ptr vertigo_box( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); sfg::Button::Ptr vertigo_button( sfg::Button::Create( L"Vertigo" ) ); vertigo_box->Pack( vertigo_button, true, true ); notebook1->AppendPage( boxmain, sfg::Label::Create( "Page Name Here" ) ); notebook1->AppendPage( notebook2, sfg::Label::Create( "Another Page" ) ); notebook2->AppendPage( notebook3, sfg::Label::Create( "Yet Another Page" ) ); notebook2->AppendPage( sfg::Label::Create( L"" ), sfg::Label::Create( "Dummy Page" ) ); notebook3->AppendPage( notebook4, sfg::Label::Create( "And Another Page" ) ); notebook3->AppendPage( sfg::Label::Create( L"" ), sfg::Label::Create( "Dummy Page" ) ); notebook4->AppendPage( vertigo_box, sfg::Label::Create( "And The Last Page" ) ); notebook4->AppendPage( sfg::Label::Create( L"" ), sfg::Label::Create( "Dummy Page" ) ); m_wndmain->Add( notebook1 ); // Signals. btnaddbuttonh->OnClick.Connect( &SampleApp::OnAddButtonHClick, this ); btnaddbuttonv->OnClick.Connect( &SampleApp::OnAddButtonVClick, this ); m_titlebar_toggle->OnClick.Connect( &SampleApp::OnToggleTitlebarClick, this ); btnhidewindow->OnClick.Connect( &SampleApp::OnHideWindowClicked, this ); btntogglespace->OnClick.Connect( &SampleApp::OnToggleSpaceClick, this ); m_limit_check->OnToggle.Connect( &SampleApp::OnLimitCharsToggle, this ); btnloadstyle->OnClick.Connect( &SampleApp::OnLoadThemeClick, this ); m_scale->GetAdjustment()->OnChange.Connect( &SampleApp::OnAdjustmentChange, this ); spinner_toggle->OnClick.Connect( &SampleApp::OnToggleSpinner, this ); m_wndmain->SetPosition( sf::Vector2f( 100.f, 100.f ) ); // Another window sfg::Window::Ptr second_window( sfg::Window::Create( sfg::Window::TITLEBAR | sfg::Window::BACKGROUND ) ); second_window->SetId( "second_window" ); second_window->SetTitle( "Another window" ); sfg::Box::Ptr box( sfg::Box::Create( sfg::Box::VERTICAL, 5.f ) ); box->Pack( sfg::Label::Create( "Aliquam sed pretium lacus." ), false ); box->Pack( sfg::Label::Create( "Nullam placerat mauris vel nulla sagittis pellentesque." ), false ); box->Pack( sfg::Label::Create( "Suspendisse in justo dui." ), false ); box->Pack( sfg::Label::Create( "Ut dolor massa, gravida eu facilisis convallis, convallis sed odio." ), false ); box->Pack( sfg::Label::Create( "Nunc placerat consequat vehicula." ), false ); second_window->Add( box ); second_window->SetPosition( sf::Vector2f( 10.f, 10.f ) ); second_window->SetId( "second_window" ); m_desktop.Add( second_window ); // Add window to desktop m_desktop.Add( m_wndmain ); // Play around with resource manager. sf::Font my_font; my_font.loadFromFile( "data/linden_hill.otf" ); m_desktop.GetEngine().GetResourceManager().AddFont( "custom_font", my_font, false ); // false -> do not manage! // Set properties. m_desktop.SetProperty( "Button#close:Normal", "Color", sf::Color::Yellow ); m_desktop.SetProperty( "Button#close", "FontName", "data/linden_hill.otf" ); m_desktop.SetProperty( "Button#close", "FontSize", 15.f ); m_desktop.SetProperty( "Window#second_window > Box > Label", "FontName", "custom_font" ); m_desktop.SetProperty( "Window#second_window > Box > Label", "FontSize", 18.f ); m_fps_counter = 0; m_fps_clock.restart(); sf::Clock clock; while( m_window.isOpen() ) { while( m_window.pollEvent( event ) ) { if( event.type == sf::Event::Closed ) { m_window.close(); } else if( event.type == sf::Event::Resized ) { m_desktop.UpdateViewRect( sf::FloatRect( 0.f, 0.f, static_cast<float>( event.size.width ), static_cast<float>( event.size.height ) ) ); } m_desktop.HandleEvent( event ); } m_window.draw( m_background_sprite ); sf::Uint64 microseconds = clock.getElapsedTime().asMicroseconds(); // Only update every 5ms if( microseconds > 5000 ) { m_desktop.Update( static_cast<float>( microseconds ) / 1000000.f ); clock.restart(); } sfg::Renderer::Get().Display( m_window ); m_window.display(); if( m_fps_clock.getElapsedTime().asMicroseconds() >= 1000000 ) { m_fps_clock.restart(); std::stringstream sstr; sstr << "SFGUI test -- FPS: " << m_fps_counter; m_window.setTitle( sstr.str() ); m_fps_counter = 0; } ++m_fps_counter; } }
void SampleApp::Run() { sf::Event event; //m_window.SetFramerateLimit( 60 ); //m_window.EnableVerticalSync( true ); // Tune Renderer m_sfgui.TuneUseFBO( true ); m_sfgui.TuneAlphaThreshold( .2f ); m_sfgui.TuneCull( true ); // Create widgets. m_wndmain = sfg::Window::Create( sfg::Window::TITLEBAR | sfg::Window::BACKGROUND | sfg::Window::RESIZE ); m_wndmain->SetTitle( L"Example application" ); sfg::Button::Ptr btnaddbuttonh( sfg::Button::Create( L"Add button horizontally" ) ); sfg::Button::Ptr btnaddbuttonv( sfg::Button::Create( L"Add button vertically" ) ); m_titlebar_toggle = sfg::ToggleButton::Create( "Toggle titlebar" ); m_titlebar_toggle->SetActive( true ); { sf::Image add_image; if( add_image.loadFromFile( "data/add.png" ) ) { sfg::Image::Ptr image( sfg::Image::Create( add_image ) ); btnaddbuttonh->SetImage( image ); image = sfg::Image::Create( add_image ); btnaddbuttonv->SetImage( image ); } } sfg::Button::Ptr btnhidewindow( sfg::Button::Create( L"Close window" ) ); btnhidewindow->SetId( "close" ); { sf::Image close_image; if( close_image.loadFromFile( "data/delete.png" ) ) { sfg::Image::Ptr image( sfg::Image::Create( close_image ) ); btnhidewindow->SetImage( image ); } } sfg::Button::Ptr btntogglespace( sfg::Button::Create( L"Box Spacing") ); sfg::Button::Ptr btnloadstyle( sfg::Button::Create( L"Load theme") ); m_entry = sfg::Entry::Create( L"Type" ); m_entry->SetRequisition( sf::Vector2f( 100.f, .0f ) ); m_entry->AppendText( L" something!" ); m_limit_check = sfg::CheckButton::Create( L"Limit to 4 chars" ); m_limit_check->SetId( "limit_check" ); sfg::Entry::Ptr password( sfg::Entry::Create() ); password->HideText( '*' ); // Layout. sfg::Box::Ptr boxtoolbar( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); boxtoolbar->SetSpacing( 5.f ); boxtoolbar->Pack( btnaddbuttonh, false ); boxtoolbar->Pack( btnaddbuttonv, false ); boxtoolbar->Pack( m_titlebar_toggle, false ); boxtoolbar->Pack( btnhidewindow, false ); boxtoolbar->Pack( m_entry, true ); boxtoolbar->Pack( m_limit_check, false ); sfg::Frame::Ptr frame1( sfg::Frame::Create( L"Toolbar 1" ) ); frame1->Add( boxtoolbar ); sfg::Box::Ptr boxtoolbar2( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); boxtoolbar2->SetSpacing( 5.f ); boxtoolbar2->Pack( btntogglespace, false ); boxtoolbar2->Pack( btnloadstyle, false ); m_boxbuttonsh = sfg::Box::Create( sfg::Box::HORIZONTAL ); m_boxbuttonsh->SetSpacing( 5.f ); m_boxbuttonsv = sfg::Box::Create( sfg::Box::VERTICAL ); m_boxbuttonsv->SetSpacing( 5.f ); sfg::Entry::Ptr username_entry( sfg::Entry::Create() ); username_entry->SetMaximumLength( 8 ); m_progress = sfg::ProgressBar::Create( sfg::ProgressBar::HORIZONTAL ); m_progress->SetRequisition( sf::Vector2f( 0.f, 20.f ) ); m_progress_vert = sfg::ProgressBar::Create( sfg::ProgressBar::VERTICAL ); m_progress_vert->SetRequisition( sf::Vector2f( 20.f, 0.f ) ); sfg::Separator::Ptr separatorv( sfg::Separator::Create( sfg::Separator::VERTICAL ) ); m_table = sfg::Table::Create(); m_table->Attach( sfg::Label::Create( L"Please login using your username and password (span example)." ), sf::Rect<sf::Uint32>( 0, 0, 2, 1 ), sfg::Table::FILL, sfg::Table::FILL | sfg::Table::EXPAND ); m_table->Attach( sfg::Label::Create( L"Username:"******"Password:"******"Login" ), sf::Rect<sf::Uint32>( 2, 1, 1, 2 ), sfg::Table::FILL, sfg::Table::FILL ); m_table->Attach( separatorv, sf::Rect<sf::Uint32>( 3, 0, 1, 3 ), sfg::Table::FILL, sfg::Table::FILL ); m_table->Attach( m_progress_vert, sf::Rect<sf::Uint32>( 4, 0, 1, 3 ), sfg::Table::FILL, sfg::Table::FILL ); m_table->SetRowSpacings( 5.f ); m_table->SetColumnSpacings( 5.f ); m_scrolled_window_box = sfg::Box::Create( sfg::Box::VERTICAL ); for( int i = 0; i < 5; i++ ) { sfg::Box::Ptr box = sfg::Box::Create( sfg::Box::HORIZONTAL ); for( int j = 0; j < 20; j++ ) { box->Pack( sfg::Button::Create( L"One button among many" ), true ); } m_scrolled_window_box->Pack( box, false ); } m_scrolled_window = sfg::ScrolledWindow::Create(); m_scrolled_window->SetRequisition( sf::Vector2f( .0f, 160.f ) ); m_scrolled_window->SetScrollbarPolicy( sfg::ScrolledWindow::HORIZONTAL_AUTOMATIC | sfg::ScrolledWindow::VERTICAL_AUTOMATIC ); m_scrolled_window->SetPlacement( sfg::ScrolledWindow::TOP_LEFT ); m_scrolled_window->AddWithViewport( m_scrolled_window_box ); sfg::Scrollbar::Ptr scrollbar( sfg::Scrollbar::Create() ); scrollbar->SetRange( .0f, 100.f ); m_scale = sfg::Scale::Create(); m_scale->SetAdjustment( scrollbar->GetAdjustment() ); m_scale->SetRequisition( sf::Vector2f( 100.f, .0f ) ); boxtoolbar2->Pack( m_scale, false ); m_combo_box = sfg::ComboBox::Create(); for( int index = 0; index < 30; ++index ) { std::stringstream sstr; sstr << "Item " << index; m_combo_box->AppendItem( sstr.str() ); } boxtoolbar2->Pack( m_combo_box, true ); sfg::Frame::Ptr frame2( sfg::Frame::Create( L"Toolbar 2" ) ); frame2->Add( boxtoolbar2 ); frame2->SetAlignment( sf::Vector2f( .8f, .0f ) ); sfg::Separator::Ptr separatorh( sfg::Separator::Create( sfg::Separator::HORIZONTAL ) ); sfg::Box::Ptr box_image( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); box_image->SetSpacing( 15.f ); sfg::Fixed::Ptr fixed_container( sfg::Fixed::Create() ); sfg::Button::Ptr fixed_button( sfg::Button::Create( L"I'm at (34,61)" ) ); fixed_container->Put( fixed_button, sf::Vector2f( 34.f, 61.f ) ); box_image->Pack( fixed_container, false ); sf::Image sfgui_logo; m_image = sfg::Image::Create(); if( sfgui_logo.loadFromFile( "data/sfgui.png" ) ) { m_image->SetImage( sfgui_logo ); box_image->Pack( m_image, false ); } sfg::Button::Ptr mirror_image( sfg::Button::Create( L"Mirror Image" ) ); box_image->Pack( mirror_image, false ); sfg::Box::Ptr spinner_box( sfg::Box::Create( sfg::Box::VERTICAL ) ); m_spinner = sfg::Spinner::Create(); m_spinner->SetRequisition( sf::Vector2f( 40.f, 40.f ) ); m_spinner->Start(); sfg::ToggleButton::Ptr spinner_toggle( sfg::ToggleButton::Create( L"Spin") ); spinner_toggle->SetActive( true ); spinner_box->SetSpacing( 5.f ); spinner_box->Pack( m_spinner, false ); spinner_box->Pack( spinner_toggle, false ); box_image->Pack( spinner_box, false ); sfg::Box::Ptr radio_box( sfg::Box::Create( sfg::Box::VERTICAL ) ); sfg::RadioButton::Ptr radio1( sfg::RadioButton::Create( "Radio 1" ) ); sfg::RadioButton::Ptr radio2( sfg::RadioButton::Create( "Radio 2", radio1->GetGroup() ) ); sfg::RadioButton::Ptr radio3( sfg::RadioButton::Create( "Radio 3", radio2->GetGroup() ) ); radio_box->Pack( radio1 ); radio_box->Pack( radio2 ); radio_box->Pack( radio3 ); box_image->Pack( radio_box, false ); sfg::SpinButton::Ptr spinbutton( sfg::SpinButton::Create( scrollbar->GetAdjustment() ) ); spinbutton->SetRequisition( sf::Vector2f( 80.f, 0.f ) ); spinbutton->SetDigits( 3 ); sfg::Box::Ptr spinbutton_box( sfg::Box::Create( sfg::Box::VERTICAL ) ); spinbutton_box->Pack( spinbutton, false, false ); box_image->Pack( spinbutton_box, false, false ); sfg::ComboBox::Ptr aligned_combo_box( sfg::ComboBox::Create() ); aligned_combo_box->AppendItem( L"I'm way over here" ); aligned_combo_box->AppendItem( L"Me too" ); aligned_combo_box->AppendItem( L"Me three" ); aligned_combo_box->SelectItem( 0 ); sfg::Alignment::Ptr alignment( sfg::Alignment::Create() ); alignment->Add( aligned_combo_box ); box_image->Pack( alignment, true ); alignment->SetAlignment( sf::Vector2f( 1.f, .5f ) ); alignment->SetScale( sf::Vector2f( 0.f, .01f ) ); sfg::Box::Ptr boxmain( sfg::Box::Create( sfg::Box::VERTICAL ) ); boxmain->SetSpacing( 5.f ); boxmain->Pack( scrollbar, false ); boxmain->Pack( m_progress, false ); boxmain->Pack( frame1, false ); boxmain->Pack( frame2, false ); boxmain->Pack( m_boxbuttonsh, false ); boxmain->Pack( m_boxbuttonsv, false ); boxmain->Pack( box_image, true ); boxmain->Pack( separatorh, false ); boxmain->Pack( m_table, true ); boxmain->Pack( m_scrolled_window ); sfg::Notebook::Ptr notebook1( sfg::Notebook::Create() ); sfg::Notebook::Ptr notebook2( sfg::Notebook::Create() ); sfg::Notebook::Ptr notebook3( sfg::Notebook::Create() ); sfg::Notebook::Ptr notebook4( sfg::Notebook::Create() ); notebook1->SetTabPosition( sfg::Notebook::TOP ); notebook2->SetTabPosition( sfg::Notebook::RIGHT ); notebook3->SetTabPosition( sfg::Notebook::BOTTOM ); notebook4->SetTabPosition( sfg::Notebook::LEFT ); sfg::Box::Ptr vertigo_box( sfg::Box::Create( sfg::Box::HORIZONTAL ) ); sfg::Button::Ptr vertigo_button( sfg::Button::Create( L"Vertigo" ) ); vertigo_box->Pack( vertigo_button, true, true ); notebook1->AppendPage( boxmain, sfg::Label::Create( "Page Name Here" ) ); notebook1->AppendPage( notebook2, sfg::Label::Create( "Another Page" ) ); notebook2->AppendPage( notebook3, sfg::Label::Create( "Yet Another Page" ) ); notebook2->AppendPage( sfg::Label::Create( L"" ), sfg::Label::Create( "Dummy Page" ) ); notebook3->AppendPage( notebook4, sfg::Label::Create( "And Another Page" ) ); notebook3->AppendPage( sfg::Label::Create( L"" ), sfg::Label::Create( "Dummy Page" ) ); notebook4->AppendPage( vertigo_box, sfg::Label::Create( "And The Last Page" ) ); notebook4->AppendPage( sfg::Label::Create( L"" ), sfg::Label::Create( "Dummy Page" ) ); m_wndmain->Add( notebook1 ); // Signals. btnaddbuttonh->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnAddButtonHClick, this ); btnaddbuttonv->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnAddButtonVClick, this ); m_titlebar_toggle->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnToggleTitlebarClick, this ); btnhidewindow->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnHideWindowClicked, this ); btntogglespace->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnToggleSpaceClick, this ); m_limit_check->GetSignal( sfg::ToggleButton::OnToggle ).Connect( &SampleApp::OnLimitCharsToggle, this ); btnloadstyle->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnLoadThemeClick, this ); m_scale->GetAdjustment()->GetSignal( sfg::Adjustment::OnChange ).Connect( &SampleApp::OnAdjustmentChange, this ); spinner_toggle->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnToggleSpinner, this ); mirror_image->GetSignal( sfg::Widget::OnLeftClick ).Connect( &SampleApp::OnMirrorImageClick, this ); spinbutton->SetValue( 20.f ); spinbutton->GetAdjustment()->SetMinorStep( .8f ); m_wndmain->SetPosition( sf::Vector2f( 100.f, 100.f ) ); // Another window sfg::Window::Ptr second_window( sfg::Window::Create( sfg::Window::TITLEBAR | sfg::Window::BACKGROUND | sfg::Window::RESIZE ) ); second_window->SetId( "second_window" ); second_window->SetTitle( "Resize this window to see ad-hoc wrapping." ); sfg::Box::Ptr box( sfg::Box::Create( sfg::Box::VERTICAL, 5.f ) ); sfg::Label::Ptr lipsum = sfg::Label::Create( "Nullam ut ante leo. Quisque consequat condimentum pulvinar. " "Duis a enim sapien, ut vestibulum est. Vestibulum commodo, orci non gravida. " "Aliquam sed pretium lacus. " "Nullam placerat mauris vel nulla sagittis pellentesque. " "Suspendisse in justo dui.\n" "Ut dolor massa, gravida eu facilisis convallis, convallis sed odio.\n" "Nunc placerat consequat vehicula." ); lipsum->SetRequisition( sf::Vector2f( 400.f, 0.f ) ); lipsum->SetLineWrap( true ); box->Pack( lipsum ); second_window->Add( box ); second_window->SetPosition( sf::Vector2f( 10.f, 10.f ) ); second_window->SetId( "second_window" ); m_desktop.Add( second_window ); sfg::Window::Ptr third_window( sfg::Window::Create( sfg::Window::TITLEBAR | sfg::Window::BACKGROUND | sfg::Window::RESIZE ) ); m_gl_canvas = sfg::Canvas::Create( true ); m_gl_canvas->SetRequisition( sf::Vector2f( 200.f, 150.f ) ); third_window->Add( m_gl_canvas ); third_window->SetId( "third_window" ); third_window->SetTitle( "Embedded OpenGL drawing" ); third_window->SetPosition( sf::Vector2f( 480.f, 20.f ) ); m_desktop.Add( third_window ); sf::Texture texture; texture.loadFromImage( sfgui_logo ); m_canvas_sprite.setTexture( texture ); sfg::Window::Ptr fourth_window( sfg::Window::Create( sfg::Window::TITLEBAR | sfg::Window::BACKGROUND | sfg::Window::RESIZE ) ); m_sfml_canvas = sfg::Canvas::Create(); m_sfml_canvas->SetRequisition( sf::Vector2f( static_cast<float>( texture.getSize().x ), static_cast<float>( texture.getSize().y ) ) ); fourth_window->Add( m_sfml_canvas ); fourth_window->SetId( "fourth_window" ); fourth_window->SetTitle( "Embedded SFML drawing" ); fourth_window->SetPosition( sf::Vector2f( 760.f, 20.f ) ); m_desktop.Add( fourth_window ); // Add window to desktop m_desktop.Add( m_wndmain ); // Play around with resource manager. sf::Font my_font; my_font.loadFromFile( "data/linden_hill.otf" ); m_desktop.GetEngine().GetResourceManager().AddFont( "custom_font", my_font, false ); // false -> do not manage! // Set properties. m_desktop.SetProperty( "Button#close:Normal", "Color", sf::Color::Yellow ); // #close is sufficient since there is only 1 widget with this id m_desktop.SetProperty( "#close", "FontName", "data/linden_hill.otf" ); m_desktop.SetProperty( "#close", "FontSize", 15.f ); // Multiple properties can be set at once to save calls. m_desktop.SetProperties( "Window#second_window > Box > Label {" " FontName: custom_font;" " FontSize: 18;" "}" ); m_fps_counter = 0; m_fps_clock.restart(); sf::Clock clock; sf::Clock frame_time_clock; sf::Int64 frame_times[5000]; std::size_t frame_times_index = 0; while( m_window.isOpen() ) { while( m_window.pollEvent( event ) ) { if( event.type == sf::Event::Closed ) { m_window.close(); } else if( event.type == sf::Event::Resized ) { m_desktop.UpdateViewRect( sf::FloatRect( 0.f, 0.f, static_cast<float>( event.size.width ), static_cast<float>( event.size.height ) ) ); } m_desktop.HandleEvent( event ); } m_window.draw( m_background_sprite ); sf::Uint64 microseconds = clock.getElapsedTime().asMicroseconds(); // Only update every 5ms if( microseconds > 5000 ) { m_desktop.Update( static_cast<float>( microseconds ) / 1000000.f ); clock.restart(); // Only refresh canvas contents every 5ms too m_gl_canvas->Bind(); m_gl_canvas->Clear( sf::Color( 0, 0, 0, 0 ), true ); RenderCustomGL(); m_gl_canvas->Display(); m_gl_canvas->Unbind(); m_sfml_canvas->Bind(); m_sfml_canvas->Clear( sf::Color( 0, 0, 0, 0 ) ); RenderCustomSFML(); m_sfml_canvas->Display(); m_sfml_canvas->Unbind(); m_window.setActive( true ); } m_sfgui.Display( m_window ); m_window.display(); sf::Int64 frame_time = frame_time_clock.getElapsedTime().asMicroseconds(); frame_time_clock.restart(); frame_times[ frame_times_index ] = frame_time; frame_times_index = ( frame_times_index + 1 ) % 5000; if( m_fps_clock.getElapsedTime().asMicroseconds() >= 1000000 ) { m_fps_clock.restart(); sf::Int64 total_time = 0; for( std::size_t index = 0; index < 5000; ++index ) { total_time += frame_times[index]; } std::stringstream sstr; sstr << "SFGUI test -- FPS: " << m_fps_counter << " -- Frame Time (microsecs): min: " << *std::min_element( frame_times, frame_times + 5000 ) << " max: " << *std::max_element( frame_times, frame_times + 5000 ) << " avg: " << static_cast<float>( total_time ) / 5000.f; m_window.setTitle( sstr.str() ); m_fps_counter = 0; } ++m_fps_counter; } glDeleteLists( m_custom_draw_display_list, 1 ); }
MainMenu::MainMenu(sf::RenderWindow &w) :Controller(w), usernameTextBox(&font, sf::Vector2f(0, 0), sf::Vector2f(100, 50)), serverIpTextBox(&font, sf::Vector2f(0, 0), sf::Vector2f(100, 30), 2), portTextBox(&font, sf::Vector2f(0, 0), sf::Vector2f(100, 30), 2) { std::cout << "Error: Main Menu not constructed with access to parent app"; w.close(); }
int main(){ srand(time(NULL)); Background::load_background(); Sound::load_sounds(); Sprites::load_sprites(); Font::load_font(); window.setFramerateLimit(30); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shot_counter==0){ break; } window.draw(Background::before_game_start_sprite); window.display(); } Hero hero; Enemys enemys; while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } shot_counter++; shot_counter%=10; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shot_counter==0){ hero.fire(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){ hero.move_left(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){ hero.move_right(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){ hero.move_up(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){ hero.move_down(); } Sound::play_background_music(); Background::show(window); hero.turn(window); enemys.turn(window); window.display(); if (hero.get_health()<=0) break; } while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shot_counter==0){ break; } Sound::game_music.stop(); window.draw(Background::gameover_sprite); window.display(); } return 0; }
void Level1::eventListen(sf::RenderWindow &window) { sf::Event event; while (window.pollEvent(event)) { // get the current mouse position in the window mPixelPos = sf::Mouse::getPosition(window); // convert it to world coordinates mWorldPos = window.mapPixelToCoords(mPixelPos); switch (event.type) { //window closed case sf::Event::Closed: window.close(); break; //mouse button pressed case sf::Event::MouseButtonPressed: //if Inventory Mode is enabled, only check for collisions with Items in Inventory if (mUI->getState() == UI::INVENTORY) { mInventory->checkCollision(mInventory->getItems(), mWorldPos, *mUI); mInventory->setCraftPos(mInventory->getSelectedItem()); if (mInventory->craftCheck()) { mInventory->craftItem(mInventory->getCraftSelect1(), mInventory->getCraftSelect2()); //Clues mHasCraftedFishingRod = true; if (mClues->getClue(2)->getState2()) { mClues->getClue(3)->setState2(); mClues->getClue(4)->setState1(); mUI->setActiveAnimation("CluesIconGlowOnce"); } } } else if (mCursor->getMode() == Cursor::DIALOGUE) { mDialogueSystem->setState(); } else if (mUI->getState() != UI::INGAME) { mUI->checkCollision(mWorldPos); } else if (mCursor->getMode() != Cursor::DISABLED && !mPushingBlock && !mFishing) { mouseClick(event); } break; case sf::Event::MouseButtonReleased: if (mUI->getState() == UI::INVENTORY) { mInventory->swapCheck(); mInventory->deSelectCheck(); mInventory->setCraftPos(mInventory->getSelectedItem()); } else if (mCursor->getMode() != Cursor::DISABLED && !mPushingBlock && !mFishing) { mouseReleased(event); } break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::I) { if (mUI->getState() == UI::INVENTORY) { mUI->setState(UI::INGAME); mCursor->setMode(Cursor::NORMAL); } else if (mCursor->getMode() != Cursor::DIALOGUE) { mUI->setState(UI::INVENTORY); mCursor->setMode(Cursor::INVENTORY); mMenuInventorySound.play(); if (mUI->getActiveAnimation() == "InventoryIconGlow" || mUI->getActiveAnimation() == "InventoryIconGlowOnce") { mUI->setActiveAnimation("None"); } } } if (event.key.code == sf::Keyboard::P) { mPlayer->togglePlayer(); } if (event.key.code == sf::Keyboard::Escape) { if (mUI->getState() == UI::EXIT || mUI->getState() == UI::INVENTORY || mUI->getState() == UI::CLUES) { mUI->setState(UI::INGAME); mCursor->setMode(Cursor::NORMAL); } else if (mCursor->getMode() != Cursor::DIALOGUE) { mUI->setState(UI::EXIT); mCursor->setMode(Cursor::MENU); } } break; default: break; } } }
void PlayGame(sf::RenderWindow& window) { sf::View view; sf::Image layout; sf::Music theme; theme.openFromFile("resources/audio/Child of Light - Boss Battle Theme.wav"); theme.play(); int mapNum = rand() % 4 + 1; string mapString("resources/environment/map." + std::to_string(mapNum) + ".png"); //string mapString("resources/environment/map." + std::to_string(mapNum) + ".png"); string outputMapString("Loaded Map " + std::to_string(mapNum) + "."); cout << outputMapString << endl; layout.loadFromFile(mapString); sf::Texture red; sf::Texture green; sf::Texture blue; sf::Texture black; sf::Texture blank; red.loadFromFile("resources/environment/darkgrassyrock.jpg"); green.loadFromFile("resources/environment/playerSpawn.jpg"); blue.loadFromFile("resources/environment/purplecliffrock.jpg"); black.loadFromFile("resources/environment/darkgrassyrock.jpg"); blank.loadFromFile("resources/environment/darkestrock.jpg"); Map currentMap(window, 150, red, green, blue, black, blank, layout); sf::Clock deltaTimeClock; float DeltaTime = 0; // load some resources like textures which will be used for the duration of the game sf::Texture petRockTex; petRockTex.loadFromFile("resources/character/petRock.png"); sf::Clock spawnTime; bool pause = false; sf::Texture reaperBossIdleTex; reaperBossIdleTex.loadFromFile("resources/character/Reaper Boss-Idle.png"); //window.setFramerateLimit(60); //std::vector<Character*> petRockList; std::vector<std::unique_ptr<Character>> petRockList; MeleeWeapon sword("axe", "gold", 5, 9, 10, "Golden-BattleAxe.png"); Player player(100, 10, 10, 10, 10, 10, 10, 10, 10, window, petRockList, DeltaTime, currentMap); //ReaperBoss reaperBoss(500, window, player); player.equipMelee(sword); sf::Font asmanFont; sf::Text pauseText; asmanFont.loadFromFile("resources/font/ASMAN.ttf"); pauseText.setFont(asmanFont); pauseText.setString("Paused"); pauseText.setCharacterSize(200); pauseText.setColor(sf::Color::Red); pauseText.setPosition(player.position.x - 350, player.position.y - 20); for (int i = 0; i < 10; i++) { // make 10 enemies std::unique_ptr<Character> newPetRock(new PetRock(1, window, petRockTex, player, DeltaTime, currentMap)); petRockList.push_back(std::move(newPetRock)); } //ReaperBoss reaperBoss(500, window, player); std::unique_ptr<Character> reaperBoss(new ReaperBoss(750, window, player, DeltaTime, currentMap)); petRockList.push_back(std::move(reaperBoss)); //sf::Sprite backGround; //sf::Texture backGroundTex; //backGroundTex.loadFromFile("resources/environment/floorBackground.jpg"); //backGround.setTexture(backGroundTex); //backGround.setScale(5, 5); view.setCenter(sf::Vector2f(player.sprite.getPosition().x, player.sprite.getPosition().y)); view.setSize(1780, 980); while (window.isOpen()) { sf::Time timeFromClock = deltaTimeClock.restart(); DeltaTime = timeFromClock.asSeconds(); if (spawnTime.getElapsedTime().asSeconds() > 10 && petRockList.size() < 10) { for (int i = 0; i < 10; i++) { // make 10 enemies std::unique_ptr<Character> newPetRock(new PetRock(1, window, petRockTex, player, DeltaTime, currentMap)); petRockList.push_back(std::move(newPetRock)); } spawnTime.restart(); } if (!pause && sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { pause = true; } if (pause && sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) { pause = false; } // get all the input first every frame sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } // input loop ended window.setView(view); view.setCenter(sf::Vector2f(player.sprite.getPosition().x, player.sprite.getPosition().y)); window.clear(); if (!pause) { //This is the pause function //window.draw(backGround); currentMap.Update(); player.Update(); for (int i = 0; i < petRockList.size(); i++) { petRockList.at(i)->Update(); } window.draw(player.scoreText); } else { window.draw(pauseText); } window.display(); if (!player.alive) { return; } } }
void Game::manageEvents(sf::RenderWindow &window, Character &player, TileMap map) { sf::Event event; while (window.pollEvent(event)) { // Close window : exit if (event.type == Event::Closed) { window.close(); deleteAllMobs(); } // Escape pressed : exit else if (Keyboard::isKeyPressed(Keyboard::Escape)) { window.close(); deleteAllMobs(); } //Right arrow : move player right else if (Keyboard::isKeyPressed(Keyboard::Right)) { player.getAnimatedWalk().y=48*2; player.collisionWithTileManager(map); player.moveRight(); player.canMove(); } //Left arrow : move player left else if (Keyboard::isKeyPressed(Keyboard::Left)) { player.getAnimatedWalk().y=48; player.collisionWithTileManager(map); player.moveLeft(); player.canMove(); } //Up arrow : move player up else if (Keyboard::isKeyPressed(Keyboard::Up)) { player.getAnimatedWalk().y=48*3; player.collisionWithTileManager(map); player.moveUp(); player.canMove(); } //Down arrow : move player down else if (Keyboard::isKeyPressed(Keyboard::Down)) { player.getAnimatedWalk().y=0; player.collisionWithTileManager(map); player.moveDown(); player.canMove(); } if(Keyboard::isKeyPressed(Keyboard::Right)||Keyboard::isKeyPressed(Keyboard::Left) || //So walk animation only occur Keyboard::isKeyPressed(Keyboard::Up) ||Keyboard::isKeyPressed(Keyboard::Down)) //when pler moved { //Animates the plaer's movements player.getAnimatedWalk().x += 47; if(player.getAnimatedWalk().x>=47*2) player.getAnimatedWalk().x=0; player.getSprite().setTextureRect(IntRect(player.getAnimatedWalk().x,player.getAnimatedWalk().y,47,47)); } } }
void Engine::startMenu(sf::RenderWindow &window) { Menu menu(profiles); while (bMenu) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Up)) { menu.selectOption(1); } if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Down)) { menu.selectOption(2); } if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Right)) { menu.selectOption(3); } if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Left)) { menu.selectOption(4); } if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space)) { int request = menu.useOption(this->iBombs, this->iDynamites, this->currentProfile); if (request == 1)//save profiles { this->profiles->Save(); } else if (request == 2) //exit { window.close(); this->brun = false; return; } else if (request == 3) { bool bResult = true; sf::String profileName; while (bResult) { while (window.pollEvent(event)) { if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space)) { bResult = false; } else if (event.type == sf::Event::TextEntered) { if (event.text.unicode > 47 && event.text.unicode < 123) { profileName += event.text.unicode; } } } sf::Text Player; sf::Font font; font.loadFromFile("C:\\Users\\Quantzo\\Source\\Repos\\ProjektPK4\\Pk4Project\\Pk4Project\\Cinta Adalah Perhatian.ttf"); Player.setFont(font); Player.setCharacterSize(50); Player.setString(profileName); Player.setPosition(20, 200); window.clear(); window.draw(Player); window.display(); } Profile tmp; tmp.setName(profileName); this->profiles->addProfile(tmp); } else if (request == 4) { this->bGame = true; this->bMenu = false; return; } } } window.clear(); menu.Draw(window); window.display(); } }
void Window::Destroy() { _window.close(); }
//pass some parameters at some point //one of them being map...? void gameLoop(sf::Clock clock, sf::Time frameGap) { std::vector<Projectile*>::iterator prjIterator; /* for (int i=0;i<9;i++) { Projectile prj("blueBullet.png",10,11,1280/2,720/2,(360/8)*i,2); Projectiles.push_back(prj); } */ // for (int i=0;i<9;i++) { //Projectiles.push_back(new Laser("blueBullet.png",10,11,1280/2,720/2,(360/8)*i,10)); //} Projectiles.push_back(new Projectile("blueBullet.png",10,11,1280/2,720/2,0, 20)); //When an object is pushed, it loses its texture and must be retextured //OBSOLETE //for (prjIterator=Projectiles.begin(); prjIterator!=Projectiles.end(); ++prjIterator) { //(*prjIterator)->retexture(); // } /******************v NECESSARY STUFF v*********************/ while (running) { /***********************v Keyboard v*********************/ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { left = true; } else left = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { right = true; } else right = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { up = true; } else up = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { down = true; } else down = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { w = true; } else w = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { a = true; } else a = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { s = true; } else s = false; if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { d = true; } else d = false; //gets the mouse coordinates mirror.mouseX = sf::Mouse::getPosition(window).x; mirror.mouseY = sf::Mouse::getPosition(window).y; /***********************^ Keyboard ^*********************/ sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: window.close(); break; } } /******************^ NECESSARY STUFF ^*********************/ //*****if one frame completes if (clock.getElapsedTime() >= frameGap) { //timer reset clock.restart(); totalFrame++; //key response: arrows or wasd if (left || a) p.dX = (p.speed*-1); else if (right || d) p.dX = p.speed; else p.dX = 0; if (up || w) p.dY = (p.speed*-1); else if (down || s) p.dY = p.speed; else p.dY = 0; //movement**************************************** p.step(); mirror.step(p, mirror.mouseX, mirror.mouseY); /****v Projectiles v****/ for (prjIterator=Projectiles.begin(); prjIterator!=Projectiles.end(); ++prjIterator) { (*prjIterator)->step(); } /****^ Projectiles ^****/ //reset window window.clear(); //draws new stuff********************************* window.draw(p.shape); window.draw(mirror.sprite); //testing an hp bar window.draw(p.hpSprite); /****v Projectiles v****/ for (prjIterator=Projectiles.begin(); prjIterator!=Projectiles.end(); ++prjIterator) { window.draw((*prjIterator)->sprite); } /****^ Projectiles ^****/ //display new stuff window.display(); } } }
void Graph::gestEvent(sf::RenderWindow &window, sf::Time time) { sf::Event event; sf::View view; view = window.getView(); view.move((-sf::Keyboard::isKeyPressed(sf::Keyboard::Left) + sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) * time.asSeconds() * 1000, (-sf::Keyboard::isKeyPressed(sf::Keyboard::Up) + sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) * time.asSeconds() * 1000); window.setView(view); while (window.pollEvent(event)) { if (event.type == sf::Event::Resized) { sf::View view; view = window.getView(); view.setSize(event.size.width, event.size.height); window.setView(view); } if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::TextEntered) { if (_target != NULL) _target->write(event.text.unicode); replaceEntity(); } if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) window.close(); if (event.key.code == sf::Keyboard::F1) saveToFile(); if (event.key.code == sf::Keyboard::F2) saveToImage(); } if (event.type == sf::Event::MouseButtonPressed) { if (event.mouseButton.button == sf::Mouse::Left) { bool inside = false; for(std::vector<std::vector<Entity*> >::iterator i = _entities.begin(); !inside && i != _entities.end();++i) { for(std::vector<Entity*>::iterator j = (*i).begin(); !inside && j != (*i).end();++j) { State state; state = (*j)->inside(window.mapPixelToCoords(sf::Vector2<int>(event.mouseButton.x, event.mouseButton.y))); if (state == INSIDE) { inside = true; _target = *j; } else if (state == KILLME) { inside = true; delete (*j); (*i).erase(j); if ((*i).empty()) _entities.erase(i); } } } if (!inside) _target = NULL; } replaceEntity(); } } }
void Events::processEvents(sf::RenderWindow& window, sf::Event& event) { // Calculate coordinate adjustment factors int viewShiftX = window.getSize().x/2 - window.getView().getCenter().x; int viewShiftY = window.getSize().y/2 - window.getView().getCenter().y; resetStates(); while(window.pollEvent(event)) { // Close Event if(event.type == sf::Event::Closed) { window.close(); } // Mouse if(event.type == sf::Event::MouseButtonPressed) { if(event.mouseButton.button == sf::Mouse::Left) { lastMouseLeft.x = sf::Mouse::getPosition(window).x - viewShiftX; lastMouseLeft.y = sf::Mouse::getPosition(window).y - viewShiftY; mouseLeftClicked = true; mouseLeftHeld = true; } if(event.mouseButton.button == sf::Mouse::Right) { lastMouseRight.x = sf::Mouse::getPosition(window).x - viewShiftX; lastMouseRight.y = sf::Mouse::getPosition(window).y - viewShiftY; mouseRightClicked = true; mouseRightHeld = true; } } if(event.type == sf::Event::MouseButtonReleased) { if(event.mouseButton.button == sf::Mouse::Left) { mouseLeftHeld = false; } if(event.mouseButton.button == sf::Mouse::Right) { mouseRightHeld = false; } } // Get last mouse coordinates lastMouse.x = sf::Mouse::getPosition(window).x - viewShiftX; lastMouse.y = sf::Mouse::getPosition(window).y - viewShiftY; // Get last mouse coordinates relative to window lastMouseWindow.x = sf::Mouse::getPosition(window).x; lastMouseWindow.y = sf::Mouse::getPosition(window).y; // Keyboard if(event.type == sf::Event::KeyPressed) { switch(event.key.code) { case sf::Keyboard::A : isA = true; isAHeld = true; break; case sf::Keyboard::D : isD = true; isDHeld = true; break; case sf::Keyboard::E : isE = true; isEHeld = true; break; case sf::Keyboard::F : isF = true; isFHeld = true; break; case sf::Keyboard::G : isG = true; isGHeld = true; break; case sf::Keyboard::H : isH = true; isHHeld = true; break; case sf::Keyboard::I : isI = true; isIHeld = true; break; case sf::Keyboard::J : isJ = true; isJHeld = true; break; case sf::Keyboard::K : isK = true; isKHeld = true; break; case sf::Keyboard::L : isL = true; isLHeld = true; break; case sf::Keyboard::O : isO = true; isOHeld = true; break; case sf::Keyboard::P : isP = true; isPHeld = true; break; case sf::Keyboard::Q : isQ = true; isQHeld = true; break; case sf::Keyboard::R : isR = true; isRHeld = true; break; case sf::Keyboard::S : isS = true; isSHeld = true; break; case sf::Keyboard::T : isT = true; isTHeld = true; break; case sf::Keyboard::U : isU = true; isUHeld = true; break; case sf::Keyboard::W : isW = true; isWHeld = true; break; case sf::Keyboard::Y : isY = true; isYHeld = true; break; case sf::Keyboard::Z : isZ = true; isZHeld = true; break; case sf::Keyboard::Space : isSpace = true; isSpaceHeld = true; break; case sf::Keyboard::LControl : isLCTRL = true; isLCTRLHeld = true; break; case sf::Keyboard::LAlt : isALT = true; isALTHeld = true; break; case sf::Keyboard::Num1 : isNum1 = true; isNum1Held = true; break; case sf::Keyboard::Num2 : isNum2 = true; isNum2Held = true; break; case sf::Keyboard::Num3 : isNum3 = true; isNum3Held = true; break; case sf::Keyboard::Num4 : isNum4 = true; isNum4Held = true; break; case sf::Keyboard::Num5 : isNum5 = true; isNum5Held = true; break; case sf::Keyboard::Numpad1 : isNumPad1 = true; isNumPad1Held = true; break; case sf::Keyboard::Numpad2 : isNumPad2 = true; isNumPad2Held = true; break; case sf::Keyboard::Numpad3 : isNumPad3 = true; isNumPad3Held = true; break; case sf::Keyboard::Numpad4 : isNumPad4 = true; isNumPad4Held = true; break; case sf::Keyboard::Escape : isEsc = true; break; } } if(event.type == sf::Event::KeyReleased) { switch(event.key.code) { case sf::Keyboard::A : isAHeld = false; break; case sf::Keyboard::D : isDHeld = false; break; case sf::Keyboard::E : isEHeld = false; break; case sf::Keyboard::F : isFHeld = false; break; case sf::Keyboard::G : isGHeld = false; break; case sf::Keyboard::H : isHHeld = false; break; case sf::Keyboard::I : isIHeld = false; break; case sf::Keyboard::J : isJHeld = false; break; case sf::Keyboard::K : isKHeld = false; break; case sf::Keyboard::L : isLHeld = false; break; case sf::Keyboard::O : isOHeld = false; break; case sf::Keyboard::P : isPHeld = false; break; case sf::Keyboard::Q : isQHeld = false; break; case sf::Keyboard::R : isRHeld = false; break; case sf::Keyboard::S : isSHeld = false; break; case sf::Keyboard::T : isTHeld = false; break; case sf::Keyboard::U : isUHeld = false; break; case sf::Keyboard::W : isWHeld = false; break; case sf::Keyboard::Y : isYHeld = false; break; case sf::Keyboard::Z : isZHeld = false; break; case sf::Keyboard::Space : isSpaceHeld = false; break; case sf::Keyboard::LControl : isLCTRLHeld = false; break; case sf::Keyboard::LAlt : isALTHeld = false; break; case sf::Keyboard::Num1 : isNum1Held = false; break; case sf::Keyboard::Num2 : isNum2Held = false; break; case sf::Keyboard::Num3 : isNum3Held = false; break; case sf::Keyboard::Num4 : isNum4Held = false; break; case sf::Keyboard::Num5 : isNum5Held = false; break; case sf::Keyboard::Numpad1 : isNumPad1Held = false; break; case sf::Keyboard::Numpad2 : isNumPad2Held = false; break; case sf::Keyboard::Numpad3 : isNumPad3Held = false; break; case sf::Keyboard::Numpad4 : isNumPad4Held = false; break; } } if(event.type == sf::Event::LostFocus || event.type == sf::Event::MouseLeft) { resetHeldStates(); } } }
void gameClient(sf::RenderWindow & window,char * mapName){ int i,/*displacementX=0,displacementY=0,*/ menu=0; gameMap_t map; // int redrawMMAP = 1; cursor_t gCur; gCur.status = 0; gCur.cell = NULL; player_t players; players.resourcesPlayer1 = 400; players.resourcesPlayer2 = 400; // player_t player2; unsigned int currentPlayerTurn=0; selection_t select; select.status=0; select.cell=NULL; createMap(&map); /* Set textures. */ sf::Texture background, interface_image,menu1,menu2,grind,cursor,pCourse,endTurn1,endTurn2,sel,enemy,fpT,spT,cT1,cT2,cB1,cB2; sf::Sprite gameBackground,gameInterface,gameMenu,gameGrind,gameCursor,aCell,gameEndTurn,cSel,cEnemy,cpT,cTc,cBc; menu1.loadFromFile("gameInterface/menu.png"); fpT.loadFromFile("gameInterface/fpTurn.png"); spT.loadFromFile("gameInterface/spTurn.png"); enemy.loadFromFile("gameInterface/enemyCell.png"); sel.loadFromFile("gameInterface/selected.png"); menu2.loadFromFile("gameInterface/menuConfirmed.png"); grind.loadFromFile("maps/grind.png"); endTurn1.loadFromFile("gameInterface/endTurn.png"); endTurn2.loadFromFile("gameInterface/endTurnConfirmed.png"); cT1.loadFromFile("gameInterface/cTank.png"); cT2.loadFromFile("gameInterface/cTankC.png"); cB1.loadFromFile("gameInterface/cBuggy.png"); cB2.loadFromFile("gameInterface/cBuggyC.png"); //test addUnit(&map,window,0,TANK,15,0); addUnit(&map,window,0,BUGGY,12,0); addUnit(&map,window,0,TANK,9,0); addUnit(&map,window,1,TANK,27,18); addUnit(&map,window,1,BUGGY,30,18); addUnit(&map,window,1,TANK,33,18); addObject(&map,window,0,20,12); addObject(&map,window,0,10,10); addObject(&map,window,0,30,8); cpT.setPosition(130,0); cursor.loadFromFile("gameInterface/setCell.png"); pCourse.loadFromFile("gameInterface/availableCell.png"); background.loadFromFile(mapName); interface_image.loadFromFile("gameInterface/mainInterface.png"); gameBackground.setTexture(background); cSel.setTexture(sel); aCell.setTexture(pCourse); gameGrind.setTexture(grind); gameInterface.setTexture(interface_image); cEnemy.setTexture(enemy); gameCursor.setTexture(cursor); drawMinMap(window,currentPlayerTurn,&map); while (window.isOpen()){ cameraMouseMove(window,&map); mouseEvents(window,&map); menu=gameSelection(window,gameMenu,menu1,menu2,gameEndTurn,endTurn1,endTurn2,cTc,cT1,cT2,cBc,cB1,cB2); gameBackground.setPosition(map.displacementX,map.displacementY); gameInterface.setPosition(-1,-1); gameMenu.setPosition(1700,0); gameEndTurn.setPosition(1500,5); cTc.setPosition(1680,750); cBc.setPosition(1680,890); selectUnit(&map,window,cSel,&select,currentPlayerTurn); if(select.status==1){ cSel.setPosition(select.cell->X,select.cell->Y); } sf::Event event; if (sf::Mouse::isButtonPressed(sf::Mouse::Left)&&menu==1){ if(pauseMenu(window)==0){ break; } } if (sf::Mouse::isButtonPressed(sf::Mouse::Left)&&menu>=3){ createUnit(&map,&players,currentPlayerTurn,menu,window,&select,gameBackground,gameInterface,gameMenu,gameEndTurn,cTc,cBc); } if (sf::Mouse::isButtonPressed(sf::Mouse::Left)&&menu==2){ isEnd(&map,window,endFn); getOP(&map,&players); getResources(&map,currentPlayerTurn,&players); deleteSelect(&select); overmind(&map,window,&select,aCell,cEnemy,&gCur,gameBackground,gameInterface,gameMenu,gameEndTurn,currentPlayerTurn,cTc,&players,cBc); endTurn(&map); Sleep(500); } if (sf::Mouse::isButtonPressed(sf::Mouse::Right)){ deleteSelect(&select); } while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } window.clear(sf::Color::Black); window.draw(gameBackground); drawUnits(&map,window); if(cursorConfirm(window,&map,gameCursor,&gCur)==1){ window.draw(gameCursor); } if(select.status==1){ window.draw(cSel); findWay(&map,window,&select,aCell,cEnemy,&gCur,gameBackground,gameInterface,gameMenu,gameEndTurn,currentPlayerTurn,cTc,&players,cBc); } window.draw(gameInterface); if(select.status==1){ pData(window,&select); } window.draw(gameMenu); window.draw(gameEndTurn); drawMinMap(window,currentPlayerTurn,&map); drawPlayer(window,currentPlayerTurn,&players); window.draw(cTc); window.draw(cBc); window.display(); } }
void Game() { bgm.Play(); sf::Clock clock; sf::Event event; while (window.isOpen()) { //系统关键位置初始化 while (window.pollEvent(event)) { if (event.type == sf::Event::Closed){ window.close(); } } background.Show(); sf::Time time1 = clock.getElapsedTime(); //显示分数 text.ShowScore(); //显示敌机以及子弹 for (int i = 0; i < 80; i++) { if (time1 >= sf::seconds(1.5*i)) { enemy[i].Show(); window.draw(enemy_bullet[i].enemy_bullet); enemy_bullet[i].enemy_bullet.setPosition(sf::Vector2f(enemy[i].enemy.getPosition().x + 30, enemy[i].enemy.getPosition().y + 60)); enemy_bullet[i].Show(); } } //显示飞机、控制移动 rocket.move(); //开炮 rocket.Gun(); bullet.Show(); if (bullet.bullet.getPosition().y <= 10) { bullet.Gone(); } //碰撞处理 sf::FloatRect collision_enemy[80]; sf::FloatRect collision_enemy_bullet[80]; sf::FloatRect boundingBox2 = rocket.rocket.getGlobalBounds(); for (int i = 0; i < 80; i++) { collision_enemy[i] = enemy[i].enemy.getGlobalBounds(); collision_enemy_bullet[i] = enemy_bullet[i].enemy_bullet.getGlobalBounds(); sf::FloatRect boundingBox1 = bullet.bullet.getGlobalBounds(); if ((boundingBox1.intersects(collision_enemy[i])) && (enemy[i].enemy.getPosition().y >= 0.0f)) { bullet.bullet.setPosition(sf::Vector2f(1000, 0)); bgs1.Play(); score += 100; } if ((boundingBox2.intersects(collision_enemy_bullet[i]))) { enemy_bullet[i].enemy_bullet.setPosition(sf::Vector2f(-400, 0)); bgs2.Play(); life--; } if ((boundingBox2.intersects(collision_enemy[i]))) { enemy[i].enemy.setPosition(sf::Vector2f(-400, 0)); bgs2.Play(); life--; } } window.display(); //分数迭代 if (score >= 100 * level) {level++;} if (life <= 0) {window.close();} if (score >= 7500) {window.close();} } }