Eat pellets

This commit is contained in:
Corentin Jabot 2021-06-16 13:59:16 +02:00
parent 2398bf9c36
commit f911f6e2a8
9 changed files with 52 additions and 0 deletions

View File

@ -19,11 +19,18 @@ void Game::run() {
auto time_delta = now() - current_time;
auto milli_delta = std::chrono::duration_cast<std::chrono::milliseconds>(time_delta);
pacMan.update(milli_delta, inputState, board);
eatPellets();
current_time += time_delta;
canvas.update(pacMan, pellets, superPellets);
}
}
void Game::eatPellets() {
const auto pos = pacMan.positionInGrid();
pellets.eatPelletAtPosition(pos);
superPellets.eatPelletAtPosition(pos);
}
void Game::processEvents(InputState & inputState) {
SDL_Event event;
while (SDL_PollEvent(&event)) {

View File

@ -21,6 +21,8 @@ private:
Pellets pellets;
SuperPellets superPellets;
void eatPellets();
static void processEvents(InputState & inputState);
static void keyToggle(const SDL_Event & event, InputState & inputState, bool on);

View File

@ -11,6 +11,20 @@ Position PacMan::position() const {
return pos;
}
Position PacMan::positionInGrid() const {
switch (direction) {
case Direction::LEFT:
case Direction::RIGHT:
return { floor(pos.x), round(pos.y) };
case Direction::UP:
case Direction::DOWN:
return { floor(pos.x), round(pos.y) };
default:
return pos;
}
return pos;
}
void PacMan::update(std::chrono::milliseconds time_delta, InputState state, const Board & board) {
setDirection(state);
updateAnimationPosition(time_delta);

View File

@ -18,6 +18,8 @@ public:
[[nodiscard]] Position position() const;
[[nodiscard]] Position positionInGrid() const;
void update(std::chrono::milliseconds time_delta, InputState state, const Board & board);
private:

View File

@ -1,4 +1,13 @@
#include "Pellets.hpp"
#include <algorithm>
Pellets::Pellets(const Board & board)
: positions(board.initialPelletPositions()) {}
bool Pellets::eatPelletAtPosition(Position p) {
auto it = std::find(positions.begin(), positions.end(), p);
if (it == positions.end())
return false;
positions.erase(it);
return true;
}

View File

@ -17,6 +17,8 @@ public:
return positions;
}
bool eatPelletAtPosition(Position p);
private:
const SDL_Point sprite = { 1, 9 };
std::vector<SDL_Point> positions;

View File

@ -1,6 +1,12 @@
#pragma once
#include <SDL2/SDL_rect.h>
struct Position {
float x;
float y;
};
inline bool operator==(const SDL_Point & b, const Position & a) {
return a.x == b.x && a.y == b.y;
}

View File

@ -2,3 +2,11 @@
SuperPellets::SuperPellets(const Board & board)
: positions(board.initialSuperPelletPositions()) {}
bool SuperPellets::eatPelletAtPosition(Position p) {
auto it = std::find(positions.begin(), positions.end(), p);
if (it == positions.end())
return false;
positions.erase(it);
return true;
}

View File

@ -17,6 +17,8 @@ public:
return positions;
}
bool eatPelletAtPosition(Position p);
private:
const SDL_Point sprite = { 0, 9 };
std::vector<SDL_Point> positions;