sliding-puzzle/application.cpp

128 lines
2.6 KiB
C++
Raw Normal View History

2020-12-13 13:45:52 -05:00
#include <SFML/Window/Event.hpp>
#include <SFML/System/Time.hpp>
2020-12-13 13:45:52 -05:00
#include "application.h"
2020-12-14 14:22:52 -05:00
// Hardcoded for now
2020-12-13 13:45:52 -05:00
const sf::Time TIME_PER_SECOND = sf::seconds(1.f / 60.f);
2020-12-20 08:49:24 -05:00
Application::Application(unsigned int window_width, unsigned int window_height) :
2021-01-08 16:14:28 -05:00
current_state(STATE::PLAY),
2020-12-20 08:49:24 -05:00
render_window({window_width, window_height}, "Sliding Puzzle")
2020-12-13 13:45:52 -05:00
{}
2020-12-18 15:12:28 -05:00
bool Application::init(const std::string &path, int splitting)
2020-12-13 13:45:52 -05:00
{
render_window.setFramerateLimit(60);
2020-12-20 08:49:24 -05:00
return board.init(path, splitting, render_window);
}
2020-12-13 13:45:52 -05:00
void Application::run()
{
2020-12-14 14:22:52 -05:00
// Main game cycle
render_window.display();
2020-12-13 13:45:52 -05:00
while (render_window.isOpen())
{
processInput();
draw();
}
}
void Application::draw()
{
render_window.clear();
board.draw(render_window);
render_window.display();
}
2020-12-14 14:22:52 -05:00
void Application::processInput()
2020-12-13 13:45:52 -05:00
{
sf::Event event;
while (render_window.pollEvent(event))
2021-01-08 16:14:28 -05:00
{
switch (current_state)
2020-12-13 13:45:52 -05:00
{
2021-01-08 16:14:28 -05:00
case STATE::PLAY:
onGameState(event);
2020-12-13 13:45:52 -05:00
break;
2021-01-08 16:14:28 -05:00
case STATE::WIN:
onWinState(event);
2020-12-13 13:45:52 -05:00
break;
}
}
}
2021-01-08 16:14:28 -05:00
void Application::onGameState(sf::Event& event)
{
switch (event.type)
{
case sf::Event::Closed:
render_window.close();
break;
case sf::Event::KeyPressed:
// Go to selection mode
if (event.key.code == sf::Keyboard::Z)
board.onSelectionMode();
else // if it wasn't selection mode, then try to handle direction
board.moveSelection(getDirection(event.key.code));
break;
default: // otherwise - do nothing
break;
}
if (board.isWinCondition())
{
current_state = STATE::WIN;
board.setCursorVisibility(false);
}
}
void Application::onWinState(sf::Event& event)
{
switch (event.type)
{
case sf::Event::Closed:
render_window.close();
break;
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Z)
render_window.close();
break;
default:
break;
}
}
2020-12-13 13:45:52 -05:00
DIRECTION Application::getDirection(sf::Keyboard::Key &key) const
{
switch (key)
{
case sf::Keyboard::A:
case sf::Keyboard::Left:
case sf::Keyboard::Num4:
return DIRECTION::LEFT;
case sf::Keyboard::W:
case sf::Keyboard::Up:
case sf::Keyboard::Num8:
return DIRECTION::UP;
case sf::Keyboard::D:
case sf::Keyboard::Right:
case sf::Keyboard::Num6:
return DIRECTION::RIGHT;
case sf::Keyboard::S:
case sf::Keyboard::Down:
case sf::Keyboard::Num2:
return DIRECTION::DOWN;
default:
return DIRECTION::NONE;
}
}