epr24pr42-ojanssen2/Player.cpp
2025-01-19 18:20:22 +01:00

108 lines
2.8 KiB
C++

#include "Entities/Player.h"
#include "../Environment/Maze.h"
#include "MovementNotPossible.h"
#include "GameState.h"
#include "Game.h"
using game::GameState;
using game::Game;
using game_exceptions::MovementNotPossible;
namespace game
{
Player::Player(const int target_x, const int target_y): pos(target_x, target_y), keys_in_inventory(0)
{
}
Player::Player(const Vector2d pos) : pos(pos), keys_in_inventory(0)
{
}
Vector2d Player::get_pos() const
{
return this->pos;
}
void Player::update_position(const Vector2d& target)
{
this->pos = target;
}
Maze Player::handle_move(Maze& maze, const Vector2d& move_vector)
{
const Vector2d target_position = Vector2d(this->get_pos().x + move_vector.x,
this->get_pos().y + move_vector.y);
if (maze.is_pos_free(target_position, this->has_key_available()))
{
this->update_position(target_position);
}
else
throw MovementNotPossible("Bewegung nicht moeglich!");
return maze;
}
Maze Player::handle_user_input(Maze& maze, const char& input) {
Vector2d move_vector = {0, 0};
switch (input) {
case 'w':
move_vector = {0, -1};
break;
case 's':
move_vector = {0, 1};
break;
case 'a':
move_vector = {-1, 0};
break;
case 'd':
move_vector = {1, 0};
break;
}
this->handle_move(maze, move_vector);
return maze;
}
void Player::handle_keys(Maze& maze) {
switch (maze.get_field(this->pos))
{
case 'K':
++this->keys_in_inventory;
maze.update_field(this->get_pos(), '.');
break;
case 'T':
--this->keys_in_inventory;
maze.update_field(this->get_pos(), '.');
break;
default: ;
}
}
GameState Player::handle_collisions(const Game& game, const Maze& maze) const {
char field_at_pos = maze.get_field(this->get_pos());
// Game state sanity check
if (game.get_state() != GameState::RUNNING)
return game.get_state();
if (field_at_pos == '.'){
if (game.is_enemy_at_pos(this->get_pos()))
return GameState::HIT_BY_GHOST;
return GameState::RUNNING;
}
// You are not supposed to be here!
return game.get_state();
}
GameState Player::tick(const Game& game, Maze& maze) {
this->handle_keys(maze);
return this->handle_collisions(game, maze);
}
bool Player::has_key_available() const
{
return this->keys_in_inventory > 0;
}
} // game