project-kyoku/src/application.cpp

115 lines
2.8 KiB
C++

#include "application.h"
#include "game/inputtype.h"
#include "classicgame/classicgame.h"
#include "classicgame/classicgraphicsmanager.h"
#include "gui/mainmenu.h"
#include "gui/gamestate.h"
#include "gui/editor.h"
#include "tools/musicsfml.h"
#include <iostream>
const sf::Time TIME_PER_FRAME = sf::seconds(1.f / 90.f);
Application::Application() :
_game_window({1280, 720}, "Test", sf::Style::Default)
{
_font_holder.load(Fonts::Id::GUI, "SourceCodePro-Regular.ttf");
_game = std::make_unique<ClassicGame>(std::make_unique<ClassicGraphicsManager>(_game_window), std::make_unique<MusicSFML>());
_game_window.setFramerateLimit(60);
_game_window.setKeyRepeatEnabled(false);
_game_window.setMouseCursorGrabbed(false);
_game_window.setVerticalSyncEnabled(true);
MainMenu::Callbacks callbacks = {[&](){ pushState(GUIState::Tag::EDITOR); }};
Editor::Callbacks editor_callbacks = {[&](){ popState(); }};
const auto main_menu = std::make_shared<MainMenu>(_game_window, std::move(callbacks), _font_holder);
const auto game_state = std::make_shared<GameState>(_game_window, _game, GameState::Callbacks());
const auto editor = std::make_shared<Editor>(_game_window, std::move(editor_callbacks), std::make_unique<MusicSFML>(), _font_holder);
_states[GUIState::Tag::MAIN_MENU] = main_menu;
_states[GUIState::Tag::GAME] = game_state;
_states[GUIState::Tag::EDITOR] = editor;
_state_stack.emplace_back(_states.at(GUIState::Tag::MAIN_MENU));
}
void Application::run()
{
_game_window.display();
exec();
}
void Application::exec()
{
sf::Clock timer;
sf::Time time_since_last_update = sf::Time::Zero;
while (_game_window.isOpen())
{
time_since_last_update += timer.restart();
input();
bool isOneFramePassed = time_since_last_update >= TIME_PER_FRAME;
if (isOneFramePassed)
{
time_since_last_update -= TIME_PER_FRAME;
update();
draw();
}
}
}
void Application::input()
{
sf::Event event;
while (_game_window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
_game_window.close();
break;
default:
_state_stack.back()->input(event);
break;
}
}
}
void Application::update()
{
_state_stack.back()->update();
}
void Application::draw()
{
_game_window.clear();
for (const auto& state : _state_stack)
state->draw();
_game_window.display();
}
void Application::pushState(GUIState::Tag new_state)
{
_state_stack.back()->leave();
_state_stack.emplace_back(_states.at(new_state));
_state_stack.back()->enter();
}
void Application::popState()
{
_state_stack.back()->leave();
_state_stack.pop_back();
_state_stack.back()->enter();
}