Skip to content

Commit

Permalink
Preserve the order of artifacts when adding the Spell Book to the art…
Browse files Browse the repository at this point in the history
…ifacts bag (#9096)
  • Loading branch information
oleg-derevenetz authored Sep 10, 2024
1 parent 1146cc4 commit 9b91dae
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/fheroes2/resource/artifact.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iterator>
#include <map>
#include <ostream>
#include <string>
Expand Down Expand Up @@ -832,24 +833,29 @@ bool BagArtifacts::PushArtifact( const Artifact & art )
return false;
}

// There should not be more than one Magic Book in the artifact bag at a time.
if ( art.GetID() == Artifact::MAGIC_BOOK && isPresentArtifact( art ) ) {
// We add a magic book while adding a hero on the map.
// In case if a map creator set Magic Book to be an artifact of the hero we face two Magic Books situation.
return false;
}

iterator it = std::find( begin(), end(), Artifact( Artifact::UNKNOWN ) );
if ( it == end() ) {
const auto firstEmptySlotIter = std::find( begin(), end(), Artifact( Artifact::UNKNOWN ) );
if ( firstEmptySlotIter == end() ) {
return false;
}

*it = art;
// If the artifact to add is not a Magic Book, then just use the first empty slot.
if ( art.GetID() != Artifact::MAGIC_BOOK ) {
*firstEmptySlotIter = art;

// Always put Magic Book at first place.
if ( art.GetID() == Artifact::MAGIC_BOOK ) {
std::swap( *it, front() );
return true;
}

// Otherwise, we should first shift the existing artifacts (if any) from left to right...
std::move_backward( begin(), firstEmptySlotIter, std::next( firstEmptySlotIter ) );

// ... and then put the Magic Book to the first slot of the artifact bag.
front() = art;

return true;
}

Expand Down

0 comments on commit 9b91dae

Please sign in to comment.