#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include "Maze.hpp"
class Player {
private:
sf::Sprite player;
sf::Vector2f position;
sf::Texture texture;
float speed;
public:
Player(sf::Color color, const std::string &texturePath, float speed, float scale, sf::Vector2f position = sf::Vector2f(0,0));
sf::Rect<float> getGlobalBounds();
sf::Vector2f getPosition();
void setPosition(sf::Vector2f position);
void draw(sf::RenderWindow *window);
void move(Maze *maze, float deltaSpeed = 1);
bool locationAllowed(Maze *maze, sf::Vector2f position, const char &direction);
};
const char UP = 'U';
const char DOWN = 'D';
const char LEFT = 'L';
const char RIGHT = 'R';
Player:: Player(sf::Color color, const std::string &texturePath, float speed, float scale, sf::Vector2f position) {
if (this->texture.loadFromFile(texturePath)) {
this->player.setTexture(texture, true);
}
this->player.setColor(color);
this->player.setScale(sf::Vector2<float>(scale, scale));
this->position = position;
this->speed = speed;
}
sf::Vector2f Player::getPosition() {
return this->player.getPosition();
}
void Player::setPosition(sf::Vector2f position) {
this->player.setPosition(position);
this->position = position;
}
sf::Rect<float> Player::getGlobalBounds() {
return this->player.getGlobalBounds();
}
void Player::draw(sf::RenderWindow *window) {
window->draw(this->player);
}
void Player::move(Maze *maze, float deltaTime) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && locationAllowed(maze, position, UP)) {
this->position += sf::Vector2f(0, -speed * deltaTime);
this->player.move(0, -speed * deltaTime);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && locationAllowed(maze, position, DOWN)) {
this->position += sf::Vector2f(0, speed * deltaTime);
this->player.move(0, speed * deltaTime);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && locationAllowed(maze, position, LEFT)) {
this->position += sf::Vector2f(-speed * deltaTime, 0);
this->player.move(-speed * deltaTime, 0);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right) && locationAllowed(maze, position, RIGHT)) {
this->position += sf::Vector2f(speed * deltaTime, 0);
this->player.move(speed * deltaTime, 0);
}
}
bool Player:: locationAllowed(Maze *maze, sf::Vector2f position, const char &direction) {
bool allowed = false;
Cell *aux;
switch (direction) {
case UP:
position += sf::Vector2f(0.f, 1.f);
aux = maze->getCell(position);
if (aux)
allowed = (aux->getActiveWalls() != UP_WALL);
break;
case DOWN:
position += sf::Vector2f(0.f, -1.f);
aux = maze->getCell(position);
if (aux)
allowed = (aux->getActiveWalls() != DOWN_WALL);
break;
case LEFT:
position += sf::Vector2f(-1.f, 0.f);
aux = maze->getCell(position);
if (aux)
allowed = (aux->getActiveWalls() != LEFT_WALL);
break;
case RIGHT:
position += sf::Vector2f(1.f, 0.f);
aux = maze->getCell(position);
if (aux)
allowed = (aux->getActiveWalls() != RIGHT_WALL);
break;
}
return allowed;
}