pacman/lib/PacMan.cpp

72 lines
1.9 KiB
C++
Raw Normal View History

#include "PacMan.hpp"
PacMan::PacMan(const Board & board)
: pos(board.initialPacManPosition()) {}
2020-11-27 13:10:09 +00:00
SDL_Point PacMan::currentSprite() const {
2020-11-28 12:04:14 +00:00
return pacManAnimation.animationFrame(direction);
2020-11-27 13:10:09 +00:00
}
Position PacMan::position() const {
2020-11-27 13:10:09 +00:00
return pos;
}
void PacMan::update(std::chrono::milliseconds time_delta, InputState state, const Board & board) {
setDirection(state);
updateAnimationPosition(time_delta);
updateMazePosition(time_delta, board);
}
void PacMan::setDirection(const InputState & state) {
if (state.left)
2020-11-27 16:01:27 +00:00
desired_direction = Direction::LEFT;
2020-11-27 13:10:09 +00:00
else if (state.right)
2020-11-27 16:01:27 +00:00
desired_direction = Direction::RIGHT;
2020-11-27 13:10:09 +00:00
else if (state.up)
2020-11-27 16:01:27 +00:00
desired_direction = Direction::UP;
2020-11-27 13:10:09 +00:00
else if (state.down)
2020-11-27 16:01:27 +00:00
desired_direction = Direction::DOWN;
2020-11-27 13:10:09 +00:00
}
void PacMan::updateAnimationPosition(std::chrono::milliseconds time_delta) {
2020-11-28 12:04:14 +00:00
pacManAnimation.updateAnimationPosition(time_delta);
2020-11-27 13:10:09 +00:00
}
void PacMan::updateMazePosition(std::chrono::milliseconds time_delta, const Board & board) {
2021-06-16 11:18:05 +00:00
float position_delta = time_delta.count() / 128.0;
2020-11-27 13:10:09 +00:00
// Handle teleport
if (pos.x >= COLUMNS - 1 && direction == Direction::RIGHT) {
pos.x = -1;
} else if (pos.x <= 0 && direction == Direction::LEFT) {
pos.x = COLUMNS;
}
else if (board.isWalkable(pos, position_delta, desired_direction)) {
2020-11-27 16:01:27 +00:00
direction = desired_direction;
}
2020-11-27 13:10:09 +00:00
if (board.isWalkable(pos, position_delta, direction)) {
switch (direction) {
case Direction::NONE:
break;
case Direction::LEFT:
pos.x -= position_delta;
pos.y = floor(pos.y);
break;
case Direction::RIGHT:
pos.x += position_delta;
pos.y = floor(pos.y);
break;
case Direction::UP:
pos.x = floor(pos.x);
pos.y -= position_delta;
break;
case Direction::DOWN:
pos.x = floor(pos.x);
pos.y += position_delta;
break;
}
}
}