void handleEvent() { while (window.pollEvent(myEvent)) { switch (myEvent.type) { case Event::Closed: window.close(); break; case Event::KeyPressed: if (myEvent.key.code == sf::Keyboard::Space) { if (isGameStarted == false) { ball.setVelocity( rotate2D(getRandomNumber(), {0,-1}) ); isGameStarted = true; } break; } case Event::MouseButtonPressed: break; case Event::MouseButtonReleased: break; } } }
void ProcessEvents(RenderWindow& window, Game* game) { SnakeParts* snake = game->snake; Event event; while (window.pollEvent(event)) { Keyboard::Key pressed; if (event.type == Event::KeyPressed) { pressed = event.key.code; if ((pressed == Keyboard::W) && snake[0].dir != DOWN) { snake[0].dir = UP; } else if ((pressed == Keyboard::S) && snake[0].dir != UP) { snake[0].dir = DOWN; } else if ((pressed == Keyboard::A) && snake[0].dir != LEFT) { snake[0].dir = RIGHT; } else if ((pressed == Keyboard::D) && snake[0].dir != RIGHT) { snake[0].dir = LEFT; } else if ((pressed == Keyboard::P)) { game->state = PAUSE; } else if ((pressed == Keyboard::U)) { game->state = PLAY; } else if ((pressed == Keyboard::R) && game->state == ENDGAME) { game->state = RESTART; } } if (event.type == Event::Closed || ((event.type == Event::KeyPressed) && (pressed == Keyboard::Escape) && game->state == ENDGAME)) window.close(); } }
void run_animation(RenderWindow &window) { Clock clock; std::vector<initialization_blocks*> object; float x = RECTANGLES_SIZE.x / 2, y = 0; int number_block; for (int i = 0; i < NUMBER_BLOCKS; i++) { y += 10 + RECTANGLES_SIZE.y; object.push_back(new initialization_blocks(x, y, i)); } while (window.isOpen()) { Event event; while (window.pollEvent(event)) if (event.type == Event::Closed) window.close(); float time = clock.getElapsedTime().asMicroseconds(); clock.restart(); time = time / 800; window.clear(Color::White); number_block = 0; for (auto i : object) { i->update(time, number_block); window.draw(i->rectangle); number_block++; } window.display(); } }
void ProcessEvents(RenderWindow& window) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } }
void CheckWindowClose(RenderWindow & window) { Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) { window.close(); } } }
void processEvents() { Event event; while (window.pollEvent(event)) { if ( (event.type == Event::Closed) || ((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Escape))) window.close(); else if (event.type == Event::KeyPressed) { if (gameState == INTRO) gameState = PLAYING; } } }
void processEvents(RenderWindow & window, Racket & racket, Racket & racket2, GameState & gameState) { Event event; while (window.pollEvent(event)) { // Проверяем нажатую кнопку if (Keyboard::isKeyPressed(Keyboard::W)) { racket.direction = W; } else if (Keyboard::isKeyPressed(Keyboard::S)) { racket.direction = S; } else { racket.direction = NONE; } if (Keyboard::isKeyPressed(Keyboard::Up)) { racket2.direction = UP; } else if (Keyboard::isKeyPressed(Keyboard::Down)) { racket2.direction = DOWN; } else { racket2.direction = NONE; } if (event.type == Event::KeyPressed && event.key.code == Keyboard::Return) // Возвращение в главное меню { gameState.isPlay = false; } if (event.type == Event::KeyPressed && event.key.code == Keyboard::P) // Поставить на паузу или снять с паузы игру { if (!gameState.isPayse) { gameState.isPayse = true; } else { gameState.isPayse = false; } } // Окно закрыли if ((event.type == Event::Closed) || (event.type == Event::KeyPressed && event.key.code == Keyboard::Escape)) { window.close(); } } }
void RunProgram(RenderWindow& window) { RectangleStruct rect[QUANTITY] = {}; SecreteStruct secret; StageStruct stage; InitializationSqure(rect); Clock clock; Clock change_clock; srand(time(NULL)); InitializationStage(stage); int secret_stage = 1; int i_color = 0; int num_turns = 0; float i_size = 1; Vector2f speed_move; speed_move.x = SPEED; speed_move.y = SPEED; InitializationSecret(secret); change_clock.restart(); while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); float time_for_change = change_clock.getElapsedTime().asSeconds(); clock.restart(); time = time / 1000; sf::Event event; if (time_for_change >= TIME) { change_clock.restart(); SecretChange(secret); } while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } StageSelect(stage, i_color, i_size, rect); SceneChange(stage, i_color, i_size, speed_move, time); if (secret.rotation == 1) Rotation(rect, time); if (secret.color == 1) ChangeColor(rect, i_color, time); if (secret.size == 1) ChangeSize(rect, i_size, time); if (secret.move == 1) Move(rect, speed_move); Draw(window, rect); } }
int main(int, char const**) { // Create the main window RenderWindow window; window.create(VideoMode(800, 600), "Pong"); //Create and initialize the actual game screen GameScreen gamescreen = GameScreen(); gamescreen.initialize(); // Start the game loop while (window.isOpen()) { // Process events Event p1; while (window.pollEvent(p1)) { // Close window: exit if (p1.type == Event::Closed) { window.close(); } } // Clear screen window.clear(); /* Here I am trying to use that standard game loop with initialize, update, and draw. If I ever try to make a real game in C++ I know that I will need to know how to use these methods and create objects outside of this class. */ gamescreen.update(); //Draw each entity (sprite) for(Sprite ent : gamescreen.entities) { window.draw(ent); } // Update the window window.display(); } return EXIT_SUCCESS; }
void Game::doUpdate(RenderWindow &window) { Event event; while(window.pollEvent(event)) { switch(event.type) { case Event::Closed: window.close(); break; case Event::KeyPressed: switch(event.key.code) { case Keyboard::Escape: window.close(); break; case Keyboard::Left: if(player.x > 0 && gameGrid->blocks[player.x - 1][player.y] == 0) --player.x; break; case Keyboard::Right: if(player.x < gameGrid->width - 1 && gameGrid->blocks[player.x + 1][player.y] == 0) ++player.x; break; case Keyboard::Up: if(player.y > 0 && gameGrid->blocks[player.x][player.y - 1] == 0) --player.y; break; case Keyboard::Down: if(player.y < gameGrid->height - 1 && gameGrid->blocks[player.x][player.y + 1] == 0) ++player.y; break; } break; case Event::MouseButtonPressed: switch(event.mouseButton.button) { case Mouse::Left: path = pathfinder.findPath(player, Vector2i(event.mouseButton.x / 16, event.mouseButton.y / 16), gameGrid->blocks, gameGrid->width, gameGrid->height); break; } } } }
int main() { //Synchonisation coordonnée à l'écran! mainWin.setVerticalSyncEnabled(true); Menu mainMenu; mainMenu.draw(mainWin); while (mainWin.isOpen()) { Event event; while (mainWin.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: mainWin.close(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Down) { mainMenu.MoveCursor("Down", mainWin); } else if (event.key.code == sf::Keyboard::Up) { mainMenu.MoveCursor("Up", mainWin); } else if (event.key.code == sf::Keyboard::Space) { mainMenu.SelectItem(mainWin); } break; } } } return EXIT_SUCCESS; }
int main() { Button start_button(MediaBucket.getTexture("Start1"), sf::Vector2f(WINDOW_RESOLUTION.x/2, WINDOW_RESOLUTION.y/2)); start_button.addSprite(MediaBucket.getTexture("Start2")); start_button.addSprite(MediaBucket.getTexture("Start3")); start_button.setPosition(sf::Vector2f(WINDOW_RESOLUTION.x/2, WINDOW_RESOLUTION.y/2), -1); Sprite firecan_icon; firecan_icon.setTexture(MediaBucket.getTexture("firecan_icon")); FloatRect firecan_icon_size = firecan_icon.getLocalBounds(); firecan_icon.setOrigin(firecan_icon_size.width/2, firecan_icon_size.height/2); firecan_icon.setPosition(Vector2f(firecan_icon_size.width/2, WINDOW_RESOLUTION.y-firecan_icon_size.height/2)); intro(); while(app.isOpen()) { while(app.pollEvent(event)) { if(event.type == Event::KeyPressed) { if(event.key.code == Keyboard::Escape) { app.close(); } } if(event.type == Event::Closed) { app.close(); } if(event.type == Event::MouseButtonPressed && start_button.isClicked()) { } } app.clear(Color::White); app.draw(start_button); app.draw(firecan_icon); app.display(); } }
void whenGameIsOver() { if (ball.min.x <= 0 || ball.min.y <= 0 || ball.max.x >= 1024 || ball.max.y >= 800) { char text[60]; sprintf_s(text,"You have ended the game with score : %i",score); MessageBox(NULL,text , NULL, NULL); string name; name=fetchNameFromUser(); HighScore::updateHighScore(score,name); getchar(); window.close(); } }
int main() { //{ -1,0 }left GlobalNormal //{1,0}right GlobalNormal //{0,1}down GlobalNormal //{0,-1}up GlobalNormal //position x, position y, width, height, Color ,faceNormal ,backNormal ,leftNormal , rightNormal platform[0] = { 512 - 40 , 750 - 8 , 150, 20,Color::White ,{0,-1 } ,{0 ,1 } ,{-1,0 } ,{ 1,0 } }; //kinda tryhard ;p but it works, so its not stupid platform[1] = { 20, 380, 20, 150, Color::White ,{ 1,0 } ,{-1,0 } ,{ 0,-1} ,{ 0,1 } }; platform[2] = { 512 - 40, 42, 150, 20, Color::White ,{ 0,1 } ,{ 0,1 } ,{ 1,0 } ,{-1,0 } }; platform[3] = { 984, 380, 20, 150, Color::White ,{-1,0 } ,{ 1,0 } ,{ 0,1 } ,{ 0,-1} }; position.x = ball.position.x; position.y = ball.position.y; if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf")) { MessageBox(NULL,"ERROR:Couldn't load font",NULL,NULL); window.close(); } setText(scoreText, font, Color::Red, 24, "Score: 0", {0,0}); setText(initialText, font, Color::White, 20, "Press space to start", { 420,320 }); //game loop clock_t previous = clock(); clock_t lag = 0; while (window.isOpen()) { clock_t current = clock(); clock_t elapsed = current-previous; lag += elapsed; previous = current; handleEvent(); while (lag > 16) { update(); lag -=16; } render(); } return 0; }
void events(RenderWindow &window, globalBool *id) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (Keyboard::isKeyPressed(Keyboard::RAlt)) { if (!id->g_isPause) { id->g_isPause = true; } else if (id->g_isPause) { id->g_isPause = false; } } if (Keyboard::isKeyPressed(Keyboard::Escape)) { id->g_isMenu = true; } } }
int main(int argc, char** argv) { globalvariables->running = true; window.create(VideoMode(800,600),"Quadcopter Project"); window.setVerticalSyncEnabled(true); //thread CaptureThread(Capture); LoadingRender loadingrender(globalvariables); loadingrender.Load(); globalvariables->currentrenderer = &loadingrender; Clock fps; while (globalvariables->running) { globalvariables->currentrenderer->Tick(window); } delete globalvariables; window.close(); exit(EXIT_SUCCESS); }
int main() { Sky sky; load_all_sound(); bgm.play(); Player player; while (window.isOpen()) { window.clear(); sky.drawsky(); Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Up) player.moveup(); if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Down) player.movedown(); if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Left) player.moveleft(); if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Right) player.moveright(); if(event.type==Event::KeyPressed&& event.key.code == Keyboard::Space) player.gun(); } player.bullet_refresh(); window.display(); } return 0; }
void menu(RenderWindow & window, Music &musicInMenu) { init_texture textu; bool kek = false; musicInMenu.play(); bool isMenu = 1; int menuNum = 0; while (isMenu) { textu.menu1.setColor(Color::White); textu.menu2.setColor(Color::White); textu.menu3.setColor(Color::White); menuNum = 0; window.clear(Color(129, 181, 221)); if (IntRect(100, 30, 300, 50).contains(Mouse::getPosition(window))) { textu.menu1.setColor(Color::Blue); menuNum = 1; } if (IntRect(100, 90, 300, 50).contains(Mouse::getPosition(window))) { textu.menu3.setColor(Color::Blue); menuNum = 3; } if (IntRect(100, 150, 300, 50).contains(Mouse::getPosition(window))) { textu.menu2.setColor(Color::Blue); menuNum = 2; } window.draw(textu.menuBg); window.draw(textu.menu1); window.draw(textu.menu2); window.draw(textu.menu3); if (kek) { window.draw(textu.training); if (IntRect(1200, 90, 50, 50).contains(Mouse::getPosition(window)) && Mouse::isButtonPressed(Mouse::Left)) { kek = false; } } if (Mouse::isButtonPressed(Mouse::Left)) { if (menuNum == 1) isMenu = false; if (menuNum == 2) { window.close(); isMenu = false; } if (menuNum == 3) { kek = true; } } window.display(); } }
int main(int argc, char* argv[]) { Config config; Game game; game.configure(config); game.start(); RenderWindow* window = GameWindow::instance().getWindow(); while (window->isOpen()) { Event Event; while (window->pollEvent(Event)) { if (Event.type == Event::Closed) window->close(); } window->clear(Color::Black); game.tick(); game.render(); window->display(); } }
int menu_proc(RenderWindow & win){ int status[3] = {CHOSE_PERSON, LOAD_SAVE_GAME, EXIT}; Texture t_fon; t_fon.loadFromFile("Labelmenu1.png"); Sprite s_fon; s_fon.setTexture(t_fon); Font font; font.loadFromFile("GoodDog.otf"); //Text text("text", font); char text[3][15] = {"New Game", "Load Game", "Exit"}; Text t[3]; Color pink(254, 137, 245); Color yellow(255, 214, 136); for(int i = 0; i < 3; i++){ t[i].setString(text[i]); t[i].setFont(font); t[i].setCharacterSize(100); t[i].setPosition(190, i*90+160); t[i].setColor(pink); } int cur = 0; t[cur].setColor(yellow); bool IsKeyPressedOneTime = false; while (win.isOpen()){ Event event; while (win.pollEvent(event)){ if (event.type == sf::Event::Closed || Keyboard::isKeyPressed(Keyboard::Escape)){ win.close(); } } if(Keyboard::isKeyPressed(Keyboard::Down) && !IsKeyPressedOneTime){ IsKeyPressedOneTime = true; t[cur].setColor(pink); if(cur < 2) cur++; t[cur].setColor(yellow); } else if(Keyboard::isKeyPressed(Keyboard::Up) && !IsKeyPressedOneTime){ IsKeyPressedOneTime = true; t[cur].setColor(pink); if(cur > 0) cur--; t[cur].setColor(yellow); } else if(Keyboard::isKeyPressed(Keyboard::Return)){ break; } win.clear(); win.draw(s_fon); for(int i = 0; i < 3; i++) win.draw(t[i]); win.display(); Sleep(100); IsKeyPressedOneTime = false; } return status[cur]; }
void GameProcess(RenderWindow & window, Font & font, bool &isWin, bool &isLose) { Clock clock; Board board; Ball ball; list<Brick*> bricks; iniGameObj(board, ball, bricks, WINDOW_SIZE); Event event; bool isPause = false; while (window.isOpen() && (!isWin) && (!isLose)) { float time = float(clock.restart().asMicroseconds()); time = time / COEF_SPEED_GAME; if (isPause) { time = 0; isPause = false; } while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (Keyboard::isKeyPressed(Keyboard::Left)) { board.dir = LEFT; } else if (Keyboard::isKeyPressed(Keyboard::Right)) { board.dir = RIGHT; } else { board.dir = NONE; } if (Keyboard::isKeyPressed(Keyboard::Space)) { ball.inBoard = false; } if (Keyboard::isKeyPressed(Keyboard::Escape)) { window.close(); } if (Keyboard::isKeyPressed(Keyboard::P)) { isPause = true; } } if (window.isOpen()) { if (isPause) { PauseMenu(window, font); } else { update(board, time, WINDOW_SIZE); if (ball.inBoard) { MoveBallInBoard(ball, board, time); } else { CollisionAndMove(ball, bricks, board, time, WINDOW_SIZE); }; UpdateList(bricks); window.clear(); window.draw(*(board.sprite)); window.draw(*(ball.sprite)); RenderList(bricks, window); window.display(); if (bricks.size() == 0) { isWin = true; } if (ball.sprite->getPosition().y + ball.sprite->getRadius() >= WINDOW_SIZE.y) { isLose = true; } } } } DispolseGameObj(&board, &ball, bricks); }
int ride( RenderWindow &window) { //RenderWindow window(sf::VideoMode(640, 480), "Lesson 7. kychka-pc.ru"); Image image; image.loadFromFile("machine.png"); image.createMaskFromColor(Color (255, 255, 255)); image.createMaskFromColor(Color (253, 253, 253)); image.createMaskFromColor(Color (254, 254, 254)); Texture herotexture; herotexture.loadFromImage(image); Sprite herosprite, tmpherosprite; herosprite.setTexture(herotexture); herosprite.setTextureRect(IntRect(0, 0, 135, 72)); herosprite.setPosition(250, 250); tmpherosprite = herosprite; float CurrentFrame = 0;//хранит текущий кадр Clock clock; float angle = 0; Vector2f vert; Vector2f pos; vert.x = 1; vert.y = 0; while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); clock.restart(); time = time / 800; sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if ((Keyboard::isKeyPressed(Keyboard::Up) || (Keyboard::isKeyPressed(Keyboard::W)))) { CurrentFrame += 0.005*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации //if (CurrentFrame > 3) CurrentFrame -= 3; //проходимся по кадрам с первого по третий включительно. если пришли к третьему кадру - откидываемся назад. // herosprite.setTextureRect(IntRect(96 * int(CurrentFrame), 0, 96, 96)); //проходимся по координатам Х. получается 96,96*2,96*3 и опять 96 herosprite.move(0.1 * time * vert.x, 0.1 * time * vert.y);//происходит само движение персонажа вниз } if ((Keyboard::isKeyPressed(Keyboard::Down) || (Keyboard::isKeyPressed(Keyboard::S)))) { CurrentFrame += 0.005*time; //служит для прохождения по "кадрам". переменная доходит до трех суммируя произведение времени и скорости. изменив 0.005 можно изменить скорость анимации //if (CurrentFrame > 3) CurrentFrame -= 3; //проходимся по кадрам с первого по третий включительно. если пришли к третьему кадру - откидываемся назад. // herosprite.setTextureRect(IntRect(96 * int(CurrentFrame), 0, 96, 96)); //проходимся по координатам Х. получается 96,96*2,96*3 и опять 96 herosprite.move(-0.1 * time * vert.x, -0.1 * time * vert.y);//происходит само движение персонажа вниз } if ((Keyboard::isKeyPressed(Keyboard::Right) || (Keyboard::isKeyPressed(Keyboard::D)))) { angle += float(time)/1000; vert.x = cos(angle); vert.y = sin(angle); } if ((Keyboard::isKeyPressed(Keyboard::Left) || (Keyboard::isKeyPressed(Keyboard::A)))) { angle -= float(time)/1000; vert.x = cos(angle); vert.y = sin(angle); } if(Keyboard::isKeyPressed(Keyboard::Escape)) break; pos = herosprite.getPosition(); tmpherosprite.setPosition(int(-vert.x * 67.5 + 36 * vert.y + pos.x), int(-vert.y * 67.5 - 36 * vert.x + pos.y)); tmpherosprite.setRotation(angle * 180 / 3.14); window.clear(Color(255, 255, 255)); window.draw(tmpherosprite); window.display(); } }
void endGameScreen(RenderWindow& window, string winner) { Sprite background; Rectangle button(236, 566, 389, 451); Event event; if (winner == "human") { background.setTexture(humanWon); window.draw(background); window.display(); while (true) { window.pollEvent(event); if (hovering(window, button, event)) { background.setTexture(humanWonButtonHighlighted); window.draw(background); window.display(); } else { background.setTexture(humanWon); window.draw(background); window.display(); } if (event.type == Event::Closed) { window.close(); return; } if (wasClicked(window, button, event)) return; } } else { background.setTexture(compWon); window.draw(background); window.display(); while (true) { window.pollEvent(event); if (hovering(window, button, event)) { background.setTexture(compWonButtonHighlighted); window.draw(background); window.display(); } else { background.setTexture(compWon); window.draw(background); window.display(); } if (event.type == Event::Closed) { window.close(); return; } if (wasClicked(window, button, event)) return; } } }
int playerAbilitySelect(RenderWindow& window, Player& human, Player& computer) { // set up UI components Sprite abilities; Sprite yourTurn; yourTurn.setTexture(yourTurnTexture); abilities.setTexture(abilitiesNothingHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); window.draw(yourTurn); window.display(); Rectangle ability1(7, 60, 681, 735); Rectangle ability2(64, 117, 681, 735); Rectangle ability3(121, 174, 681, 735); Rectangle ability4(7, 60, 739, 793); Rectangle ability5(64, 117, 739, 793); Rectangle ability6(121, 174, 739, 793); // decide what abilities are currently available stunRandomAbilities(human); bool availability[6]; for (int i = 0; i < 6; i++) { availability[i] = !human.abilities[i].stunned && human.abilities[i].turnsUntilAvailable == 0 && human.abilities[i].resourcesConsumed <= human.currentResources; } if (!availability[0] && !availability[1] && !availability[2] && !availability[3] && !availability[4] && !availability[5]) { for (int i = 0; i < 6; i++) { if (human.abilities[i].resourcesCreated > 0) { availability[i] = true; } } } // user chooses an ability Event event; while (true) { window.pollEvent(event); if (hovering(window, ability1, event)) { abilities.setTexture(abilitiesOneHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); drawAbilityInfo(window, human, 0, availability[0]); window.draw(yourTurn); window.display(); } else if (hovering(window, ability2, event)) { abilities.setTexture(abilitiesTwoHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); drawAbilityInfo(window, human, 1, availability[1]); window.draw(yourTurn); window.display(); } else if (hovering(window, ability3, event)) { abilities.setTexture(abilitiesThreeHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); drawAbilityInfo(window, human, 2, availability[2]); window.draw(yourTurn); window.display(); } else if (hovering(window, ability4, event)) { abilities.setTexture(abilitiesFourHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); drawAbilityInfo(window, human, 3, availability[3]); window.draw(yourTurn); window.display(); } else if (hovering(window, ability5, event)) { abilities.setTexture(abilitiesFiveHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); drawAbilityInfo(window, human, 4, availability[4]); window.draw(yourTurn); window.display(); } else if (hovering(window, ability6, event)) { abilities.setTexture(abilitiesSixHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); drawAbilityInfo(window, human, 5, availability[5]); window.draw(yourTurn); window.display(); } else { abilities.setTexture(abilitiesNothingHighlighted); drawGameWindow(window, human, computer); window.draw(abilities); window.draw(yourTurn); window.display(); } if (availability[0] && wasClicked(window, ability1, event)) { undoStuns(human); return 0; } if (availability[1] && wasClicked(window, ability2, event)) { undoStuns(human); return 1; } if (availability[2] && wasClicked(window, ability3, event)) { undoStuns(human); return 2; } if (availability[3] && wasClicked(window, ability4, event)) { undoStuns(human); return 3; } if (availability[4] && wasClicked(window, ability5, event)) { undoStuns(human); return 4; } if (availability[5] && wasClicked(window, ability6, event)) { undoStuns(human); return 5; } if (event.type == Event::Closed) { window.close(); undoStuns(human); return 0; } } }
string shipSelection(RenderWindow& window) { // load ship data ifstream fin; fin.open("data\\ships.txt"); if (!fin) { cout << "\"ships.txt\" could not be opened.\n"; window.close(); return "Cargo Ship"; } string temp; string shipDescription[NUM_SHIPS]; for (int i = 0; i < NUM_SHIPS; i++) { fin.clear(); fin.seekg(0, ios::beg); while (true) { getline(fin, temp); if (temp == SHIPS[i]) { getline(fin, shipDescription[i]); textWrap(shipDescription[i], 35); break; } } } // set up UI elements Rectangle cargo(18, 222, 234, 269); Rectangle stealth(18, 222, 282, 317); Rectangle scout(18, 222, 330, 365); Rectangle repair(18, 222, 370, 413); Rectangle destroyer(18, 222, 426, 461); Rectangle science(18, 222, 474, 509); Rectangle station(18, 222, 522, 557); Rectangle pod(18, 222, 570, 605); Sprite background; background.setTexture(shipsNothingHighlighted); window.draw(background); window.display(); // player choses a ship Event event; while (true) { window.pollEvent(event); if (event.type == Event::Closed) { window.close(); return "Cargo Ship"; } if (hovering(window, cargo, event)) { background.setTexture(shipsCargoHighlighted); window.draw(background); drawShipInfo(window, 0, shipDescription[0]); window.display(); } else if (hovering(window, stealth, event)) { background.setTexture(shipsStealthHighlighted); window.draw(background); drawShipInfo(window, 1, shipDescription[1]); window.display(); } else if (hovering(window, scout, event)) { background.setTexture(shipsScoutHighlighted); window.draw(background); drawShipInfo(window, 2, shipDescription[2]); window.display(); } else if (hovering(window, repair, event)) { background.setTexture(shipsRepairHighlighted); window.draw(background); drawShipInfo(window, 3, shipDescription[3]); window.display(); } else if (hovering(window, destroyer, event)) { background.setTexture(shipsDestroyerHighlighted); window.draw(background); drawShipInfo(window, 4, shipDescription[4]); window.display(); } else if (hovering(window, science, event)) { background.setTexture(shipsScienceHighlighted); window.draw(background); drawShipInfo(window, 5, shipDescription[5]); window.display(); } else if (hovering(window, station, event)) { background.setTexture(shipsStationHighlighted); window.draw(background); drawShipInfo(window, 6, shipDescription[6]); window.display(); } else if (hovering(window, pod, event)) { background.setTexture(shipsPodHighlighted); window.draw(background); drawShipInfo(window, 7, shipDescription[7]); window.display(); } else { background.setTexture(shipsNothingHighlighted); window.draw(background); window.display(); } if (wasClicked(window, cargo, event)) return "Cargo Ship"; if (wasClicked(window, stealth, event)) return "Stealth Fighter"; if (wasClicked(window, scout, event)) return "Patrol Scout"; if (wasClicked(window, repair, event)) return "Repair Ship"; if (wasClicked(window, destroyer, event)) return "Destroyer"; if (wasClicked(window, science, event)) return "Science Vessel"; if (wasClicked(window, station, event)) return "Space Station"; if (wasClicked(window, pod, event)) return "Escape Pod"; } return "Cargo Ship"; }
int main(int, char const**){ // Create the main window RenderWindow window(VideoMode(800, 600), "SFML window"); window.setFramerateLimit(60); Font font; if (!font.loadFromFile("Resources/sansation.ttf")) { return EXIT_FAILURE; } Text text(std::to_string(fps), font, 50); text.setColor(Color::White); text.setPosition(0,600-text.getGlobalBounds().height*2); tileTexture.loadFromFile("Resources/mapTileSpritesheet.png"); guyTexture.loadFromFile("Resources/sprite1.png"); // guyTexture.loadFromFile("Resources/guy.png"); wallTexture.loadFromFile("Resources/64x64/b0.png"); chestTexture.loadFromFile("Resources/chest.png"); // std::cout << sizeof(tileTexture) << std::endl; dirtRect.left = 0; dirtRect.top = 0; dirtRect.width = 32; dirtRect.height = 32; Sprite dirt(tileTexture, dirtRect); grassRect.left = 32; grassRect.top = 0; grassRect.width = 32; grassRect.height = 32; Sprite grass(tileTexture, grassRect); wallRect.left = 0; wallRect.top = 0; wallRect.width = 32; wallRect.height = 32; Sprite wall(wallTexture,wallRect); Sprite closedChest(chestTexture,IntRect(0,0,16,16)); closedChest.setScale(2,2); Sprite openChest(chestTexture,IntRect(17,0,16,16)); openChest.setScale(2,2); // guyRect.left = 0; // guyRect.top = 128; // guyRect.width = 64; // guyRect.height = 64; guyRect.left = 0; guyRect.top = 32; guyRect.width = 24; guyRect.height = 24; Sprite guy(guyTexture, guyRect); // guy.setOrigin(guy.getLocalBounds().width/2, guy.getLocalBounds().height/2); // guy.setScale(32/24.0,32/24.0); guy.setPosition(windowWidth/2,windowHeight/2); RectangleShape guyHitBox(Vector2f(guy.getLocalBounds().width, guy.getLocalBounds().height)); // guyHitBox.setOrigin(guyHitBox.getLocalBounds().width/2, guyHitBox.getLocalBounds().height/2); // guyHitBox.setScale(32/24.0,32/24.0); guyHitBox.setPosition(guy.getPosition()); RectangleShape centerScreen(Vector2f(10,10)); centerScreen.setPosition(windowWidth/2-5,windowHeight/2-5); centerScreen.setFillColor(Color(255,0,0)); // std::cout << sizeof(dirt) << std::endl; // std::cout << sizeof(grass) << std::endl; tiles = new Tile[numTiles]; for (int i = 0; i < numTiles; i++){ if(i/columns == 0 || i / columns == rows-1 || i%columns == 0 || i%columns == columns-1){ tiles[i].setVal(i/columns,i%columns,WALL,false); } else{ tiles[i].setVal(i/columns,i%columns,GRASS,true); } } tiles[getTileIndex(5,5)].type = WALL; tiles[getTileIndex(5,5)].walkable = false; tiles[getTileIndex(6,5)].type = WALL; tiles[getTileIndex(6,5)].walkable = false; tiles[getTileIndex(7,5)].type = WALL; tiles[getTileIndex(7,5)].walkable = false; tiles[getTileIndex(8,5)].type = WALL; tiles[getTileIndex(8,5)].walkable = false; tiles[getTileIndex(5,18)].type = GRASS; tiles[getTileIndex(5,18)].walkable = false; tiles[getTileIndex(5,18)].chest = true; // tiles[getTileIndex(5,18)].chestOpen = true; // std::cout << sizeof(tiles[1]) << std::endl; // tiles[getTileIndex(2, 1)].setColor(Color::White); while (window.isOpen()){ Event event; while (window.pollEvent(event)){ // Close window: exit if (event.type == Event::Closed) { window.close(); } // Escape pressed: exit if (event.type == Event::KeyPressed) { if(event.key.code == Keyboard::Escape){ window.close(); } if(event.key.code == Keyboard::E){ tileAction(guy); } } if (event.type == Event::MouseButtonPressed) { if (event.mouseButton.button == Mouse::Left) { int index = mouseToTile(event.mouseButton.x,event.mouseButton.y); if (index >= 0) { if(tiles[index].chest){ tiles[index].toggleState(); } } } } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)){ facing = UP; guy.move(0,-movementSpeed); guyPos = guy.getPosition(); FloatRect guyBox = guy.getLocalBounds(); tempIndex = mouseToTile(guyPos.x+guyBox.width/2,guyPos.y); Tile tempTile = tiles[tempIndex]; int tempRow = tempTile.row; int tempCol = tempTile.col; for(int i = tempCol-2; i < tempCol+2; i++){ // tiles[getTileIndex(tempRow,i)].type = DIRT; tempTile = tiles[getTileIndex(tempRow,i)]; if(!tempTile.walkable){ int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2); int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2); int z3 = tempTile.width/2 + guyBox.width/2; int z4 = tempTile.height/2 + guyBox.height/2; if(std::abs(z1) < z3 && std::abs(z2) < z4){ // printf("top\n"); guyPos = Vector2f(guyPos.x, tempTile.y + tempTile.height+spacing); guy.setPosition(guyPos); } } } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)){ facing = DOWN; guy.move(0,movementSpeed); guyPos = guy.getPosition(); FloatRect guyBox = guy.getLocalBounds(); tempIndex = mouseToTile(guyPos.x+guyBox.width/2,guyPos.y+guyBox.height); Tile tempTile = tiles[tempIndex]; int tempRow = tempTile.row; int tempCol = tempTile.col; for(int i = tempCol-2; i < tempCol+2; i++){ // tiles[getTileIndex(tempRow,i)].type = DIRT; tempTile = tiles[getTileIndex(tempRow,i)]; if(!tempTile.walkable){ int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2); int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2); int z3 = tempTile.width/2 + guyBox.width/2; int z4 = tempTile.height/2 + guyBox.height/2; if(std::abs(z1) < z3 && std::abs(z2) < z4){ // printf("bottom\n"); guyPos = Vector2f(guyPos.x, tempTile.y - guyBox.height - spacing); guy.setPosition(guyPos); } } } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){ facing = LEFT; guy.move(-movementSpeed,0); guyPos = guy.getPosition(); FloatRect guyBox = guy.getLocalBounds(); tempIndex = mouseToTile(guyPos.x,guyPos.y+guyBox.height/2); Tile tempTile = tiles[tempIndex]; int tempRow = tempTile.row; int tempCol = tempTile.col; for(int i = tempRow-2; i < tempRow+2; i++){ tempTile = tiles[getTileIndex(i,tempCol)]; // tiles[getTileIndex(i,tempCol)].type = DIRT; if(!tempTile.walkable){ int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2); int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2); int z3 = tempTile.width/2 + guyBox.width/2; int z4 = tempTile.height/2 + guyBox.height/2; if(std::abs(z1) < z3 && std::abs(z2) < z4){ // printf("left\n"); guyPos = Vector2f(tempTile.x + tempTile.width+spacing,guyPos.y); guy.setPosition(guyPos); } } } } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)){ facing = RIGHT; guy.move(movementSpeed,0); guyPos = guy.getPosition(); FloatRect guyBox = guy.getLocalBounds(); tempIndex = mouseToTile(guyPos.x+guyBox.width,guyPos.y+guyBox.height/2); Tile tempTile = tiles[tempIndex]; int tempRow = tempTile.row; int tempCol = tempTile.col; for(int i = tempRow-2; i < tempRow+2; i++){ // tiles[getTileIndex(i,tempCol)].type = DIRT; tempTile = tiles[getTileIndex(i,tempCol)]; if(!tempTile.walkable){ int z1 = (tempTile.x +tempTile.width/2) - (guyPos.x + guyBox.width/2); int z2 = (tempTile.y +tempTile.height/2) - (guyPos.y + guyBox.height/2); int z3 = tempTile.width/2 + guyBox.width/2; int z4 = tempTile.height/2 + guyBox.height/2; if(std::abs(z1) < z3 && std::abs(z2) < z4){ // printf("right\n"); guyPos = Vector2f(tempTile.x - guyBox.width - spacing,guyPos.y); guy.setPosition(guyPos); } } } } guyHitBox.setPosition(guy.getPosition()); calculateFPS(); text.setString(std::to_string(fps)); closedChest.setPosition(-100,-100); openChest.setPosition(-100,-100); window.clear(Color(0,0,0)); for (int i = 0; i < numTiles; i++){ switch (tiles[i].type){ case DIRT: dirt.setPosition(tiles[i].x,tiles[i].y); window.draw(dirt); break; case GRASS: grass.setPosition(tiles[i].x,tiles[i].y); window.draw(grass); break; case WALL: wall.setPosition(tiles[i].x,tiles[i].y); window.draw(wall); break; } if(tiles[i].chest){ if(tiles[i].chestOpen){ openChest.setPosition(tiles[i].x,tiles[i].y); window.draw(openChest); } else{ closedChest.setPosition(tiles[i].x,tiles[i].y); window.draw(closedChest); } } } window.draw(guyHitBox); window.draw(guy); // window.draw(openChest); window.draw(text); //FPS // window.draw(centerScreen); // window.draw(dirt); window.display(); } return EXIT_SUCCESS; }
void Menu::menu(RenderWindow & app, int width, int height) { bool musicIsPlaying = true; Music music; music.openFromFile("sounds/menuMusic.ogg"); music.setLoop(true); Texture menuTexture1, menuTexture2, menuTexture3, aboutTexture, menuBackground; menuTexture1.loadFromFile("images/StartGame.png"); menuTexture2.loadFromFile("images/LeaderBoard.png"); menuTexture3.loadFromFile("images/exit.png"); menuBackground.loadFromFile("images/menu.png"); Sprite menu1(menuTexture1), menu2(menuTexture2), menu3(menuTexture3), menuBg(menuBackground); bool isMenu = 1; int menuNum = 0; menu1.setPosition(400, 300); menu2.setPosition(400, 375); menu3.setPosition(400, 450); menuBg.setPosition(0, 0); while (isMenu) { if (musicIsPlaying) { music.play(); musicIsPlaying = false; } menu1.setColor(Color::White); menu2.setColor(Color::White); menu3.setColor(Color::White); menuNum = 0; app.clear(Color(129, 181, 221)); if (IntRect(400, 300, 300, 50).contains(Mouse::getPosition(app))) { menu1.setColor(Color::Blue); menuNum = 1; } if (IntRect(400, 375, 300, 50).contains(Mouse::getPosition(app))) { menu2.setColor(Color::Blue); menuNum = 2; } if (IntRect(400, 450, 300, 50).contains(Mouse::getPosition(app))) { menu3.setColor(Color::Blue); menuNum = 3; } if (Mouse::isButtonPressed(Mouse::Left)) { if (menuNum == 1) { music.stop(); const char * filename = "score.txt"; isMenu = false; Game * game = new Game(width, height); int score = game->run(app); int prevScore; ifstream scoreFile; scoreFile.open(filename); scoreFile >> prevScore; scoreFile.close(); if (score > prevScore) { ofstream scoreFile; scoreFile.open(filename); scoreFile << score; scoreFile.close(); } isMenu = true; } //if (menuNum == 2) { window.draw(about); window.display(); while (!Keyboard::isKeyPressed(Keyboard::Escape)); } if (menuNum == 3) { app.close(); isMenu = false; } musicIsPlaying = true; } app.draw(menuBg); app.draw(menu1); app.draw(menu2); app.draw(menu3); printTopScore(app); app.display(); }
void infoScreen(RenderWindow& window) { Sprite background; Rectangle menuButton(684, 788, 746, 788); background.setTexture(infoNothingHighlighted); // load info text vector<string> paragraphs; ifstream fin; fin.open("data\\info.txt"); if (!fin) { cout << "\"info.txt\" could not be opened!\n"; window.close(); return; } while (fin) { string temp; getline(fin, temp); if (!temp.empty()) paragraphs.push_back(temp); } for (int i = 0; i < paragraphs.size(); i++) { textWrap(paragraphs[i], 70); } vector<Text> messages(paragraphs.size()); vector<RectangleShape> recs(paragraphs.size()); for (int i = 0; i < paragraphs.size(); i++) { messages[i].setString(paragraphs[i]); messages[i].setColor(Color(218, 255, 180)); messages[i].setCharacterSize(17); messages[i].setFont(infoFont); recs[i].setSize(Vector2f(messages[i].getLocalBounds().width + 23, messages[i].getLocalBounds().height + 30)); recs[i].setFillColor(Color(0, 17, 16, 170)); recs[i].setOutlineColor(Color(0, 255, 180)); recs[i].setOutlineThickness(1); } // position and draw text boxes messages[0].setPosition(Vector2f(int(400 - messages[0].getLocalBounds().width / 2), 230)); recs[0].setPosition(Vector2f(messages[0].getPosition().x - 10, messages[0].getPosition().y - 10)); for (int i = 1; i < messages.size(); i++) { messages[i].setPosition(Vector2f(int(400 - messages[i].getLocalBounds().width / 2), messages[i-1].getPosition().y + messages[i-1].getLocalBounds().height + 10 + 50)); recs[i].setPosition(Vector2f(messages[i].getPosition().x - 10, messages[i].getPosition().y - 10)); } for (int i = 0; i < messages.size(); i++) { window.draw(recs[i]); window.draw(messages[i]); } // event loop window.draw(background); window.display(); Event event; while (true) { window.pollEvent(event); if (hovering(window, menuButton, event)) { background.setTexture(infoMenuHighlighted); window.draw(background); for (int i = 0; i < messages.size(); i++) { window.draw(recs[i]); window.draw(messages[i]); } window.display(); } else { background.setTexture(infoNothingHighlighted); window.draw(background); for (int i = 0; i < messages.size(); i++) { window.draw(recs[i]); window.draw(messages[i]); } window.display(); } if (event.type == Event::Closed) { window.close(); return; } if (wasClicked(window, menuButton, event)) { return; } } }
void menu(RenderWindow &window) { Texture menuText1, menuText2, menuText3, menuBackground; menuBackground.loadFromFile("images/menu1.jpg"); menuText2.loadFromFile("images/cat.jpg"); Sprite menuLoad(menuText2); Sprite menuBg(menuBackground); bool isMenu = 1; int menuNum = 0; menuBg.setPosition(0,0); Music music; music.openFromFile("music/menu.ogg"); music.play(); Font font; font.loadFromFile("dumb.ttf"); Text text("", font, 38); text.setStyle(Text::Bold); Text text2("", font, 38); text2.setStyle(Text::Bold); Text text3("", font, 38); text3.setStyle(Text::Bold); text.setString("New Game"); text2.setString("Load"); text3.setString("Exit"); text.setPosition(485, 410); text2.setPosition(550, 450); text3.setPosition(550,568); while(isMenu) { text.setColor(Color(254,150,121)); text2.setColor(Color(254,150,121)); text3.setColor(Color(254,150,121)); menuNum = 0; window.clear(Color(129,181,221)); //New Game if(IntRect(500,410,200,60).contains(Mouse::getPosition(window))) { text.setColor(Color(98,198,223)); menuNum = 1; } //Load Game if(IntRect(550,488,200,60).contains(Mouse::getPosition(window))) { text2.setColor(Color(98,198,223)); menuNum = 2; } //Exit if(IntRect(500,564,200,60).contains(Mouse::getPosition(window))) { text3.setColor(Color(98,198,223)); menuNum = 3; } if(Mouse::isButtonPressed(Mouse::Left)) { if(menuNum == 1) { music.stop(); return; } if(menuNum == 2) { window.draw(menuLoad); window.display(); while(!Keyboard::isKeyPressed(Keyboard::Escape)) {;} } if(menuNum == 3) { music.stop(); window.close(); isMenu = false; } } window.draw(menuBg); window.draw(text); window.draw(text2); window.draw(text3); window.display(); } }
int main() { // Creates the window to show your game RenderWindow *window; window = new RenderWindow(VideoMode(800, 600),"Ping Pong"); window->setFramerateLimit (25); Sprite *background = new Sprite(); // a pointer for sprite Texture bg; // bgtex to store the texture if(!bg.loadFromFile("assets/background.png")) // Loads image as texture. Image must at least be 610 x 600 std::cout<<"\nError loading image"; else background->setTexture (bg); // you set the texture to the sprite // Use setTextureRect() function to set the texture to some of the window background->setTextureRect (IntRect (0, 0, 610, 600)); //Initialize the game objects onCreate (); // The Game Loop while (window->isOpen ()) { // check all the window's events that were triggered since the last iteration of the loop Event event; while (window->pollEvent (event)) { //Window is closed or 'Esc' key is pressed if (event.type == Event::Closed || (event.type == Event::KeyPressed && event.key.code == Keyboard::Escape)) window->close (); } //checks User input InputHandler (window); //update positions,scores etc. GameUpdate (); //perform AI operations AIOperation (); //Clears the window every frame to render updated positions. MUST DO window->clear (sf::Color::White); //Draw the background image window->draw (*background); //Draw everything else here Display (window); //Check score ScoreManager (window); if (ResultManager (window) ) onEnd (); //Display everything on the Window window->display(); } //free memory delete background; delete window; return 0; }