Add some AI tests

This commit is contained in:
Corentin Jabot 2021-10-05 13:42:56 +02:00
parent 82157dd701
commit c6d13a046a
3 changed files with 42 additions and 7 deletions

View file

@ -15,15 +15,15 @@ Direction PacManAI::suggestedDirection() const {
}
GridPosition PacManAI::pelletClosestToPacman(GridPosition pacmanGridPosition,
const Pellets & pellets) {
auto pelletPositions = pellets.allPellets();
std::vector<GridPosition> & pellets) {
auto pelletSort = [&pacmanGridPosition](GridPosition pelletA, GridPosition pelletB) {
double distanceA = positionDistance(pacmanGridPosition, pelletA);
double distanceB = positionDistance(pacmanGridPosition, pelletB);
return distanceA < distanceB;
};
std::sort(pelletPositions.begin(), pelletPositions.end(), pelletSort);
return pelletPositions[0];
std::sort(pellets.begin(), pellets.end(), pelletSort);
return pellets[0];
}
bool PacManAI::isValidMove(const Move & move) {
@ -56,12 +56,12 @@ void PacManAI::update(const PacMan & pacMan, const Pellets & pellets) {
return;
}
const auto & pelletPositions = pellets.allPellets();
auto pelletPositions = pellets.allPellets();
if (pelletPositions.empty()) {
return;
}
const GridPosition targetPos = pelletClosestToPacman(pacManGridPos, pellets);
const GridPosition targetPos = pelletClosestToPacman(pacManGridPos, pelletPositions);
const GridPosition currentPosition = pacMan.positionInGrid();
const auto [x, y] = currentPosition;

View file

@ -22,7 +22,7 @@ public:
void update(const PacMan & pacMan, const Pellets & pellets);
Direction suggestedDirection() const;
GridPosition pelletClosestToPacman(GridPosition pacmanGridPosition,
const Pellets & pellets);
std::vector<GridPosition> & pellets);
bool isValidMove(const Move & move);
Direction optimalDirection(const std::array<Move, 4> & moves);
void reset();

35
test/testPacmanAI.cpp Normal file
View file

@ -0,0 +1,35 @@
#include <catch2/catch.hpp>
#include <PacManAI.hpp>
TEST_CASE("find pellet closest to pacman", "[AI]") {
using namespace pacman;
PacManAI AI;
using TestData = std::tuple<GridPosition, std::vector<GridPosition>, GridPosition>;
auto data = GENERATE(
TestData{{5, 5}, {{5, 6}}, {5, 6}},
TestData{{5, 5}, {{5, 5}}, {5, 5}},
TestData{{5, 5}, {{0, 0}, {5, 6}}, {5, 6}},
TestData{{5, 5}, {{6, 5}, {5, 6}}, {6, 5}},
TestData{{5, 5}, {{6, 6}, {5, 6}}, {5, 6}}
);
CHECK(AI.pelletClosestToPacman(std::get<0>(data), std::get<1>(data)) == std::get<2>(data));
}
TEST_CASE("Is valid move", "[AI]") {
using namespace pacman;
using TestData = std::tuple<PacManAI::Move, bool>;
auto data = GENERATE(
TestData{{Direction::RIGHT, {13, 23}}, true},
TestData{{Direction::LEFT, {13, 23}}, false}, // opposite direction
TestData{{Direction::RIGHT, {13, 22}}, false} // wall
);
PacManAI AI;
CHECK(AI.isValidMove(std::get<0>(data)) == std::get<1>(data));
}
TEST_CASE("is optimal direction", "[AI]") {
using namespace pacman;
using TestData = std::tuple<std::array<PacManAI::Move, 4>, std::size_t>;
}