From a8804d096bb70ea713cac6176d79b510529d739d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dag-Erling=20Sm=C3=B8rgrav?= Date: Tue, 19 Oct 2021 10:07:57 +0200 Subject: [PATCH] Ex 25: Implement pelletClosestToPacman(). --- lib/PacManAI.cpp | 11 +++++++---- test/testPacmanAI.cpp | 1 + 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/PacManAI.cpp b/lib/PacManAI.cpp index 4688b15..9168ab7 100644 --- a/lib/PacManAI.cpp +++ b/lib/PacManAI.cpp @@ -16,10 +16,13 @@ Direction PacManAI::suggestedDirection() const { // This function is not yet implemented. // You will implement it as part of module 25. -GridPosition PacManAI::pelletClosestToPacman(GridPosition, - std::vector &) { - - return {0, 0}; +GridPosition PacManAI::pelletClosestToPacman(GridPosition position, + std::vector & pellets) { + if (pellets.empty()) + return { 0, 0 }; + return *std::min_element(pellets.begin(), pellets.end(), [position](GridPosition a, GridPosition b) { + return positionDistance(a, position) < positionDistance(b, position); + }); } // This function is not yet implemented. diff --git a/test/testPacmanAI.cpp b/test/testPacmanAI.cpp index 4d429fb..4e9e609 100644 --- a/test/testPacmanAI.cpp +++ b/test/testPacmanAI.cpp @@ -7,6 +7,7 @@ TEST_CASE("Find pellet closest to PacMan", "[AI]") { PacManAI AI; using TestData = std::tuple, GridPosition>; auto data = GENERATE( + TestData{{5, 5}, {}, {0, 0}}, TestData{{5, 5}, {{5, 6}}, {5, 6}}, TestData{{5, 5}, {{5, 5}}, {5, 5}}, TestData{{5, 5}, {{0, 0}, {5, 6}}, {5, 6}},